file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/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 v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IVeANGLE.sol";
import "./interfaces/IFeeDistributor.sol";
import "./interfaces/IAngleGaugeController.sol";
/// @title AngleLocker
/// @author StakeDAO
/// @notice Locks the ANGLE tokens to veANGLE contract
contract AngleLocker {
using SafeERC20 for IERC20;
using Address for address;
/* ========== STATE VARIABLES ========== */
address public governance;
address public angleDepositor;
address public accumulator;
address public constant angle = address(0x31429d1856aD1377A8A0079410B297e1a9e214c2);
address public constant veAngle = address(0x0C462Dbb9EC8cD1630f1728B2CFD2769d09f0dd5);
address public feeDistributor = address(0x7F82ff050128e29Fd89D85d01b93246F744E62A0);
address public gaugeController = address(0x9aD7e7b0877582E14c17702EecF49018DD6f2367);
/* ========== EVENTS ========== */
event LockCreated(address indexed user, uint256 value, uint256 duration);
event TokenClaimed(address indexed user, uint256 value);
event Voted(uint256 _voteId, address indexed _votingAddress, bool _support);
event VotedOnGaugeWeight(address indexed _gauge, uint256 _weight);
event Released(address indexed user, uint256 value);
event GovernanceChanged(address indexed newGovernance);
event AngleDepositorChanged(address indexed newAngleDepositor);
event AccumulatorChanged(address indexed newAccumulator);
event FeeDistributorChanged(address indexed newFeeDistributor);
event GaugeControllerChanged(address indexed newGaugeController);
/* ========== CONSTRUCTOR ========== */
constructor(address _accumulator) {
governance = msg.sender;
accumulator = _accumulator;
IERC20(angle).approve(veAngle, type(uint256).max);
}
/* ========== MODIFIERS ========== */
modifier onlyGovernance() {
require(msg.sender == governance, "!gov");
_;
}
modifier onlyGovernanceOrAcc() {
require(msg.sender == governance || msg.sender == accumulator, "!(gov||acc)");
_;
}
modifier onlyGovernanceOrDepositor() {
require(msg.sender == governance || msg.sender == angleDepositor, "!(gov||proxy||AngleDepositor)");
_;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/// @notice Creates a lock by locking ANGLE token in the veAngle contract for the specified time
/// @dev Can only be called by governance or proxy
/// @param _value The amount of token to be locked
/// @param _unlockTime The duration for which the token is to be locked
function createLock(uint256 _value, uint256 _unlockTime) external onlyGovernanceOrDepositor {
IVeANGLE(veAngle).create_lock(_value, _unlockTime);
emit LockCreated(msg.sender, _value, _unlockTime);
}
/// @notice Increases the amount of ANGLE locked in veANGLE
/// @dev The ANGLE needs to be transferred to this contract before calling
/// @param _value The amount by which the lock amount is to be increased
function increaseAmount(uint256 _value) external onlyGovernanceOrDepositor {
IVeANGLE(veAngle).increase_amount(_value);
}
/// @notice Increases the duration for which ANGLE is locked in veANGLE for the user calling the function
/// @param _unlockTime The duration in seconds for which the token is to be locked
function increaseUnlockTime(uint256 _unlockTime) external onlyGovernanceOrDepositor {
IVeANGLE(veAngle).increase_unlock_time(_unlockTime);
}
/// @notice Claim the token reward from the ANGLE fee Distributor passing the token as input parameter
/// @param _recipient The address which will receive the claimed token reward
function claimRewards(address _token, address _recipient) external onlyGovernanceOrAcc {
uint256 claimed = IFeeDistributor(feeDistributor).claim();
emit TokenClaimed(_recipient, claimed);
IERC20(_token).safeTransfer(_recipient, claimed);
}
/// @notice Withdraw the ANGLE from veANGLE
/// @dev call only after lock time expires
/// @param _recipient The address which will receive the released ANGLE
function release(address _recipient) external onlyGovernanceOrDepositor {
IVeANGLE(veAngle).withdraw();
uint256 balance = IERC20(angle).balanceOf(address(this));
IERC20(angle).safeTransfer(_recipient, balance);
emit Released(_recipient, balance);
}
/// @notice Vote on Angle Gauge Controller for a gauge with a given weight
/// @param _gauge The gauge address to vote for
/// @param _weight The weight with which to vote
function voteGaugeWeight(address _gauge, uint256 _weight) external onlyGovernance {
IAngleGaugeController(gaugeController).vote_for_gauge_weights(_gauge, _weight);
emit VotedOnGaugeWeight(_gauge, _weight);
}
function setGovernance(address _governance) external onlyGovernance {
governance = _governance;
emit GovernanceChanged(_governance);
}
function setAngleDepositor(address _angleDepositor) external onlyGovernance {
angleDepositor = _angleDepositor;
emit AngleDepositorChanged(_angleDepositor);
}
function setFeeDistributor(address _newYD) external onlyGovernance {
feeDistributor = _newYD;
emit FeeDistributorChanged(_newYD);
}
function setGaugeController(address _gaugeController) external onlyGovernance {
gaugeController = _gaugeController;
emit GaugeControllerChanged(_gaugeController);
}
function setAccumulator(address _accumulator) external onlyGovernance {
accumulator = _accumulator;
emit AccumulatorChanged(_accumulator);
}
/// @notice execute a function
/// @param to Address to sent the value to
/// @param value Value to be sent
/// @param data Call function data
function execute(
address to,
uint256 value,
bytes calldata data
) external onlyGovernanceOrDepositor returns (bool, bytes memory) {
(bool success, bytes memory result) = to.call{ value: value }(data);
return (success, result);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IAngleGaugeController {
function vote_for_gauge_weights(address, uint256) external;
function vote(
uint256,
bool,
bool
) external; //voteId, support, executeIfDecided
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IFeeDistributor {
function claim() external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IVeANGLE {
struct LockedBalance {
int128 amount;
uint256 end;
}
function create_lock(uint256 _value, uint256 _unlock_time) external;
function increase_amount(uint256 _value) external;
function increase_unlock_time(uint256 _unlock_time) external;
function withdraw() external;
}
|
========== STATE VARIABLES ========== */ ========== EVENTS ========== */ ========== CONSTRUCTOR ========== */
|
constructor(address _accumulator) {
governance = msg.sender;
accumulator = _accumulator;
IERC20(angle).approve(veAngle, type(uint256).max);
}
| 14,538,775 |
[
1,
1432,
631,
7442,
22965,
55,
422,
1432,
342,
422,
1432,
9964,
55,
422,
1432,
342,
422,
1432,
3492,
13915,
916,
422,
1432,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
12316,
12,
2867,
389,
8981,
18514,
13,
288,
203,
202,
202,
75,
1643,
82,
1359,
273,
1234,
18,
15330,
31,
203,
202,
202,
8981,
18514,
273,
389,
8981,
18514,
31,
203,
202,
202,
45,
654,
39,
3462,
12,
4341,
2934,
12908,
537,
12,
537,
8467,
16,
618,
12,
11890,
5034,
2934,
1896,
1769,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xcb6c2FF1E9E2f54AFeeFe4EBd5EF5e6b8a18C720/sources/ISS.sol
|
capture the contract's current ETH balance. this is so that we can capture exactly the amount of ETH that the swap creates, and not make the fee events include any ETH that has been manually sent to the contract swap tokens for ETH for shills/buybacks/dev send to the buyback wallet
|
function swapAndRedirectEthFees(uint256 contractTokenBalance) private lockTheSwap {
uint256 initialBalance = address(this).balance;
swapTokensForEth(contractTokenBalance);
uint256 newBalance = address(this).balance.sub(initialBalance);
if (newBalance > 0) {
sendEthToFeeWallet(newBalance);
emit OnSwapAndRedirectEthFees(contractTokenBalance, newBalance);
}
}
| 2,987,652 |
[
1,
19250,
326,
6835,
1807,
783,
512,
2455,
11013,
18,
333,
353,
1427,
716,
732,
848,
7477,
8950,
326,
3844,
434,
512,
2455,
716,
326,
7720,
3414,
16,
471,
486,
1221,
326,
14036,
2641,
2341,
1281,
512,
2455,
716,
711,
2118,
10036,
3271,
358,
326,
6835,
7720,
2430,
364,
512,
2455,
364,
699,
737,
87,
19,
70,
9835,
823,
87,
19,
5206,
1366,
358,
326,
30143,
823,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7720,
1876,
5961,
41,
451,
2954,
281,
12,
11890,
5034,
6835,
1345,
13937,
13,
3238,
2176,
1986,
12521,
288,
203,
3639,
2254,
5034,
2172,
13937,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
203,
3639,
7720,
5157,
1290,
41,
451,
12,
16351,
1345,
13937,
1769,
203,
203,
3639,
2254,
5034,
394,
13937,
273,
1758,
12,
2211,
2934,
12296,
18,
1717,
12,
6769,
13937,
1769,
203,
203,
3639,
309,
261,
2704,
13937,
405,
374,
13,
288,
203,
203,
5411,
1366,
41,
451,
774,
14667,
16936,
12,
2704,
13937,
1769,
203,
203,
5411,
3626,
2755,
12521,
1876,
5961,
41,
451,
2954,
281,
12,
16351,
1345,
13937,
16,
394,
13937,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.12;
// @author Authereum, Inc.
/**
* @title AccountStateV1
* @author Authereum, Inc.
* @dev This contract holds the state variables used by the account contracts.
* @dev This abscraction exists in order to retain the order of the state variables.
*/
contract AccountStateV1 {
uint256 public lastInitializedVersion;
mapping(address => bool) public authKeys;
uint256 public nonce;
uint256 public numAuthKeys;
}
// File: contracts/account/state/AccountState.sol
pragma solidity 0.5.12;
/**
* @title AccountState
* @author Authereum, Inc.
* @dev This contract holds the state variables used by the account contracts.
* @dev This exists as the main contract to hold state. This contract is inherited
* @dev by Account.sol, which will not care about state as long as it inherits
* @dev AccountState.sol. Any state variable additions will be made to the various
* @dev versions of AccountStateVX that this contract will inherit.
*/
contract AccountState is AccountStateV1 {}
// File: contracts/account/event/AccountEvent.sol
pragma solidity 0.5.12;
/**
* @title AccountEvent
* @author Authereum, Inc.
* @dev This contract holds the events used by the Authereum contracts.
* @dev This abscraction exists in order to retain the order to give initialization functions
* @dev access to events.
* @dev This contract can be overwritten with no changes to the upgradeability.
*/
contract AccountEvent {
/**
* BaseAccount.sol
*/
event FundsReceived(address indexed sender, uint256 indexed value);
event AddedAuthKey(address indexed authKey);
event RemovedAuthKey(address indexed authKey);
event SwappedAuthKeys(address indexed oldAuthKey, address indexed newAuthKey);
// Invalid Sigs
event InvalidAuthkey();
event InvalidTransactionDataSigner();
// Invalid Tx
event CallFailed(bytes32 encodedData);
/**
* AccountUpgradeability.sol
*/
event Upgraded(address indexed implementation);
}
// File: contracts/account/initializer/AccountInitializeV1.sol
pragma solidity 0.5.12;
/**
* @title AccountInitializeV1
* @author Authereum, Inc.
* @dev This contract holds the initialize function used by the account contracts.
* @dev This abscraction exists in order to retain the order of the initialization functions.
*/
contract AccountInitializeV1 is AccountState, AccountEvent {
/// @dev Initialize the Authereum Account
/// @param _authKey authKey that will own this account
function initializeV1(
address _authKey
)
public
{
require(lastInitializedVersion == 0);
lastInitializedVersion = 1;
// Add self as an authKey
authKeys[_authKey] = true;
numAuthKeys += 1;
emit AddedAuthKey(_authKey);
}
}
// File: contracts/account/initializer/AccountInitialize.sol
pragma solidity 0.5.12;
/**
* @title AccountInitialize
* @author Authereum, Inc.
* @dev This contract holds the intialize functions used by the account contracts.
* @dev This exists as the main contract to hold these functions. This contract is inherited
* @dev by AuthereumAccount.sol, which will not care about initialization functions as long as it inherits
* @dev AccountInitialize.sol. Any initialization function additions will be made to the various
* @dev versions of AccountInitializeVx that this contract will inherit.
*/
contract AccountInitialize is AccountInitializeV1 {}
// File: contracts/interfaces/IERC1271.sol
pragma solidity 0.5.12;
contract IERC1271 {
function isValidSignature(
bytes memory _messageHash,
bytes memory _signature)
public
view
returns (bytes4 magicValue);
}
// File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol
pragma solidity ^0.5.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* (.note) This call _does not revert_ if the signature is invalid, or
* if the signer is otherwise unable to be retrieved. In those scenarios,
* the zero address is returned.
*
* (.warning) `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise)
* be too long), and then calling `toEthSignedMessageHash` on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* [`eth_sign`](https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign)
* JSON-RPC method.
*
* See `recover`.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: solidity-bytes-utils/contracts/BytesLib.sol
/*
* @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;
library BytesLib {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(
bytes storage _preBytes,
bytes memory _postBytes
)
internal
view
returns (bool)
{
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
// File: contracts/account/BaseAccount.sol
pragma solidity 0.5.12;
pragma experimental ABIEncoderV2;
/**
* @title BaseAccount
* @author Authereum, Inc.
* @dev Base account contract. Performs most of the functionality
* @dev of an Authereum account contract.
*/
contract BaseAccount is AccountInitialize, IERC1271 {
using SafeMath for uint256;
using ECDSA for bytes32;
using BytesLib for bytes;
// Include a CHAIN_ID const
uint256 constant CHAIN_ID = 1;
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 constant internal VALID_SIG = 0x20c13b0b;
bytes4 constant internal INVALID_SIG = 0xffffffff;
modifier onlyValidAuthKeyOrSelf {
_validateAuthKey(msg.sender);
_;
}
// This is required for funds sent to this contract
function () external payable {}
/**
* Getters
*/
/// @dev Get the current nonce of the contract
/// @return The nonce of the contract
function getNonce() public view returns (uint256) {
return nonce;
}
/// @dev Get the chain ID constant
/// @return The chain id
function getChainId() public view returns (uint256) {
return CHAIN_ID;
}
/**
* Public functions
*/
/// @dev Execute a transaction
/// @notice This is to be called directly by an AuthKey
/// @param _destination Destination of the transaction
/// @param _value Value of the transaction
/// @param _data Data of the transaction
/// @param _gasLimit Gas limit of the transaction
/// @return Response of the call
function executeTransaction(
address _destination,
uint256 _value,
bytes memory _data,
uint256 _gasLimit
)
public
onlyValidAuthKeyOrSelf
returns (bytes memory)
{
return _executeTransaction(_destination, _value, _data, _gasLimit);
}
/// @dev Add an auth key to the list of auth keys
/// @param _authKey Address of the auth key to add
function addAuthKey(address _authKey) public onlyValidAuthKeyOrSelf {
require(!authKeys[_authKey], "Auth key already added");
authKeys[_authKey] = true;
numAuthKeys += 1;
emit AddedAuthKey(_authKey);
}
/// @dev Add multiple auth keys to the list of auth keys
/// @param _authKeys Array of addresses to add to the auth keys list
function addMultipleAuthKeys(address[] memory _authKeys) public onlyValidAuthKeyOrSelf {
for (uint256 i = 0; i < _authKeys.length; i++) {
addAuthKey(_authKeys[i]);
}
}
/// @dev Remove an auth key from the list of auth keys
/// @param _authKey Address of the auth key to remove
function removeAuthKey(address _authKey) public onlyValidAuthKeyOrSelf {
require(authKeys[_authKey], "Auth key not yet added");
require(numAuthKeys > 1, "Cannot remove last auth key");
authKeys[_authKey] = false;
numAuthKeys -= 1;
emit RemovedAuthKey(_authKey);
}
/// @dev Remove multiple auth keys to the list of auth keys
/// @param _authKeys Array of addresses to remove to the auth keys list
function removeMultipleAuthKeys(address[] memory _authKeys) public onlyValidAuthKeyOrSelf {
for (uint256 i = 0; i < _authKeys.length; i++) {
removeAuthKey(_authKeys[i]);
}
}
/// @dev Swap one authKey for a non-authKey
/// @param _oldAuthKey An existing authKey
/// @param _newAuthKey A non-existing authKey
function swapAuthKeys(
address _oldAuthKey,
address _newAuthKey
)
public
onlyValidAuthKeyOrSelf
{
require(authKeys[_oldAuthKey], "Old auth key does not exist");
require(!authKeys[_newAuthKey], "New auth key already exists");
addAuthKey(_newAuthKey);
removeAuthKey(_oldAuthKey);
emit SwappedAuthKeys(_oldAuthKey, _newAuthKey);
}
/// @dev Swap multiple auth keys to the list of auth keys
/// @param _oldAuthKeys Array of addresses to remove to the auth keys list
/// @param _newAuthKeys Array of addresses to add to the auth keys list
function swapMultipleAuthKeys(
address[] memory _oldAuthKeys,
address[] memory _newAuthKeys
)
public
{
require(_oldAuthKeys.length == _newAuthKeys.length, "Input arrays not equal length");
for (uint256 i = 0; i < _oldAuthKeys.length; i++) {
swapAuthKeys(_oldAuthKeys[i], _newAuthKeys[i]);
}
}
/// @dev Check if a message and signature pair is valid
/// @notice The _signatures parameter can either be one auth key signature or it can
/// @notice be a login key signature and an auth key signature (signed login key)
/// @param _msg Message that was signed
/// @param _signatures Signature(s) of the data. Either a single signature (login) or two (login and auth)
/// @return VALID_SIG or INVALID_SIG hex data
function isValidSignature(
bytes memory _msg,
bytes memory _signatures
)
public
view
returns (bytes4)
{
if (_signatures.length == 65) {
return isValidAuthKeySignature(_msg, _signatures);
} else if (_signatures.length == 130) {
return isValidLoginKeySignature(_msg, _signatures);
} else {
revert("Invalid _signatures length");
}
}
/// @dev Check if a message and auth key signature pair is valid
/// @param _msg Message that was signed
/// @param _signature Signature of the data signed by the authkey
/// @return VALID_SIG or INVALID_SIG hex data
function isValidAuthKeySignature(
bytes memory _msg,
bytes memory _signature
)
public
view
returns (bytes4)
{
address authKeyAddress = _getEthSignedMessageHash(_msg).recover(
_signature
);
if(authKeys[authKeyAddress]) {
return VALID_SIG;
} else {
return INVALID_SIG;
}
}
/// @dev Check if a message and login key signature pair is valid, as well as a signed login key by an auth key
/// @param _msg Message that was signed
/// @param _signatures Signatures of the data. Signed msg data by the login key and signed login key by auth key
/// @return VALID_SIG or INVALID_SIG hex data
function isValidLoginKeySignature(
bytes memory _msg,
bytes memory _signatures
)
public
view
returns (bytes4)
{
bytes memory msgHashSignature = _signatures.slice(0, 65);
bytes memory loginKeyAuthorizationSignature = _signatures.slice(65, 65);
address loginKeyAddress = _getEthSignedMessageHash(_msg).recover(
msgHashSignature
);
bytes32 loginKeyAuthorizationMessageHash = keccak256(abi.encodePacked(
loginKeyAddress
)).toEthSignedMessageHash();
address authorizationSigner = loginKeyAuthorizationMessageHash.recover(
loginKeyAuthorizationSignature
);
if(authKeys[authorizationSigner]) {
return VALID_SIG;
} else {
return INVALID_SIG;
}
}
/**
* Internal functions
*/
/// @dev Validate an authKey
/// @param _authKey Address of the auth key to validate
function _validateAuthKey(address _authKey) internal view {
require(authKeys[_authKey] == true || msg.sender == address(this), "Auth key is invalid");
}
/// @dev Validate signatures from an AuthKeyMetaTx
/// @param _txDataMessageHash Ethereum signed message of the transaction
/// @param _transactionDataSignature Signed tx data
/// @return Address of the auth key that signed the data
function _validateAuthKeyMetaTxSigs(
bytes32 _txDataMessageHash,
bytes memory _transactionDataSignature
)
internal
view
returns (address)
{
address transactionDataSigner = _txDataMessageHash.recover(_transactionDataSignature);
_validateAuthKey(transactionDataSigner);
return transactionDataSigner;
}
/// @dev Validate signatures from an AuthKeyMetaTx
/// @param _txDataMessageHash Ethereum signed message of the transaction
/// @param _transactionDataSignature Signed tx data
/// @param _loginKeyAuthorizationSignature Signed loginKey
/// @return Address of the login key that signed the data
function validateLoginKeyMetaTxSigs(
bytes32 _txDataMessageHash,
bytes memory _transactionDataSignature,
bytes memory _loginKeyAuthorizationSignature
)
public
view
returns (address)
{
address transactionDataSigner = _txDataMessageHash.recover(
_transactionDataSignature
);
bytes32 loginKeyAuthorizationMessageHash = keccak256(abi.encodePacked(
transactionDataSigner
)).toEthSignedMessageHash();
address authorizationSigner = loginKeyAuthorizationMessageHash.recover(
_loginKeyAuthorizationSignature
);
_validateAuthKey(authorizationSigner);
return transactionDataSigner;
}
/// @dev Execute a transaction without a refund
/// @notice This is the transaction sent from the CBA
/// @param _destination Destination of the transaction
/// @param _value Value of the transaction
/// @param _data Data of the transaction
/// @param _gasLimit Gas limit of the transaction
/// @return Response of the call
function _executeTransaction(
address _destination,
uint256 _value,
bytes memory _data,
uint256 _gasLimit
)
internal
returns (bytes memory)
{
(bool success, bytes memory response) = _destination.call.gas(_gasLimit).value(_value)(_data);
if (!success) {
bytes32 encodedData = _encodeData(nonce, _destination, _value, _data);
emit CallFailed(encodedData);
}
// Increment nonce here so that both relayed and non-relayed calls will increment nonce
// Must be incremented after !success data encode in order to encode original nonce
nonce++;
return response;
}
/// @dev Issue a refund
/// @param _startGas Starting gas at the beginning of the transaction
/// @param _gasPrice Gas price to use when sending a refund
function _issueRefund(
uint256 _startGas,
uint256 _gasPrice
)
internal
{
uint256 _gasUsed = _startGas.sub(gasleft());
require(_gasUsed.mul(_gasPrice) <= address(this).balance, "Insufficient gas for refund");
msg.sender.transfer(_gasUsed.mul(_gasPrice));
}
/// @dev Get the gas buffer for each transaction
/// @notice This takes into account the input params as well as the fixed
/// @notice cost of checking if the account has enough gas left as well as the
/// @notice transfer to the relayer
/// @param _txData Input data of the transaction
/// @return Total cost of input data and final require and transfer
function _getGasBuffer(bytes memory _txData) internal view returns (uint256) {
// Input data cost
uint256 costPerByte = 68;
uint256 txDataCost = _txData.length * costPerByte;
// Cost of require and transfer
uint256 costPerCheck = 10000;
return txDataCost.add(costPerCheck);
}
/// @dev Encode data for a failed transaction
/// @param _nonce Nonce of the transaction
/// @param _destination Destination of the transaction
/// @param _value Value of the transaction
/// @param _data Data of the transaction
/// @return Encoded data hash
function _encodeData(
uint256 _nonce,
address _destination,
uint256 _value,
bytes memory _data
)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
_nonce,
_destination,
_value,
_data
));
}
/// @dev Adds ETH signed message prefix to bytes message and hashes it
/// @param _msg Bytes message before adding the prefix
/// @return Prefixed and hashed message
function _getEthSignedMessageHash(bytes memory _msg) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", _uint2str(_msg.length), _msg));
}
/// @dev Convert uint to string
/// @param _num Uint to be converted
/// @return String equivalent of the uint
function _uint2str(uint _num) private pure returns (string memory _uintAsString) {
if (_num == 0) {
return "0";
}
uint i = _num;
uint j = _num;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0) {
bstr[k--] = byte(uint8(48 + i % 10));
i /= 10;
}
return string(bstr);
}
}
// File: contracts/account/LoginKeyMetaTxAccount.sol
pragma solidity 0.5.12;
/**
* @title LoginKeyMetaTxAccount
* @author Authereum, Inc.
* @dev Contract used by login keys to send transactions. Login key firwall checks
* @dev are performed in this contract as well.
*/
contract LoginKeyMetaTxAccount is BaseAccount {
/// @dev Execute an loginKey meta transaction
/// @param _destinations Destinations of the transaction
/// @param _datas Datas of the transaction
/// @param _values Values of the transaction
/// @param _gasLimits Gas limits of the transaction
/// @param _transactionDataSignatures Signed tx datas
/// @param _loginKeyAuthorizationSignature Signed loginKey
/// @return Response of the call
function executeMultipleLoginKeyMetaTx(
address[] memory _destinations,
bytes[] memory _datas,
uint256[] memory _values,
uint256[] memory _gasLimits,
bytes[] memory _transactionDataSignatures,
bytes memory _loginKeyAuthorizationSignature
)
public
returns (bytes[] memory)
{
uint256 startGas = gasleft();
// Verify data length
verifyLoginKeyParamDataLength(
_destinations, _datas, _values, _gasLimits, _transactionDataSignatures
);
// Execute transactions individually
bytes[] memory returnValues = new bytes[](_destinations.length);
for(uint i = 0; i < _destinations.length; i++) {
returnValues[i] = _executeLoginKeyMetaTx(
_destinations[i], _datas[i], _values[i], _gasLimits[i], _transactionDataSignatures[i], _loginKeyAuthorizationSignature
);
}
// Refund gas costs
_issueRefund(startGas, tx.gasprice);
return returnValues;
}
/// @dev Check if a loginKey is valid
/// @param _transactionDataSigner loginKey that signed the tx data
/// @param _loginKeyAuthorizationSignature Signed loginKey
/// @return True if login key is valid
function isValidLoginKey(
address _transactionDataSigner,
bytes memory _loginKeyAuthorizationSignature
)
public
view
returns (bool)
{
bytes32 loginKeyAuthorizationMessageHash = keccak256(abi.encodePacked(
_transactionDataSigner
)).toEthSignedMessageHash();
address authorizationSigner = loginKeyAuthorizationMessageHash.recover(
_loginKeyAuthorizationSignature
);
return authKeys[authorizationSigner];
}
/**
* Internal functions
*/
/// @dev Execute an loginKey meta transaction
/// @param _destination Destination of the transaction
/// @param _data Data of the transaction
/// @param _value Value of the transaction
/// @param _gasLimit Gas limit of the transaction
/// @param _transactionDataSignature Signed tx data
/// @param _loginKeyAuthorizationSignature Signed loginKey
/// @return Response of the call
function _executeLoginKeyMetaTx(
address _destination,
bytes memory _data,
uint256 _value,
uint256 _gasLimit,
bytes memory _transactionDataSignature,
bytes memory _loginKeyAuthorizationSignature
)
internal
returns (bytes memory)
{
uint256 startGas = gasleft();
// Login key cannot upgrade the contract
require(_checkDestination(_destination), "Login key is not able to upgrade to proxy");
bytes32 _txDataMessageHash = keccak256(abi.encodePacked(
address(this),
msg.sig,
CHAIN_ID,
_destination,
_data,
_value,
nonce,
tx.gasprice,
_gasLimit
)).toEthSignedMessageHash();
validateLoginKeyMetaTxSigs(
_txDataMessageHash, _transactionDataSignature, _loginKeyAuthorizationSignature
);
return _executeTransaction(
_destination, _value, _data, _gasLimit
);
}
/// @dev Verify the length of the input data
/// @param _destinations Destinations of the transaction
/// @param _dataArray Data of the transactions
/// @param _values Values of the transaction
/// @param _gasLimits Gas limits of the transaction
/// @param _transactionDataSignatures Signed tx data
function verifyLoginKeyParamDataLength(
address[] memory _destinations,
bytes[] memory _dataArray,
uint256[] memory _values,
uint256[] memory _gasLimits,
bytes[] memory _transactionDataSignatures
)
internal
view
{
require(_destinations.length == _values.length, "Invalid values length");
require(_destinations.length == _dataArray.length, "Invalid dataArray length");
require(_destinations.length == _gasLimits.length, "Invalid gasLimits length");
require(_destinations.length == _transactionDataSignatures.length, "Invalid transactionDataSignatures length");
}
/// @dev Check to see if the destination is self.
/// @notice The login key is not able to upgrade the proxy by transacting with itself.
/// @notice This transaction will throw if an upgrade is attempted
/// @param _destination Destination address
/// @return True if the destination is not self
function _checkDestination(address _destination) internal view returns (bool) {
return (address(this) != _destination);
}
}
// File: contracts/account/AuthKeyMetaTxAccount.sol
pragma solidity 0.5.12;
/**
* @title AuthKeyMetaTxAccount
* @author Authereum, Inc.
* @dev Contract used by auth keys to send transactions.
*/
contract AuthKeyMetaTxAccount is BaseAccount {
/// @dev Execute multiple authKey meta transactiona
/// @param _destinations Destinations of the transaction
/// @param _datas Data of the transactions
/// @param _values Values of the transaction
/// @param _gasLimits Gas limits of the transaction
/// @param _transactionDataSignatures Signed tx data
function executeMultipleAuthKeyMetaTx(
address[] memory _destinations,
bytes[] memory _datas,
uint256[] memory _values,
uint256[] memory _gasLimits,
bytes[] memory _transactionDataSignatures
)
public
returns (bytes[] memory)
{
uint256 startGas = gasleft();
// Verify data length
verifyAuthKeyParamDataLength(
_destinations, _datas, _values, _gasLimits, _transactionDataSignatures
);
// Execute transactions individually
bytes[] memory returnValues = new bytes[](_destinations.length);
for(uint i = 0; i < _destinations.length; i++) {
returnValues[i] = _executeAuthKeyMetaTx(
_destinations[i], _datas[i], _values[i], _gasLimits[i], _transactionDataSignatures[i]
);
}
// Refund gas costs
_issueRefund(startGas, tx.gasprice);
return returnValues;
}
/**
* Internal functions
*/
/// @dev Execute an authKey meta transaction
/// @param _destination Destination of the transaction
/// @param _data Data of the transaction
/// @param _value Value of the transaction
/// @param _gasLimit Gas limit of the transaction
/// @param _transactionDataSignature Signed tx data
/// @return Response of the call
function _executeAuthKeyMetaTx(
address _destination,
bytes memory _data,
uint256 _value,
uint256 _gasLimit,
bytes memory _transactionDataSignature
)
internal
returns (bytes memory)
{
bytes32 _txDataMessageHash = keccak256(abi.encodePacked(
address(this),
msg.sig,
CHAIN_ID,
_destination,
_data,
_value,
nonce,
tx.gasprice,
_gasLimit
)).toEthSignedMessageHash();
// Validate the signer
_validateAuthKeyMetaTxSigs(
_txDataMessageHash, _transactionDataSignature
);
return _executeTransaction(
_destination, _value, _data, _gasLimit
);
}
/// @dev Verify the length of the input data
/// @param _destinations Destinations of the transaction
/// @param _dataArray Data of the transactions
/// @param _values Values of the transaction
/// @param _gasLimits Gas limits of the transaction
/// @param _transactionDataSignatures Signed tx data
function verifyAuthKeyParamDataLength(
address[] memory _destinations,
bytes[] memory _dataArray,
uint256[] memory _values,
uint256[] memory _gasLimits,
bytes[] memory _transactionDataSignatures
)
internal
view
{
require(_destinations.length == _values.length, "Invalid values length");
require(_destinations.length == _dataArray.length, "Invalid dataArray length");
require(_destinations.length == _gasLimits.length, "Invalid gasLimits length");
require(_destinations.length == _transactionDataSignatures.length, "Invalid gasLimits length");
}
}
// File: contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library OpenZeppelinUpgradesAddress {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: contracts/account/AccountUpgradeability.sol
pragma solidity 0.5.12;
/**
* @title AccountUpgradeability
* @author Authereum, Inc.
* @dev The upgradeability logic for an Authereum account.
*/
contract AccountUpgradeability is BaseAccount {
/// @dev Storage slot with the address of the current implementation.
/// @notice This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted
/// @notice by 1, and is validated in the constructor.
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/// Only allow this contract to perform upgrade logic
modifier onlySelf() {
require(address(this) == msg.sender);
_;
}
/// @dev Upgrades the proxy to the newest implementation of a contract and
/// @dev forwards a function call to it.
/// @notice This is useful to initialize the proxied contract.
/// @param _newImplementation Address of the new implementation.
/// @param _data Array of initialize data
function upgradeToAndCall(
address _newImplementation,
bytes memory _data
)
public
onlySelf
{
setImplementation(_newImplementation);
(bool success,) = _newImplementation.delegatecall(_data);
require(success);
emit Upgraded(_newImplementation);
}
/// @dev Sets the implementation address of the proxy.
/// @notice This is only meant to be called when upgrading self
/// @notice The initial setImplementation for a proxy is set during
/// @notice the proxy's initialization, not with this call
/// @param _newImplementation Address of the new implementation.
function setImplementation(address _newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(_newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, _newImplementation)
}
}
}
// File: contracts/account/AuthereumAccount.sol
pragma solidity 0.5.12;
/**
* @title AuthereumAccount
* @author Authereum, Inc.
* @dev Top-level contract used when creating an Authereum account.
* @dev This contract is meant to only hold the version. All other logic is inherited.
*/
contract AuthereumAccount is BaseAccount, LoginKeyMetaTxAccount, AuthKeyMetaTxAccount, AccountUpgradeability {
string constant public authereumVersion = "2019102500";
}
|
@dev Get the gas buffer for each transaction @notice This takes into account the input params as well as the fixed @notice cost of checking if the account has enough gas left as well as the @notice transfer to the relayer @param _txData Input data of the transaction @return Total cost of input data and final require and transfer Input data cost Cost of require and transfer
|
function _getGasBuffer(bytes memory _txData) internal view returns (uint256) {
uint256 costPerByte = 68;
uint256 txDataCost = _txData.length * costPerByte;
uint256 costPerCheck = 10000;
return txDataCost.add(costPerCheck);
}
| 974,981 |
[
1,
967,
326,
16189,
1613,
364,
1517,
2492,
225,
1220,
5530,
1368,
2236,
326,
810,
859,
487,
5492,
487,
326,
5499,
225,
6991,
434,
6728,
309,
326,
2236,
711,
7304,
16189,
2002,
487,
5492,
487,
326,
225,
7412,
358,
326,
1279,
1773,
225,
389,
978,
751,
2741,
501,
434,
326,
2492,
327,
10710,
6991,
434,
810,
501,
471,
727,
2583,
471,
7412,
2741,
501,
6991,
28108,
434,
2583,
471,
7412,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
588,
27998,
1892,
12,
3890,
3778,
389,
978,
751,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
6991,
2173,
3216,
273,
23797,
31,
203,
3639,
2254,
5034,
2229,
751,
8018,
273,
389,
978,
751,
18,
2469,
380,
6991,
2173,
3216,
31,
203,
540,
203,
3639,
2254,
5034,
6991,
2173,
1564,
273,
12619,
31,
203,
3639,
327,
2229,
751,
8018,
18,
1289,
12,
12398,
2173,
1564,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
.*/
pragma solidity ^0.4.8;
import "./ERC20Token.sol";
// NOTE: This token contract is used only for testing, actual PryzeToken contract in other
// repo.
contract PryzeToken is ERC20Token {
// Fancy name: eg Simon Bucks
string public constant name = "Pryze Gold Tokens";
// How many decimals to show. ie. There could 1000 base units with 3 decimals.
// Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
uint8 public constant decimals = 1;
// An identifier: eg SBX
string public constant symbol = "PRYZ";
// Human 0.1 standard. Just an arbitrary versioning scheme.
string public constant version = 'H0.1';
uint constant public TOKEN_COST_PER_SWEEPSTAKES = 1;
function PryzeToken(
uint256 _initialAmount
) ERC20Token(_initialAmount) {
}
}
|
NOTE: This token contract is used only for testing, actual PryzeToken contract in other repo. Fancy name: eg Simon Bucks How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. An identifier: eg SBX Human 0.1 standard. Just an arbitrary versioning scheme.
|
contract PryzeToken is ERC20Token {
string public constant name = "Pryze Gold Tokens";
uint8 public constant decimals = 1;
string public constant symbol = "PRYZ";
string public constant version = 'H0.1';
uint constant public TOKEN_COST_PER_SWEEPSTAKES = 1;
function PryzeToken(
uint256 _initialAmount
.*/
) ERC20Token(_initialAmount) {
}
}
| 6,342,887 |
[
1,
17857,
30,
1220,
1147,
6835,
353,
1399,
1338,
364,
7769,
16,
3214,
453,
1176,
8489,
1345,
6835,
316,
1308,
3538,
18,
478,
12514,
508,
30,
9130,
9587,
265,
605,
9031,
87,
9017,
4906,
15105,
358,
2405,
18,
9228,
18,
6149,
3377,
4336,
1026,
4971,
598,
890,
15105,
18,
21979,
310,
374,
18,
29,
3672,
348,
38,
60,
273,
2468,
3672,
1026,
4971,
18,
2597,
1807,
3007,
17553,
404,
732,
77,
358,
404,
225,
2437,
18,
1922,
2756,
30,
9130,
348,
38,
60,
670,
6925,
374,
18,
21,
4529,
18,
12526,
392,
11078,
1177,
310,
4355,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
453,
1176,
8489,
1345,
353,
4232,
39,
3462,
1345,
288,
203,
203,
565,
533,
1071,
5381,
508,
273,
315,
52,
1176,
8489,
611,
1673,
13899,
14432,
203,
203,
565,
2254,
28,
1071,
5381,
15105,
273,
404,
31,
203,
203,
565,
533,
1071,
5381,
3273,
273,
315,
8025,
61,
62,
14432,
203,
203,
565,
533,
1071,
5381,
1177,
273,
296,
44,
20,
18,
21,
13506,
203,
203,
565,
2254,
5381,
1071,
14275,
67,
28343,
67,
3194,
67,
55,
6950,
10541,
882,
14607,
3991,
273,
404,
31,
203,
203,
565,
445,
453,
1176,
8489,
1345,
12,
203,
3639,
2254,
5034,
389,
6769,
6275,
203,
4509,
19,
203,
565,
262,
4232,
39,
3462,
1345,
24899,
6769,
6275,
13,
288,
203,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x16893cf6C0dea02f0dD2f37597a02FDec18B2E4b/sources/MadBopFinal.sol/MadbopFinalUSDC.sol
|
payable isCorrectPayment(prices)
|
function mint(address _to, uint256 _quantity, string[] memory URIs, bytes[] memory signatures, uint[] memory prices)
external
whenNotPaused
isAvailable(_quantity)
{
require(URIs.length == _quantity, "invalid URIs provided");
mintInternal(_to, _quantity, URIs, signatures, prices);
}
| 5,638,676 |
[
1,
10239,
429,
353,
16147,
6032,
12,
683,
1242,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
16172,
16,
533,
8526,
3778,
24565,
16,
1731,
8526,
3778,
14862,
16,
2254,
8526,
3778,
19827,
13,
7010,
3639,
3903,
21281,
3639,
1347,
1248,
28590,
203,
3639,
28293,
24899,
16172,
13,
7010,
565,
288,
203,
3639,
2583,
12,
1099,
2520,
18,
2469,
422,
389,
16172,
16,
315,
5387,
24565,
2112,
8863,
203,
3639,
312,
474,
3061,
24899,
869,
16,
389,
16172,
16,
24565,
16,
14862,
16,
19827,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x772Fe21b59604c27cb238e46e4000E8928bAf328/sources/Strategy.sol
|
Key logic. The algorithm moves assets from lowest return to highest like a very slow idiots bubble sort we ignore debt outstanding for an easy life/we just keep all money in want if we dont have any lendersemergency exit is dealt with at beginning of harvestapr should go down after deposit so wont be withdrawing from self
|
function adjustPosition(uint256 _debtOutstanding) internal override {
if (lenders.length == 0) {
return;
}
if (emergencyExit) {
return;
}
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
| 9,312,225 |
[
1,
653,
4058,
18,
282,
1021,
4886,
13934,
7176,
628,
11981,
327,
358,
9742,
282,
3007,
279,
8572,
11816,
612,
77,
6968,
21577,
1524,
282,
732,
2305,
18202,
88,
20974,
364,
392,
12779,
17140,
19,
1814,
2537,
3455,
777,
15601,
316,
2545,
309,
732,
14046,
1240,
1281,
328,
2345,
307,
6592,
75,
2075,
2427,
353,
443,
2390,
598,
622,
8435,
434,
17895,
26923,
438,
86,
1410,
1960,
2588,
1839,
443,
1724,
1427,
341,
1580,
506,
598,
9446,
310,
628,
365,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
5765,
2555,
12,
11890,
5034,
389,
323,
23602,
1182,
15167,
13,
2713,
3849,
288,
203,
3639,
309,
261,
80,
10130,
18,
2469,
422,
374,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
351,
24530,
6767,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
261,
11890,
5034,
11981,
16,
2254,
5034,
11981,
37,
683,
16,
2254,
5034,
9742,
16,
2254,
5034,
8555,
13,
273,
11108,
10952,
2555,
5621,
203,
203,
3639,
309,
261,
26451,
405,
11981,
37,
683,
13,
288,
203,
5411,
328,
10130,
63,
821,
395,
8009,
1918,
9446,
1595,
5621,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
324,
287,
273,
2545,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
70,
287,
405,
374,
13,
288,
203,
5411,
2545,
18,
4626,
5912,
12,
2867,
12,
80,
10130,
63,
8766,
395,
65,
3631,
324,
287,
1769,
203,
5411,
328,
10130,
63,
8766,
395,
8009,
323,
1724,
5621,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-17
*/
pragma solidity ^0.5.0;
/**
* @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){
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b,"Calculation error");
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,"Calculation error");
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,"Calculation error");
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,"Calculation error");
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,"Calculation error");
return a % b;
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public;
}
/**
* @title Layerx Contract For ERC20 Tokens
* @dev LAYERX tokens as per ERC20 Standards
*/
contract Layerx is IERC20, Owned {
using SafeMath for uint256;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
uint public totalEthRewards = 0;
uint stakeNum = 0;
uint amtByDay = 27397260274000000000;
uint public stakePeriod = 30 days;
address public stakeCreator;
bool isPaused = false;
struct Stake {
uint start;
uint end;
uint layerLockedTotal;
uint layerxReward;
uint ethReward;
}
struct StakeHolder {
uint layerLocked;
uint firstStake;
uint time;
}
struct Rewards {
uint layerLocked;
uint layersx;
uint eth;
bool isReceived;
}
event logLockedTokens(address holder, uint amountLocked, uint timeLocked, uint stakeId);
event logUnlockedTokens(address holder, uint amountUnlocked, uint timeUnlocked);
event logWithdraw(address holder, uint layerx, uint eth, uint stakeId, uint time);
event logCloseStake(uint id, uint amount, uint timeClosed);
modifier paused {
require(isPaused == false, "This contract was paused by the owner!");
_;
}
modifier exist (uint index) {
require(index <= stakeNum, 'This stake does not exist.');
_;
}
mapping (address => StakeHolder) public stakeHolders;
mapping (uint => Stake) public stakes;
mapping (address => mapping (uint => Rewards)) public rewards;
mapping (address => uint) balances;
mapping (address => mapping(address => uint)) allowed;
mapping (address => bool) private swap;
IERC20 UNILAYER = IERC20(0x0fF6ffcFDa92c53F615a4A75D982f399C989366b);
constructor(address _owner) public {
owner = _owner;
stakeCreator = owner;
symbol = "LAYERX";
name = "UNILAYERX";
decimals = 18;
_totalSupply = 40000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
stakes[0] = Stake(now, 0, 0, 0, 0);
}
/**
* @dev Total number of tokens in existence.
*/
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
/**
* @dev Gets the balance of the specified address.
* @param tokenOwner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public onlyOwner {
require(value > 0, "Invalid Amount.");
require(_totalSupply >= value, "Invalid account state.");
require(balances[owner] >= value, "Invalid account balances state.");
_totalSupply = _totalSupply.sub(value);
balances[owner] = balances[owner].sub(value);
emit Transfer(owner, address(0), value);
}
/**
* @dev Set new Stake Creator address.
* @param _stakeCreator The address of the new Stake Creator.
*/
function setNewStakeCreator(address _stakeCreator) external onlyOwner {
require(_stakeCreator != address(0), 'Do not use 0 address');
stakeCreator = _stakeCreator;
}
/**
* @dev Set new pause status.
* @param newIsPaused The pause status: 0 - not paused, 1 - paused.
*/
function setIsPaused(bool newIsPaused) external onlyOwner {
isPaused = newIsPaused;
}
/**
* @dev Set new Stake Period.
* @param newStakePeriod indicates new stake period, it was 7 days by default.
*/
function setStakePeriod(uint256 newStakePeriod) external onlyOwner {
stakePeriod = newStakePeriod;
}
/**
* @dev Stake LAYER tokens for earning rewards, Tokens will be deducted from message sender account
* @param payment Amount of LAYER to be staked in the pool
*/
function lock(uint payment) external paused {
require(payment > 0, 'Payment must be greater than 0.');
require(UNILAYER.balanceOf(msg.sender) >= payment, 'Holder does not have enough tokens.');
require(UNILAYER.allowance(msg.sender, address(this)) >= payment, 'Call Approve function firstly.');
UNILAYER.transferFrom(msg.sender, address(this), payment);
StakeHolder memory holder = stakeHolders[msg.sender];
Stake memory stake = stakes[stakeNum];
if(holder.layerLocked == 0) {
holder.firstStake = stakeNum;
holder.time = now;
} else if(holder.layerLocked > 0 && stakeNum > holder.firstStake) {
Rewards memory rwds = rewards[msg.sender][stakeNum-1];
require(rwds.isReceived == true,'Withdraw your rewards.');
}
holder.layerLocked = holder.layerLocked.add(payment);
stakeHolders[msg.sender] = holder;
stake.layerLockedTotal = stake.layerLockedTotal.add(payment);
stakes[stakeNum] = stake;
emit logLockedTokens(msg.sender, payment, now, stakeNum);
}
/**
* @dev Withdraw My Staked Tokens from staker pool
*/
function unlock() external paused {
StakeHolder memory holder = stakeHolders[msg.sender];
uint amt = holder.layerLocked;
require(amt > 0, 'You do not have locked tokens.');
require(UNILAYER.balanceOf(address(this)) >= amt, 'Insufficient account balance!');
if(holder.layerLocked > 0 && stakeNum > 0) {
Rewards memory rwds = rewards[msg.sender][stakeNum-1];
require(rwds.isReceived == true,'Withdraw your rewards.');
}
Stake memory stake = stakes[stakeNum];
stake.layerLockedTotal = stake.layerLockedTotal.sub(holder.layerLocked);
stakes[stakeNum] = stake;
delete stakeHolders[msg.sender];
UNILAYER.transfer(msg.sender, amt);
emit logUnlockedTokens(msg.sender, amt, now);
}
/**
* @dev Stake Creator finalizes the stake, the stake receives the accumulated ETH as reward and calculates everyone's percentages.
*/
function closeStake() external {
require(msg.sender == stakeCreator, 'You cannot call this function');
Stake memory stake = stakes[stakeNum];
require(now >= stake.start.add(stakePeriod), 'You cannot call this function until stakePeriod is over');
stake.end = now;
stake.ethReward = stake.ethReward.add(totalEthRewards);
uint amtLayerx = stake.end.sub(stake.start).mul(amtByDay).div(1 days);
if(amtLayerx > balances[owner]) { amtLayerx = balances[owner]; }
stake.layerxReward = amtLayerx;
stakes[stakeNum] = stake;
emit logCloseStake(stakeNum, totalEthRewards, now);
stakeNum++;
stakes[stakeNum] = Stake(now, 0, stake.layerLockedTotal, 0, 0);
totalEthRewards = 0;
}
/**
* @dev Withdraw Reward Layerx Tokens and ETH
* @param index Stake index
*/
function withdraw(uint index) external paused exist(index) {
Rewards memory rwds = rewards[msg.sender][index];
Stake memory stake = stakes[index];
StakeHolder memory holder = stakeHolders[msg.sender];
uint endTime = holder.time + stakePeriod;
require(endTime <= now, 'Wait the minimum time');
require(stake.end <= now, 'Invalid date for withdrawal.');
require(rwds.isReceived == false, 'You already withdrawal your rewards.');
require(balances[owner] >= rwds.layersx, 'Insufficient account balance!');
require(address(this).balance >= rwds.eth,'Invalid account state, not enough funds.');
require(index >= holder.firstStake, 'Invalid index.');
if(holder.firstStake != index) {
Rewards memory rwdsOld = rewards[msg.sender][index-1];
require(rwdsOld.isReceived == true,'Withdraw your old rewards first.');
}
rwds.isReceived = true;
rwds.layerLocked = holder.layerLocked;
if(rwds.layerLocked > 0) {
rwds.layersx = rwds.layerLocked.mul(stake.layerxReward).div(stake.layerLockedTotal);
rwds.eth = rwds.layerLocked.mul(stake.ethReward).div(stake.layerLockedTotal);
}
rewards[msg.sender][index] = rwds;
emit logWithdraw(msg.sender, rwds.layersx, rwds.eth, index, now);
if(rwds.layersx > 0) {
balances[owner] = balances[owner].sub(rwds.layersx);
balances[msg.sender] = balances[msg.sender].add(rwds.layersx);
emit Transfer(owner, msg.sender, rwds.layersx);
}
if(rwds.eth > 0) { msg.sender.transfer(rwds.eth); }
}
/**
* @dev Function to get the number of stakes
* @return number of stakes
*/
function getStakesNum() external view returns (uint) {
return stakeNum;
}
function stakeOf(address tokenOwner) public view returns (uint balance) {
StakeHolder memory holder = stakeHolders[tokenOwner];
return holder.layerLocked;
}
/**
* @dev Receive ETH and add value to the accumulated eth for stake
*/
function() external payable {
totalEthRewards = totalEthRewards.add(msg.value);
}
function destroyContract() external onlyOwner {
selfdestruct(msg.sender);
}
}
|
* @title SafeMath @dev Unsigned math operations with safety checks that revert on error/
|
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256){
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b,"Calculation error");
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256){
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b,"Calculation error");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256){
require(b > 0,"Calculation error");
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256){
require(b <= a,"Calculation error");
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256){
uint256 c = a + b;
require(c >= a,"Calculation error");
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256){
require(b != 0,"Calculation error");
return a % b;
}
}
| 1,691,444 |
[
1,
9890,
10477,
565,
1351,
5679,
4233,
5295,
598,
24179,
4271,
716,
15226,
603,
555,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
12083,
14060,
10477,
288,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
15329,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
10837,
13989,
555,
8863,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
377,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
15329,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
10837,
13989,
555,
8863,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
377,
203,
565,
445,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
15329,
203,
3639,
2583,
12,
70,
405,
374,
10837,
13989,
555,
8863,
203,
3639,
2254,
5034,
276,
273,
279,
342,
324,
31,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
15329,
203,
3639,
2583,
12,
70,
1648,
279,
10837,
13989,
555,
8863,
203,
3639,
2254,
5034,
276,
273,
279,
300,
324,
31,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
527,
12,
11890,
5034,
279,
16,
2
] |
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// ROBOTOVERSE NFT CONSTRUCTOR
/**
* Contract Developed by @itsDigidal
* https://twitter.com/itsdigidal
*
*
*/
pragma solidity ^0.8.7;
contract Robotoverse is ERC721Enumerable, Ownable{
using Strings for uint256;
/* base attributes */
string public baseURI;
string public prerevealURI;
string public baseExtension = ".json";
/* minting prices */
uint256 public batchOnePrice = 0.08 ether;
uint256 public batchTwoPrice = 0.1 ether;
uint256 public batchThreePrice = 0.15 ether;
uint256 public batchFourPrice = 0.2 ether;
/* supply */
uint256 public maxSupply;
uint256 public maxMintAmount = 100;
uint256 public tokenCounter;
uint256 public batchOneMembers = 1000;
uint256 public batchTwoMembers = 1500;
uint256 public batchThreeMembers = 1500;
uint256 public batchFourMembers = 3477;
uint256 public teamNFTs = 300;
uint256 public teamClaimed = 0;
/* states */
bool public batchOneActive = true;
bool public batchTwoActive = false;
bool public batchThreeActive = false;
bool public batchFourActive = false;
bool public whitelistOpen = false;
bool public revealed = false;
bool public whitelistActive = true;
bool private teamNFTsclaimed = false;
/* tax getters */
address private ownerOne;
address private ownerTwo;
address private ownerThree;
uint256 private shareOne = 50;
uint256 private shareTwo = 50;
uint256 public accountOne = 0 ether;
uint256 public accountTwo = 0 ether;
/* whitelist params */
uint256 public maxWhitelistAmount = 100;
uint256 public whitelistAmount = 1000;
uint256 public whitelistSize = 0;
mapping(address => bool) public whitelist;
event AddedToWhitelist(address indexed account);
mapping(address => uint256) whitelistClaimed;
// constructor
constructor(string memory _newBaseURI, string memory _prerevealURI, address _ownerOne, address _ownerTwo) ERC721("Robotoverse", "RBV") {
tokenCounter = 0;
maxSupply = batchOneMembers + batchTwoMembers + batchThreeMembers + batchFourMembers;
baseURI = _newBaseURI;
prerevealURI = _prerevealURI;
ownerOne = _ownerOne;
ownerTwo = _ownerTwo;
}
/// public minting
function mintNFT(address _to, uint256 _mintAmount) public payable {
require(_mintAmount > 0, "At least one token must be minted");
require(_mintAmount <= maxMintAmount, "Exceeds maximal possible tokens to mint on a try");
require(tokenCounter + _mintAmount <= maxSupply, "Maximal supply of NFT is reached");
require(!whitelistActive, "Whitelist Minting is active. Please use other function");
uint256 toPay = 0;
if(tokenCounter >= 0 && tokenCounter + _mintAmount <= batchOneMembers) {
require(batchOneActive == true, "Batch one can not be minted yet");
require(msg.value >= batchOnePrice * _mintAmount, "Amount of MOVR is to less");
toPay = batchOnePrice * _mintAmount;
} else {
if(tokenCounter + _mintAmount <= batchOneMembers + batchTwoMembers) {
require(batchTwoActive == true, "Batch two can not be minted yet");
require(msg.value >= batchTwoPrice * _mintAmount, "Amount of MOVR is to less");
toPay = batchOnePrice * _mintAmount;
} else {
if(tokenCounter + _mintAmount <= batchOneMembers + batchTwoMembers + batchThreeMembers) {
require(batchThreeActive == true, "Batch two can not be minted yet");
require(msg.value >= batchThreePrice * _mintAmount, "Amount of MOVR is to less");
toPay = batchOnePrice * _mintAmount;
} else {
require(batchThreeActive == true, "Batch three can not be minted yet");
require(msg.value >= batchThreePrice * _mintAmount, "Amount of MOVR is to less");
toPay = batchOnePrice * _mintAmount;
}
}
}
for (uint256 i = 1; i <= _mintAmount; i++) {
tokenCounter++;
_safeMint(_to, tokenCounter);
}
/* pay taxes */
accountOne = accountOne + toPay * shareOne / 100;
accountTwo = accountTwo + toPay * shareTwo / 100;
}
// public minting
function mintWhitelistNFT(address _to, uint256 _mintAmount) public payable {
require(_mintAmount > 0, "At least one token must be minted");
require(_mintAmount <= maxMintAmount, "Exceeds maximal possible tokens to mint on a try");
require(tokenCounter + _mintAmount <= maxSupply, "Maximal supply of NFT is reached");
require(tokenCounter + _mintAmount <= batchOneMembers, "Maximal whitelist NFT's exceeded");
require(isWhitelisted(msg.sender), "You are not whitelisted!");
require(batchOneActive == true, "Batch one can not be minted yet");
require(maxWhitelistAmount >= _mintAmount, "Only five mints are allowed for whitlist users");
require(_mintAmount + getWhitelistClaim(msg.sender) <= maxWhitelistAmount, "You exceeded your whitelist limit");
require(msg.value >= batchOnePrice * _mintAmount, "Amount of ETH is to less");
for (uint256 i = 1; i <= _mintAmount; i++) {
tokenCounter++;
whitelistClaimed[msg.sender] += 1;
_safeMint(_to, tokenCounter);
/* pay taxes */
accountOne += msg.value * shareOne / 100;
accountTwo += msg.value * shareTwo / 100;
}
}
// read URI of Token for Meta
function tokenURI(uint256 tokenId) public view virtual override
returns (string memory)
{
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory currentBaseURI;
if (revealed) {
currentBaseURI = baseURI;
} else {
currentBaseURI = prerevealURI;
}
return string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension));
}
// get NFT of specific address
function getNFTContract(address _owner) public view returns (uint256[] memory) {
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
// get current amount of NFT
function getNFTAmount() public view returns (uint256) {
return tokenCounter;
}
// get current Price for minting depending on batch state
function currentMintingPrice() public view returns (uint256) {
if(tokenCounter >= 0 && tokenCounter < batchOneMembers) {
return batchOnePrice;
} else {
if(tokenCounter < batchOneMembers + batchTwoMembers) {
return batchTwoPrice;
} else {
if(tokenCounter < batchOneMembers + batchTwoMembers + batchThreeMembers) {
return batchThreePrice;
} else {
return batchFourPrice;
}
}
}
}
// get baseURI of nft collection
function getBaseURI() public view returns (string memory) {
return baseURI;
}
// check is user is whitelisted
function isWhitelisted(address _address) public view returns(bool) {
return whitelist[_address];
}
// check whitelist claims per user
function getWhitelistClaim(address _address) public view returns(uint256) {
return whitelistClaimed[_address];
}
// only owner functions
// set price of first batch
function setbatchOnePrice(uint256 _newPrice) public onlyOwner {
batchOnePrice = _newPrice;
}
// set price of second batch
function setbatchTwoPrice(uint256 _newPrice) public onlyOwner {
batchTwoPrice = _newPrice;
}
// set price of third batch
function setbatchThreePrice(uint256 _newPrice) public onlyOwner {
batchThreePrice = _newPrice;
}
// set price of fourth batch
function setbatchFourPrice(uint256 _newPrice) public onlyOwner {
batchFourPrice = _newPrice;
}
// set maximal amout of nft to mint on one occasion
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
// change base uri
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
// change prereveal uri
function setPrerevealURI(string memory _newBaseURI) public onlyOwner {
prerevealURI = _newBaseURI;
}
// change extension of base uri
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
// activate batchOne
function setbatchOneState() public onlyOwner {
if(batchOneActive) {
batchOneActive = false;
} else {
batchOneActive = true;
}
}
// activate batchTwo
function setbatchTwoState() public onlyOwner {
if(batchTwoActive) {
batchTwoActive = false;
} else {
batchTwoActive = true;
}
}
// activate batchThree
function setbatchThreeState() public onlyOwner {
if(batchThreeActive) {
batchThreeActive = false;
} else {
batchThreeActive = true;
}
}
// activate revealed
function setRevealed() public onlyOwner {
if(revealed) {
revealed = false;
} else {
revealed = true;
}
}
// withdrawel functions
// withdrawel of account
function withdrawAccount() public payable {
if(msg.sender == ownerOne) {
require(accountOne >= 0 ether, "Account One has no credits");
require(payable(msg.sender).send(accountOne));
accountOne = 0;
}
if(msg.sender == ownerTwo) {
require(accountTwo >= 0 ether, "Account Two has no credits");
require(payable(msg.sender).send(accountTwo));
accountTwo = 0;
}
}
// withdrawel of rest
function withdraw() public payable onlyOwner {
uint256 restAmount = address(this).balance - accountOne - accountTwo;
if(restAmount >= 0) {
require(payable(msg.sender).send(restAmount));
}
}
// bulk upload of whitelist users
function bulkSetWhitelist(address[] memory accounts) public onlyOwner returns (uint256) {
uint256 taskCounter = 0;
for (uint256 i = 0; i < accounts.length; i++) {
if(!whitelist[accounts[i]]) {
if(whitelistSize < whitelistAmount) {
whitelist[accounts[i]] = true;
emit AddedToWhitelist(accounts[i]);
whitelistSize++;
taskCounter++;
} else {
break;
}
}
}
return taskCounter;
}
// activate whitelist minting
function setWhitelistOpen() public onlyOwner {
if(whitelistActive) {
whitelistActive = false;
} else {
whitelistActive = true;
}
}
// mint teamNFTs
function mintTeamNFT(uint256 _toMint) public onlyOwner {
require(!teamNFTsclaimed, "TeamNFT already claimed");
teamClaimed += _toMint;
if(teamClaimed >= teamNFTs) {
teamNFTsclaimed = true;
}
require(teamClaimed <= teamNFTs, "Maximum of team claims reached");
for (uint256 i = 1; i <= _toMint; i++) {
tokenCounter++;
_safeMint(msg.sender, tokenCounter);
}
}
}
|
set price of third batch
|
function setbatchThreePrice(uint256 _newPrice) public onlyOwner {
batchThreePrice = _newPrice;
}
| 6,091,565 |
[
1,
542,
6205,
434,
12126,
2581,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
5303,
28019,
5147,
12,
11890,
5034,
389,
2704,
5147,
13,
1071,
1338,
5541,
288,
203,
3639,
2581,
28019,
5147,
273,
389,
2704,
5147,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
import "Ownable.sol";
import "Pausable.sol";
import "PaymentSplitter.sol";
import "ERC721A.sol";
import "Whitelist.sol";
contract InvisibleKennel is ERC721A, Ownable, Pausable, Whitelist, PaymentSplitter {
/**
* General constants and immutable variables
*/
// maximum number of items in the collection
uint256 immutable public COLLECTION_MAX_ITEMS;
// "believers" get their first few whitelist mints boosted with free items
uint256 public constant BELIEVER_MAX_SPONSORED_MINTS = 10;
// boosting factor for "believers"
uint256 public constant BELIEVER_BOOST_FACTOR = 2;
// maximum number of mints per transaction
uint256 public maxMintsPerTx;
// UTC timestamp when whitelist minting starts
uint256 public whitelistStartingTime;
// UTC timestamp when public minting starts
uint256 public publicStartingTime;
// price of one NFT in wei
uint256 public price;
// when `true`, `specialMint` cannot longer be called
bool public specialMintLocked;
// for each believer, number of paid mints that were already sponsored
mapping(address => uint256) public believerAlreadySponsoredMints;
// URI used to prefix token URI
string internal __baseURI;
constructor(string memory name_,
string memory symbol_,
uint256 collectionMaxItems_,
uint256 price_,
uint256 maxMintsPerTx_,
uint256 whitelistStartingTime_,
uint256 publicStartingTime_,
string memory _baseURI_,
address[] memory payees_,
uint256[] memory shares_)
ERC721A(name_, symbol_)
PaymentSplitter(payees_, shares_) {
COLLECTION_MAX_ITEMS = collectionMaxItems_;
setPrice(price_);
maxMintsPerTx = maxMintsPerTx_;
whitelistStartingTime = whitelistStartingTime_;
publicStartingTime = publicStartingTime_;
__baseURI = _baseURI_;
setSigner(msg.sender);
}
/**
* Unrestricted functions.
*/
/**
* Returns the total amount of tokens minted in the contract.
*/
function totalMinted() external view returns(uint256) {
return _totalMinted();
}
/**
* @dev Safely mints an amount of tokens equal to `msg.value/price` to `msg.sender`.
*/
function mint() external payable whenNotPaused {
require(block.timestamp >= publicStartingTime, "minting not open yet");
uint256 _numToMint = msg.value / price;
require(_numToMint <= maxMintsPerTx, "limit on minting too many at a time");
_isValidMintAmount(_numToMint);
_safeMint(msg.sender, _numToMint);
}
/**
* @dev Safely mints an amount of tokens equal to `msg.value/price` to `msg.sender` provided
* `_signature` is valid. If `_isBeliever` is `true`, the first paid `BELIEVER_MAX_SPONSORED_MINTS`
* mints from msg.sender will yield her an extra `BELIEVER_BOOST_FACTOR` items.
*/
function whitelistMint(bool _isBeliever, bytes memory _signature) external payable whenNotPaused {
require(block.timestamp >= whitelistStartingTime, "whitelist not open yet");
require(_verify(msg.sender, _isBeliever, _signature), "invalid arguments or not whitelisted");
uint256 _numToMint = msg.value / price;
uint256 _numToMintWithoutSponsor = _numToMint;
if (_isBeliever) {
uint256 _maxRemainingSponsored = BELIEVER_MAX_SPONSORED_MINTS - believerAlreadySponsoredMints[msg.sender];
if (_maxRemainingSponsored < _numToMint) {
believerAlreadySponsoredMints[msg.sender] += _maxRemainingSponsored;
_numToMint += _maxRemainingSponsored * (BELIEVER_BOOST_FACTOR - 1);
} else {
believerAlreadySponsoredMints[msg.sender] += _numToMint;
_numToMint *= BELIEVER_BOOST_FACTOR;
}
}
require(_numToMintWithoutSponsor <= maxMintsPerTx, "limit on minting too many at a time");
_isValidMintAmount(_numToMint);
_safeMint(msg.sender, _numToMint);
}
/**
* @dev Burns `tokenId`. See {ERC721A-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) external {
_burn(tokenId, true);
}
/**
* @dev Returns `__baseURI`.
*/
function _baseURI() internal view override returns (string memory) {
return __baseURI;
}
/**
* @dev Checks that the quantity being minted is valid.
*/
function _isValidMintAmount(uint256 _numToMint) private view returns(uint256){
require(_numToMint > 0, "cannot mint 0");
require((_numToMint + _totalMinted()) <= COLLECTION_MAX_ITEMS,
"would exceed max supply");
}
/**
* Restricted functions.
*/
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public override {
require(msg.sender == address(account), "msg.sender != account");
super.release(account);
}
/**
* @dev Minting, at no cost, a quantity of items as defined by the array `amounts`
* to an array of `recipients`. This function can only be called by the `owner`
* while `specialMintLocked` evaluates to `false`.
*/
function specialMint(address[] memory recipients, uint256[] memory amounts) external onlyOwner {
require(!specialMintLocked, "special mint permanently locked");
require(recipients.length == amounts.length, "arrays have different lengths");
for(uint256 i=0; i < recipients.length; i++){
_safeMint(recipients[i], amounts[i]);
}
require(_totalMinted() <= COLLECTION_MAX_ITEMS, "would exceed max supply");
}
/**
* @dev Sets the starting time of the whitelist.
*/
function setWhitelistStartingTime(uint256 _whitelistStartingTime) external onlyOwner {
whitelistStartingTime = _whitelistStartingTime;
}
/**
* @dev Sets the starting time of the public sale.
*/
function setPublicStartingTime(uint256 _publicStartingTime) external onlyOwner {
publicStartingTime = _publicStartingTime;
}
/**
* @dev Sets the maximum number of items that can be minted at once.
*/
function setMaxMintsPerTx(uint256 _newMaxMintsPerTx) external onlyOwner {
maxMintsPerTx = _newMaxMintsPerTx;
}
/**
* @dev Permanently prevents the `owner` from calling `specialMint`.
*/
function lockSpecialMint() external onlyOwner {
specialMintLocked = true;
}
/**
* @dev Sets the base URI.
*/
function setBaseURI(string memory _newBaseURI) external onlyOwner {
__baseURI = _newBaseURI;
}
/**
* @dev Pauses functions modified with `whenNotPaused`.
*/
function pause() external virtual whenNotPaused onlyOwner {
_pause();
}
/**
* @dev Unpauses functions modified with `whenNotPaused`.
*/
function unpause() external virtual whenPaused onlyOwner {
_unpause();
}
/**
* @dev Sets the price in wei per item. Price must be positive.
*/
function setPrice(uint256 _newPrice) public onlyOwner {
require(_newPrice > 0, "price must be positive");
price = _newPrice;
}
/**
* @dev Sets the address to use to verify validity of signatures in `whitelistMint`.
*/
function setSigner(address _newSigner) public onlyOwner {
require(_newSigner != address(0), "signer cannot be the zero address");
_signer = _newSigner;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol)
pragma solidity ^0.8.0;
import "SafeERC20.sol";
import "Address.sol";
import "Context.sol";
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*
* NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and
* tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you
* to run tests before sending real value to this contract.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
mapping(IERC20 => uint256) private _erc20TotalReleased;
mapping(IERC20 => mapping(address => uint256)) private _erc20Released;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20
* contract.
*/
function totalReleased(IERC20 token) public view returns (uint256) {
return _erc20TotalReleased[token];
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an
* IERC20 contract.
*/
function released(IERC20 token, address account) public view returns (uint256) {
return _erc20Released[token][account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + totalReleased();
uint256 payment = _pendingPayment(account, totalReceived, released(account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] += payment;
_totalReleased += payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their
* percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20
* contract.
*/
function release(IERC20 token, address account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token);
uint256 payment = _pendingPayment(account, totalReceived, released(token, account));
require(payment != 0, "PaymentSplitter: account is not due payment");
_erc20Released[token][account] += payment;
_erc20TotalReleased[token] += payment;
SafeERC20.safeTransfer(token, account, payment);
emit ERC20PaymentReleased(token, account, payment);
}
/**
* @dev internal logic for computing the pending payment of an `account` given the token historical balances and
* already released amounts.
*/
function _pendingPayment(
address account,
uint256 totalReceived,
uint256 alreadyReleased
) private view returns (uint256) {
return (totalReceived * _shares[account]) / _totalShares - alreadyReleased;
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "IERC20.sol";
import "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) (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 (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
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import "IERC721.sol";
import "IERC721Receiver.sol";
import "IERC721Metadata.sol";
import "Address.sol";
import "Context.sol";
import "Strings.sol";
import "ERC165.sol";
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerQueryForNonexistentToken();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(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 override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
abstract contract Whitelist {
address internal _signer;
function _getMessageHash(address _to, bool _believer) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_to, _believer));
}
function _getEthSignedMessageHash(bytes32 _messageHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash));
}
function _verify(address _to, bool _believer, bytes memory _signature) internal view returns (bool) {
bytes32 messageHash = _getMessageHash(_to, _believer);
bytes32 ethSignedMessageHash = _getEthSignedMessageHash(messageHash);
return _recoverSigner(ethSignedMessageHash, _signature) == _signer;
}
function _recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) internal pure returns (address) {
(bytes32 r, bytes32 s, uint8 v) = _splitSignature(_signature);
return ecrecover(_ethSignedMessageHash, v, r, s);
}
function _splitSignature(bytes memory _signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) {
require(_signature.length == 65, "invalid signature length");
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
}
}
|
* @dev Unpauses functions modified with `whenNotPaused`./
|
function unpause() external virtual whenPaused onlyOwner {
_unpause();
}
| 267,753 |
[
1,
984,
8774,
6117,
4186,
4358,
598,
1375,
13723,
1248,
28590,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
640,
19476,
1435,
3903,
5024,
1347,
28590,
1338,
5541,
288,
203,
3639,
389,
318,
19476,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xBCF9F4c6FC589c89d4aAdE063010D0f5B3733680/sources/contracts/tests/testnet/GDAI.sol
|
* @dev Check if the caller is the governor./
|
modifier onlyGovernorOrGSR {
require(msg.sender == governor || msg.sender == GSR, "Only Governor or GSR can call");
_;
}
| 4,905,562 |
[
1,
1564,
309,
326,
4894,
353,
326,
314,
1643,
29561,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
9606,
1338,
43,
1643,
29561,
1162,
43,
10090,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
314,
1643,
29561,
747,
1234,
18,
15330,
422,
611,
10090,
16,
315,
3386,
611,
1643,
29561,
578,
611,
10090,
848,
745,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
/**
* @title ProjectFactory
* @dev Factory for creating projects
*/
contract ProjectFactory {
CrowdFunding[] public deployedProjects;
function createProject(uint256 minimum) public {
CrowdFunding newProject = new CrowdFunding(minimum, msg.sender);
deployedProjects.push(newProject);
}
function getDeployedProjects() public view returns (CrowdFunding[] memory) {
return deployedProjects;
}
}
/**
* @title CrowdFunding
* @dev CrowdFunding is a contract that allows multiple parties to contribute to a single project.
*/
contract CrowdFunding {
// struct type to represent a Request
struct Request {
string description; // description of request
uint256 value; // amount requested in request
address payable recipient; // address of vendor/recipient whom money will be sent
bool complete; // True if request is completed
uint256 approvalCount; // number of approvals
mapping(address => bool) approvals; // mapping of address to bool indicating if they approved
}
uint256 numRequests;
mapping(uint256 => Request) public requests;
// state variable of type address containing manager's address
address public manager;
//state variable of type uint contating minimum contribution amount
uint256 public minContribution;
// address to bool mapping for approvers
mapping(address => bool) public approvers;
// state variable to store number of approvers
uint256 public approversCount;
// modifier onlyByManager is a modifier that checks if the sender is the manager
modifier onlyByManager() {
require(
msg.sender == manager,
"Only the manager can create new requests."
);
_;
}
// Contract constructor: set manager, set minimum contribution
constructor(uint256 _minContribution, address _manager) {
manager = _manager;
minContribution = _minContribution;
}
//function to set the approvers
function contribute() public payable {
// checking if the incoming contribution amount is greater than or equal to minimum contribution
require(
msg.value >= minContribution,
"Contibution must be greater than or equal to minimum value"
);
approvers[msg.sender] = true;
approversCount++;
}
// function to create a request
function createRequest(
string memory _description,
uint256 _value,
address payable _recipient
) public onlyByManager {
Request storage newRequest = requests[numRequests++];
newRequest.description = _description;
newRequest.value = _value;
newRequest.recipient = _recipient;
newRequest.complete = false;
newRequest.approvalCount = 0;
}
// function to approve a request
function approveRequest(uint256 _requestIndex) public {
Request storage request = requests[_requestIndex];
require(
approvers[msg.sender],
"Only contributors can approve requests."
);
require(
!request.approvals[msg.sender],
"You have already voted for this request"
);
request.approvals[msg.sender] = true;
request.approvalCount++;
}
// function to finalize a request
function finalizeRequest(uint256 _requestIndex) public onlyByManager {
Request storage request = requests[_requestIndex];
require(
request.approvalCount > (approversCount / 2),
"More approvals needed to finalize request"
);
require(!(request.complete), "Request is already finalized");
request.recipient.transfer(request.value);
request.complete = true;
}
// function to get summary of requests
function getSummary()
public
view
returns (
uint256,
uint256,
uint256,
uint256,
address
)
{
return (
minContribution,
address(this).balance,
numRequests,
approversCount,
manager
);
}
// function to get request count
function getRequestsCount() public view returns (uint256) {
return numRequests;
}
}
|
function to set the approvers checking if the incoming contribution amount is greater than or equal to minimum contribution
|
function contribute() public payable {
require(
msg.value >= minContribution,
"Contibution must be greater than or equal to minimum value"
);
approvers[msg.sender] = true;
approversCount++;
}
| 13,068,172 |
[
1,
915,
358,
444,
326,
6617,
2496,
6728,
309,
326,
6935,
24880,
3844,
353,
6802,
2353,
578,
3959,
358,
5224,
24880,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
356,
887,
1435,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
1132,
1545,
1131,
442,
4027,
16,
203,
5411,
315,
660,
495,
1421,
1297,
506,
6802,
2353,
578,
3959,
358,
5224,
460,
6,
203,
3639,
11272,
203,
203,
3639,
6617,
2496,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
3639,
6617,
2496,
1380,
9904,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0xcCAFCcDB868650E1b6700a997B2F1D0575BB7703/sources/contracts/Airdrop.sol
|
0x510a7aab47105062D1bB87b1ACB7919Ae0471124 User Info (need to figure out what other info is needed to confirm airdrop prereq)
|
contract GBAirdrop {
address public admin;
using HitchensUnorderedKeySetLib for HitchensUnorderedKeySetLib.Set;
HitchensUnorderedKeySetLib.Set airDropSet;
pragma solidity ^0.8.0;
struct userInfo{
bool airDropClaimed;
bool dropRequirementMet;
}
mapping(address => bool) processedAirdop;
IERC20 public gbToken;
event logUpdate(address sender, bytes32 userKey, string action);
mapping(bytes32 => userInfo) userInfoToAddress;
event airdopProcessed(address recipient, uint amount, uint date);
constructor(address _token){
admin = msg.sender;
gbToken = IERC20(_token);
}
function updateAdmin(address newAdmin) external {
require(msg.sender == admin, "only admin");
admin = newAdmin;
}
function claimTokens(address recipient, uint amountSent)external{
require(processedAirdop[recipient] != true, "Airdrop has already been claimed");
gbToken.transfer(recipient, amountSent);
processedAirdop[recipient] = true;
emit airdopProcessed(recipient, amountSent, block.timestamp);
}
function addToAirdrop(bytes32 userKey, bool _dropRequirementMet) public {
u.airDropClaimed = false;
u.dropRequirementMet = _dropRequirementMet;
}
function exists(bytes32 userKey) public view returns(bool) {
return airDropSet.exists(userKey);
}
function count() public view returns(uint) {
return airDropSet.count();
}
function addressToBytes32(address _address) public view returns(bytes32){
return bytes32(uint(uint160(msg.sender)));
}
function bytes32ToAddress(bytes32 _userBytes) public pure returns(address){
return address(uint160(uint(_userBytes)));
}
}
| 7,139,349 |
[
1,
20,
92,
25,
2163,
69,
27,
69,
378,
9462,
2163,
3361,
8898,
40,
21,
70,
38,
11035,
70,
21,
2226,
38,
7235,
3657,
37,
73,
3028,
11212,
24734,
2177,
3807,
261,
14891,
358,
7837,
596,
4121,
1308,
1123,
353,
3577,
358,
6932,
279,
6909,
1764,
30328,
85,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
611,
12536,
6909,
1764,
288,
203,
565,
1758,
1071,
3981,
31,
203,
377,
203,
565,
1450,
670,
1437,
773,
984,
9885,
653,
694,
5664,
364,
670,
1437,
773,
984,
9885,
653,
694,
5664,
18,
694,
31,
203,
565,
670,
1437,
773,
984,
9885,
653,
694,
5664,
18,
694,
23350,
7544,
694,
31,
203,
565,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
1958,
16753,
95,
203,
3639,
1426,
23350,
7544,
9762,
329,
31,
203,
3639,
1426,
3640,
18599,
12244,
31,
203,
565,
289,
203,
377,
203,
565,
2874,
12,
2867,
516,
1426,
13,
5204,
37,
6909,
556,
31,
203,
565,
467,
654,
39,
3462,
1071,
21649,
1345,
31,
203,
377,
203,
565,
871,
613,
1891,
12,
2867,
5793,
16,
1731,
1578,
729,
653,
16,
533,
1301,
1769,
203,
377,
203,
377,
203,
377,
203,
565,
2874,
12,
3890,
1578,
516,
16753,
13,
16753,
774,
1887,
31,
203,
565,
871,
279,
6909,
556,
13533,
12,
2867,
8027,
16,
2254,
3844,
16,
2254,
1509,
1769,
203,
565,
3885,
12,
2867,
389,
2316,
15329,
203,
3639,
3981,
273,
1234,
18,
15330,
31,
203,
3639,
21649,
1345,
273,
467,
654,
39,
3462,
24899,
2316,
1769,
203,
565,
289,
203,
377,
203,
565,
445,
1089,
4446,
12,
2867,
394,
4446,
13,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3981,
16,
315,
3700,
3981,
8863,
203,
3639,
3981,
273,
394,
4446,
31,
203,
565,
289,
203,
377,
203,
565,
445,
7516,
5157,
12,
2867,
8027,
16,
2254,
3844,
7828,
13,
2
] |
pragma solidity 0.7.6;
pragma abicoder v2;
//SPDX-License-Identifier: MIT
import "hardhat/console.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./interfaces/IArbitrator.sol";
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
contract UnbreakableVow {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
event Signed(address indexed signer, uint256 settingId);
event SettingChanged(uint256 settingId);
enum UnbreakableVowState { UNSIGNED, ACTIVE, TERMINATED }
enum UserState { UNSIGNED, SIGNED, OFFERS_TERMINATION }
struct Setting {
IArbitrator arbitrator;
string title;
bytes content;
}
struct Party {
uint256 lastSettingIdSigned;
IERC20 collateralToken;
uint256 collateralAmount;
uint256 depositedAmount;
bool offerTermination;
}
UnbreakableVowState public state = UnbreakableVowState.UNSIGNED;
uint256 public currentSettingId = 0; // All parties have to sign in order to update the setting
uint256 private nextSettingId = 1;
mapping (uint256 => Setting) private settings; // List of historic agreement settings indexed by ID (starting at 1)
EnumerableSet.AddressSet private parties;
mapping (address => Party) private partiesInfo; // Mapping of address => last agreement setting signed
/**
* @notice Initialize Agreement for "`_title`" and content "`_content`", with arbitrator `_arbitrator`
* @param _arbitrator Address of the IArbitrator that will be used to resolve disputes
* @param _title String indicating a short description
* @param _content Link to a human-readable text that describes the initial rules for the Agreement
* @param _parties List of addresses that must sign the Agreement
*/
constructor(
IArbitrator _arbitrator,
string memory _title,
bytes memory _content,
address[] memory _parties,
IERC20[] memory _collateralTokens,
uint256[] memory _collateralAmounts
) {
for (uint i = 0; i < _parties.length; i++) {
parties.add(_parties[i]);
partiesInfo[_parties[i]] = Party(0, _collateralTokens[i], _collateralAmounts[i], 0, false);
}
proposeSetting(_arbitrator, _title, _content);
}
/**
* @notice Propose and sign Agreement to title "`_title`" and content "`_content`", with arbitrator `_arbitrator`
* @dev Initialization check is implicitly provided by the `auth()` modifier
* @param _arbitrator Address of the IArbitrator that will be used to resolve disputes
* @param _title String indicating a short description
* @param _content Link to a human-readable text that describes the new rules for the Agreement
*/
function proposeSetting(
IArbitrator _arbitrator,
string memory _title,
bytes memory _content
)
public
{
sign(_newSetting(_arbitrator, _title, _content));
}
/**
* @notice Sign the agreement up-to setting #`_settingId`
* @dev Callable by any party
* @param _settingId Last setting ID the user is agreeing with
*/
function sign(uint256 _settingId) public {
uint256 lastSettingIdSigned = partiesInfo[msg.sender].lastSettingIdSigned;
require (state != UnbreakableVowState.TERMINATED, "ERROR_CAN_NOT_SIGN_TERMINATED_VOW");
require(lastSettingIdSigned != _settingId, "ERROR_SIGNER_ALREADY_SIGNED");
require(_settingId < nextSettingId, "ERROR_INVALID_SIGNING_SETTING");
// if (partiesInfo[msg.sender].depositedAmount < partiesInfo[msg.sender].collateralAmount) {
// partiesInfo[msg.sender].collateralToken.safeTransferFrom(
// msg.sender,
// address(this),
// partiesInfo[msg.sender].collateralAmount - partiesInfo[msg.sender].depositedAmount
// );
// partiesInfo[msg.sender].depositedAmount = partiesInfo[msg.sender].collateralAmount;
// }
partiesInfo[msg.sender].lastSettingIdSigned = _settingId;
emit Signed(msg.sender, _settingId);
_changeSettingIfPossible(_settingId);
}
function unstakeCollateral() public {
require (state != UnbreakableVowState.ACTIVE, "ERROR_CAN_NOT_UNSTAKE_FROM_ACTIVE_VOW");
// uint256 amount = partiesInfo[msg.sender].depositedAmount;
// partiesInfo[msg.sender].collateralToken.transfer(msg.sender, amount);
partiesInfo[msg.sender].depositedAmount = 0;
partiesInfo[msg.sender].lastSettingIdSigned = 0;
}
function terminate(bool offersTermination) public{
require (state == UnbreakableVowState.ACTIVE, "ERROR_CAN_NOT_TERMINATE_UNACTIVE_VOW");
partiesInfo[msg.sender].offerTermination = offersTermination;
_changeSettingIfPossible(0);
}
/**
* @dev Tell the information related to an agreement setting
* @param _settingId Identification number of the agreement setting
* @return arbitrator Address of the IArbitrator that will be used to resolve disputes
* @return title String indicating a short description
* @return content Link to a human-readable text that describes the current rules for the Agreement
*/
function getSetting(uint256 _settingId)
public
view
returns (IArbitrator arbitrator, string memory title, bytes memory content)
{
Setting storage setting = _getSetting(_settingId);
arbitrator = setting.arbitrator;
title = setting.title;
content = setting.content;
}
function getCurrentSetting()
public
view
returns (IArbitrator arbitrator, string memory title, bytes memory content)
{
return getSetting(currentSettingId == 0 ? 1 : currentSettingId);
}
function getParties()
external
view
returns (
address[] memory _parties,
UserState[] memory _signed,
address[] memory _collateralTokens,
uint256[] memory _collateralAmounts,
uint256[] memory _depositedAmounts
)
{
_parties = new address[](parties.length());
_signed = new UserState[](_parties.length);
_collateralTokens = new address[](_parties.length);
_collateralAmounts = new uint256[](_parties.length);
_depositedAmounts = new uint256[](_parties.length);
for(uint i=0; i < parties.length(); i++) {
_parties[i] = parties.at(i);
Party storage party = partiesInfo[_parties[i]];
_signed[i] = party.offerTermination ? UserState.OFFERS_TERMINATION : party.lastSettingIdSigned != 0? UserState.SIGNED : UserState.UNSIGNED;
_collateralTokens[i] = address(party.collateralToken);
_collateralAmounts[i] = party.collateralAmount;
_depositedAmounts[i] = party.depositedAmount;
}
}
/**
* @dev Add new agreement settings
* @param _arbitrator Address of the IArbitrator that will be used to resolve disputes
* @param _title String indicating a short description
* @param _content Link to a human-readable text that describes the new rules for the Agreement
* @return id Id of the new setting
*/
function _newSetting(
IArbitrator _arbitrator,
string memory _title,
bytes memory _content
)
internal
returns (uint256 id)
{
require(Address.isContract(address(_arbitrator)), "ERROR_ARBITRATOR_NOT_CONTRACT");
id = nextSettingId++;
Setting storage setting = settings[id];
setting.title = _title;
setting.content = _content;
setting.arbitrator = _arbitrator;
}
/**
* @dev Fetch an agreement setting instance by identification number
* @param _settingId Identification number of the agreement setting
* @return Agreement setting instance associated to the given identification number
*/
function _getSetting(uint256 _settingId) internal view returns (Setting storage) {
require(_settingId >= 0 && _settingId < nextSettingId, "ERROR_SETTING_DOES_NOT_EXIST");
return settings[_settingId];
}
function _changeSettingIfPossible(uint256 _settingId) private {
if(_settingId != 0) {
for (uint256 i = 0; i < parties.length(); i++) {
if (partiesInfo[parties.at(i)].lastSettingIdSigned != _settingId) {
return;
}
}
currentSettingId = _settingId;
state = UnbreakableVowState.ACTIVE;
emit SettingChanged(_settingId);
} else {
for (uint256 i = 0; i < parties.length(); i++) {
if (!partiesInfo[parties.at(i)].offerTermination) {
return;
}
}
state = UnbreakableVowState.TERMINATED;
}
}
}
|
Mapping of address => last agreement setting signed
|
mapping (address => Party) private partiesInfo;
| 1,760,100 |
[
1,
3233,
434,
1758,
516,
1142,
19602,
3637,
6726,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
2874,
261,
2867,
516,
6393,
93,
13,
3238,
1087,
606,
966,
31,
3639,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.16;
import "./CToken.sol";
interface CompLike {
function delegate(address delegatee) external;
}
/**
* @title Compound's CErc20 Contract
* @notice CTokens which wrap an EIP-20 underlying
* @author Compound
*/
contract CErc20 is CToken, CErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// CToken initialize does the bulk of the work
super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cNftCollateral The market in which to seize collateral from the borrower
* @param seizeIds The IDs of the NFT to seize.
* @param seizeAmounts The amount of each ID of NFT to seize.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrowNft(address borrower, uint repayAmount, CNftInterface cNftCollateral, uint[] calldata seizeIds, uint[] calldata seizeAmounts) external returns (uint) {
(uint err,) = liquidateBorrowNftInternal(borrower, repayAmount, cNftCollateral, seizeIds, seizeAmounts);
return err;
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20NonStandardInterface token) external {
require(address(token) != underlying, "CErc20::sweepToken: can not sweep underlying token");
uint256 balance = token.balanceOf(address(this));
token.transfer(admin, balance);
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
/**
* @notice Admin call to delegate the votes of the COMP-like underlying
* @param compLikeDelegatee The address to delegate votes to
* @dev CTokens whose underlying are not CompLike should revert here
*/
function _delegateCompLikeTo(address compLikeDelegatee) external {
require(msg.sender == admin, "only the admin may set the comp-like delegate");
CompLike(underlying).delegate(compLikeDelegatee);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.5.16;
/// @dev Keep in sync with CNftInterface080.sol.
contract CNftInterface {
address public underlying;
bool is1155;
address public comptroller;
bool public constant isCNft = true;
/// @notice Mapping from user to number of tokens.
mapping(address => uint256) public totalBalance;
/**
* @notice Event emitted when cNFTs are minted
*/
event Mint(address minter, uint[] mintIds, uint[] mintAmounts);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint[] redeemIds, uint[] redeemAmounts);
function seize(address liquidator, address borrower, uint256[] calldata seizeIds, uint256[] calldata seizeAmounts) external;
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./CNftInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cNftCollateral The market in which to seize collateral from the borrower
* @param seizeIds The IDs of the NFT to seize.
* @param seizeAmounts The amount of each ID of NFT to seize.
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowNftInternal(address borrower, uint repayAmount, CNftInterface cNftCollateral, uint[] memory seizeIds, uint[] memory seizeAmounts) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowNftFresh(msg.sender, borrower, repayAmount, cNftCollateral, seizeIds, seizeAmounts);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* It is the responsibility of the caller to specify the correct number of NFTs to be seized in `seizeIds` and `seizeAmounts`.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cNftCollateral The market in which to seize collateral from the borrower
* @param seizeIds The IDs of the NFT to seize.
* @param seizeAmounts The amount of each ID of NFT to seize.
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowNftFresh(address liquidator, address borrower, uint repayAmount, CNftInterface cNftCollateral, uint[] memory seizeIds, uint[] memory seizeAmounts) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cNftCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeNfts(address(this), address(cNftCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cNftCollateral.totalBalance(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_DOES_NOT_MATCH");
/* Revert if seizeTokens is greater than the number of NFTs to seize specified */
uint length = seizeIds.length;
for (uint i; i < length; ++i) {
seizeTokens -= seizeAmounts[i];
}
require(seizeTokens == 0, "LIQUIDATE_SEIZE_INCORRECT_NUM_NFTS");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
cNftCollateral.seize(liquidator, borrower, seizeIds, seizeAmounts);
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cNftCollateral), seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
struct SeizeInternalLocalVars {
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
uint liquidatorSeizeTokens;
uint protocolSeizeTokens;
uint protocolSeizeAmount;
uint exchangeRateMantissa;
uint totalReservesNew;
uint totalSupplyNew;
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
SeizeInternalLocalVars memory vars;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(vars.mathErr, vars.borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(vars.mathErr));
}
vars.protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa}));
vars.liquidatorSeizeTokens = sub_(seizeTokens, vars.protocolSeizeTokens);
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
require(vars.mathErr == MathError.NO_ERROR, "exchange rate math error");
vars.protocolSeizeAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), vars.protocolSeizeTokens);
vars.totalReservesNew = add_(totalReserves, vars.protocolSeizeAmount);
vars.totalSupplyNew = sub_(totalSupply, vars.protocolSeizeTokens);
(vars.mathErr, vars.liquidatorTokensNew) = addUInt(accountTokens[liquidator], vars.liquidatorSeizeTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
totalReserves = vars.totalReservesNew;
totalSupply = vars.totalSupplyNew;
accountTokens[borrower] = vars.borrowerTokensNew;
accountTokens[liquidator] = vars.liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, vars.liquidatorSeizeTokens);
emit Transfer(borrower, address(this), vars.protocolSeizeTokens);
emit ReservesAdded(address(this), vars.protocolSeizeAmount, vars.totalReservesNew);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma solidity ^0.5.16;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
import "./EIP20NonStandardInterface.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
/**
* @notice Share of seized collateral that is added to reserves
*/
uint public constant protocolSeizeShareMantissa = 2.8e16; //2.8%
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
function sweepToken(EIP20NonStandardInterface token) external;
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
pragma solidity ^0.5.16;
/// @dev Keep in sync with ComptrollerInterface080.sol.
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
function liquidateCalculateSeizeNfts(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
pragma solidity ^0.5.16;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
pragma solidity ^0.5.16;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
pragma solidity ^0.5.16;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract Comp {
/// @notice EIP-20 token name for this token
string public constant name = "Compound";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "COMP";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 10000000e18; // 10 million Comp
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Comp::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce");
require(now <= expiry, "Comp::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Comp::_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, "Comp::_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, "Comp::_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, "Comp::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract GovernorAlpha {
/// @notice The name of this contract
string public constant name = "Compound Governor Alpha";
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
function quorumVotes() public pure returns (uint) { return 400000e18; } // 400,000 = 4% of Comp
/// @notice The number of votes required in order for a voter to become a proposer
function proposalThreshold() public pure returns (uint) { return 100000e18; } // 100,000 = 1% of Comp
/// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions
/// @notice The delay before voting on a proposal may take place, once proposed
function votingDelay() public pure returns (uint) { return 1; } // 1 block
/// @notice The duration of voting on a proposal, in blocks
function votingPeriod() public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks)
/// @notice The address of the Compound Protocol Timelock
TimelockInterface public timelock;
/// @notice The address of the Compound governance token
CompInterface public comp;
/// @notice The address of the Governor Guardian
address public guardian;
/// @notice The total number of proposals
uint public proposalCount;
struct Proposal {
/// @notice Unique id for looking up a proposal
uint id;
/// @notice Creator of the proposal
address proposer;
/// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
/// @notice the ordered list of target addresses for calls to be made
address[] targets;
/// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
/// @notice The ordered list of function signatures to be called
string[] signatures;
/// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
/// @notice The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
/// @notice The block at which voting ends: votes must be cast prior to this block
uint endBlock;
/// @notice Current number of votes in favor of this proposal
uint forVotes;
/// @notice Current number of votes in opposition to this proposal
uint againstVotes;
/// @notice Flag marking whether the proposal has been canceled
bool canceled;
/// @notice Flag marking whether the proposal has been executed
bool executed;
/// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
/// @notice Whether or not a vote has been cast
bool hasVoted;
/// @notice Whether or not the voter supports the proposal
bool support;
/// @notice The number of votes the voter had, which were cast
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/// @notice The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
/// @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 ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint proposalId, bool support, uint votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
constructor(address timelock_, address comp_, address guardian_) public {
timelock = TimelockInterface(timelock_);
comp = CompInterface(comp_);
guardian = guardian_;
}
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorAlpha::propose: must provide actions");
require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay());
uint endBlock = add256(startBlock, votingPeriod());
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
function queue(uint proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
function execute(uint proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
function cancel(uint proposalId) public {
ProposalState state = state(proposalId);
require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == guardian || comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function castVote(uint proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature");
return _castVote(signatory, proposalId, support);
}
function _castVote(address voter, uint proposalId, bool support) internal {
require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted");
uint96 votes = comp.getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else {
proposal.againstVotes = add256(proposal.againstVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian");
timelock.acceptAdmin();
}
function __abdicate() public {
require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian");
guardian = address(0);
}
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainId() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
interface TimelockInterface {
function delay() external view returns (uint);
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface CompInterface {
function getPriorVotes(address account, uint blockNumber) external view returns (uint96);
}
pragma solidity ^0.5.16;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
import "../CErc20.sol";
import "../CToken.sol";
import "../PriceOracle.sol";
import "../EIP20Interface.sol";
import "../Governance/GovernorAlpha.sol";
import "../Governance/Comp.sol";
interface ComptrollerLensInterface {
function markets(address) external view returns (bool, uint);
function oracle() external view returns (PriceOracle);
function getAccountLiquidity(address) external view returns (uint, uint, uint);
function getAssetsIn(address) external view returns (CToken[] memory);
function claimComp(address) external;
function compAccrued(address) external view returns (uint);
}
interface GovernorBravoInterface {
struct Receipt {
bool hasVoted;
uint8 support;
uint96 votes;
}
struct Proposal {
uint id;
address proposer;
uint eta;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
uint abstainVotes;
bool canceled;
bool executed;
}
function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas);
function proposals(uint proposalId) external view returns (Proposal memory);
function getReceipt(uint proposalId, address voter) external view returns (Receipt memory);
}
contract CompoundLens {
struct CTokenMetadata {
address cToken;
uint exchangeRateCurrent;
uint supplyRatePerBlock;
uint borrowRatePerBlock;
uint reserveFactorMantissa;
uint totalBorrows;
uint totalReserves;
uint totalSupply;
uint totalCash;
bool isListed;
uint collateralFactorMantissa;
address underlyingAssetAddress;
uint cTokenDecimals;
uint underlyingDecimals;
}
function cTokenMetadata(CToken cToken) public returns (CTokenMetadata memory) {
uint exchangeRateCurrent = cToken.exchangeRateCurrent();
ComptrollerLensInterface comptroller = ComptrollerLensInterface(address(cToken.comptroller()));
(bool isListed, uint collateralFactorMantissa) = comptroller.markets(address(cToken));
address underlyingAssetAddress;
uint underlyingDecimals;
if (compareStrings(cToken.symbol(), "cETH")) {
underlyingAssetAddress = address(0);
underlyingDecimals = 18;
} else {
CErc20 cErc20 = CErc20(address(cToken));
underlyingAssetAddress = cErc20.underlying();
underlyingDecimals = EIP20Interface(cErc20.underlying()).decimals();
}
return CTokenMetadata({
cToken: address(cToken),
exchangeRateCurrent: exchangeRateCurrent,
supplyRatePerBlock: cToken.supplyRatePerBlock(),
borrowRatePerBlock: cToken.borrowRatePerBlock(),
reserveFactorMantissa: cToken.reserveFactorMantissa(),
totalBorrows: cToken.totalBorrows(),
totalReserves: cToken.totalReserves(),
totalSupply: cToken.totalSupply(),
totalCash: cToken.getCash(),
isListed: isListed,
collateralFactorMantissa: collateralFactorMantissa,
underlyingAssetAddress: underlyingAssetAddress,
cTokenDecimals: cToken.decimals(),
underlyingDecimals: underlyingDecimals
});
}
function cTokenMetadataAll(CToken[] calldata cTokens) external returns (CTokenMetadata[] memory) {
uint cTokenCount = cTokens.length;
CTokenMetadata[] memory res = new CTokenMetadata[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenMetadata(cTokens[i]);
}
return res;
}
struct CTokenBalances {
address cToken;
uint balanceOf;
uint borrowBalanceCurrent;
uint balanceOfUnderlying;
uint tokenBalance;
uint tokenAllowance;
}
function cTokenBalances(CToken cToken, address payable account) public returns (CTokenBalances memory) {
uint balanceOf = cToken.balanceOf(account);
uint borrowBalanceCurrent = cToken.borrowBalanceCurrent(account);
uint balanceOfUnderlying = cToken.balanceOfUnderlying(account);
uint tokenBalance;
uint tokenAllowance;
if (compareStrings(cToken.symbol(), "cETH")) {
tokenBalance = account.balance;
tokenAllowance = account.balance;
} else {
CErc20 cErc20 = CErc20(address(cToken));
EIP20Interface underlying = EIP20Interface(cErc20.underlying());
tokenBalance = underlying.balanceOf(account);
tokenAllowance = underlying.allowance(account, address(cToken));
}
return CTokenBalances({
cToken: address(cToken),
balanceOf: balanceOf,
borrowBalanceCurrent: borrowBalanceCurrent,
balanceOfUnderlying: balanceOfUnderlying,
tokenBalance: tokenBalance,
tokenAllowance: tokenAllowance
});
}
function cTokenBalancesAll(CToken[] calldata cTokens, address payable account) external returns (CTokenBalances[] memory) {
uint cTokenCount = cTokens.length;
CTokenBalances[] memory res = new CTokenBalances[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenBalances(cTokens[i], account);
}
return res;
}
struct CTokenUnderlyingPrice {
address cToken;
uint underlyingPrice;
}
function cTokenUnderlyingPrice(CToken cToken) public returns (CTokenUnderlyingPrice memory) {
ComptrollerLensInterface comptroller = ComptrollerLensInterface(address(cToken.comptroller()));
PriceOracle priceOracle = comptroller.oracle();
return CTokenUnderlyingPrice({
cToken: address(cToken),
underlyingPrice: priceOracle.getUnderlyingPrice(cToken)
});
}
function cTokenUnderlyingPriceAll(CToken[] calldata cTokens) external returns (CTokenUnderlyingPrice[] memory) {
uint cTokenCount = cTokens.length;
CTokenUnderlyingPrice[] memory res = new CTokenUnderlyingPrice[](cTokenCount);
for (uint i = 0; i < cTokenCount; i++) {
res[i] = cTokenUnderlyingPrice(cTokens[i]);
}
return res;
}
struct AccountLimits {
CToken[] markets;
uint liquidity;
uint shortfall;
}
function getAccountLimits(ComptrollerLensInterface comptroller, address account) public returns (AccountLimits memory) {
(uint errorCode, uint liquidity, uint shortfall) = comptroller.getAccountLiquidity(account);
require(errorCode == 0);
return AccountLimits({
markets: comptroller.getAssetsIn(account),
liquidity: liquidity,
shortfall: shortfall
});
}
struct GovReceipt {
uint proposalId;
bool hasVoted;
bool support;
uint96 votes;
}
function getGovReceipts(GovernorAlpha governor, address voter, uint[] memory proposalIds) public view returns (GovReceipt[] memory) {
uint proposalCount = proposalIds.length;
GovReceipt[] memory res = new GovReceipt[](proposalCount);
for (uint i = 0; i < proposalCount; i++) {
GovernorAlpha.Receipt memory receipt = governor.getReceipt(proposalIds[i], voter);
res[i] = GovReceipt({
proposalId: proposalIds[i],
hasVoted: receipt.hasVoted,
support: receipt.support,
votes: receipt.votes
});
}
return res;
}
struct GovBravoReceipt {
uint proposalId;
bool hasVoted;
uint8 support;
uint96 votes;
}
function getGovBravoReceipts(GovernorBravoInterface governor, address voter, uint[] memory proposalIds) public view returns (GovBravoReceipt[] memory) {
uint proposalCount = proposalIds.length;
GovBravoReceipt[] memory res = new GovBravoReceipt[](proposalCount);
for (uint i = 0; i < proposalCount; i++) {
GovernorBravoInterface.Receipt memory receipt = governor.getReceipt(proposalIds[i], voter);
res[i] = GovBravoReceipt({
proposalId: proposalIds[i],
hasVoted: receipt.hasVoted,
support: receipt.support,
votes: receipt.votes
});
}
return res;
}
struct GovProposal {
uint proposalId;
address proposer;
uint eta;
address[] targets;
uint[] values;
string[] signatures;
bytes[] calldatas;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
bool canceled;
bool executed;
}
function setProposal(GovProposal memory res, GovernorAlpha governor, uint proposalId) internal view {
(
,
address proposer,
uint eta,
uint startBlock,
uint endBlock,
uint forVotes,
uint againstVotes,
bool canceled,
bool executed
) = governor.proposals(proposalId);
res.proposalId = proposalId;
res.proposer = proposer;
res.eta = eta;
res.startBlock = startBlock;
res.endBlock = endBlock;
res.forVotes = forVotes;
res.againstVotes = againstVotes;
res.canceled = canceled;
res.executed = executed;
}
function getGovProposals(GovernorAlpha governor, uint[] calldata proposalIds) external view returns (GovProposal[] memory) {
GovProposal[] memory res = new GovProposal[](proposalIds.length);
for (uint i = 0; i < proposalIds.length; i++) {
(
address[] memory targets,
uint[] memory values,
string[] memory signatures,
bytes[] memory calldatas
) = governor.getActions(proposalIds[i]);
res[i] = GovProposal({
proposalId: 0,
proposer: address(0),
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: 0,
endBlock: 0,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
setProposal(res[i], governor, proposalIds[i]);
}
return res;
}
struct GovBravoProposal {
uint proposalId;
address proposer;
uint eta;
address[] targets;
uint[] values;
string[] signatures;
bytes[] calldatas;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
uint abstainVotes;
bool canceled;
bool executed;
}
function setBravoProposal(GovBravoProposal memory res, GovernorBravoInterface governor, uint proposalId) internal view {
GovernorBravoInterface.Proposal memory p = governor.proposals(proposalId);
res.proposalId = proposalId;
res.proposer = p.proposer;
res.eta = p.eta;
res.startBlock = p.startBlock;
res.endBlock = p.endBlock;
res.forVotes = p.forVotes;
res.againstVotes = p.againstVotes;
res.abstainVotes = p.abstainVotes;
res.canceled = p.canceled;
res.executed = p.executed;
}
function getGovBravoProposals(GovernorBravoInterface governor, uint[] calldata proposalIds) external view returns (GovBravoProposal[] memory) {
GovBravoProposal[] memory res = new GovBravoProposal[](proposalIds.length);
for (uint i = 0; i < proposalIds.length; i++) {
(
address[] memory targets,
uint[] memory values,
string[] memory signatures,
bytes[] memory calldatas
) = governor.getActions(proposalIds[i]);
res[i] = GovBravoProposal({
proposalId: 0,
proposer: address(0),
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: 0,
endBlock: 0,
forVotes: 0,
againstVotes: 0,
abstainVotes: 0,
canceled: false,
executed: false
});
setBravoProposal(res[i], governor, proposalIds[i]);
}
return res;
}
struct CompBalanceMetadata {
uint balance;
uint votes;
address delegate;
}
function getCompBalanceMetadata(Comp comp, address account) external view returns (CompBalanceMetadata memory) {
return CompBalanceMetadata({
balance: comp.balanceOf(account),
votes: uint256(comp.getCurrentVotes(account)),
delegate: comp.delegates(account)
});
}
struct CompBalanceMetadataExt {
uint balance;
uint votes;
address delegate;
uint allocated;
}
function getCompBalanceMetadataExt(Comp comp, ComptrollerLensInterface comptroller, address account) external returns (CompBalanceMetadataExt memory) {
uint balance = comp.balanceOf(account);
comptroller.claimComp(account);
uint newBalance = comp.balanceOf(account);
uint accrued = comptroller.compAccrued(account);
uint total = add(accrued, newBalance, "sum comp total");
uint allocated = sub(total, balance, "sub allocated");
return CompBalanceMetadataExt({
balance: balance,
votes: uint256(comp.getCurrentVotes(account)),
delegate: comp.delegates(account),
allocated: allocated
});
}
struct CompVotes {
uint blockNumber;
uint votes;
}
function getCompVotes(Comp comp, address account, uint32[] calldata blockNumbers) external view returns (CompVotes[] memory) {
CompVotes[] memory res = new CompVotes[](blockNumbers.length);
for (uint i = 0; i < blockNumbers.length; i++) {
res[i] = CompVotes({
blockNumber: uint256(blockNumbers[i]),
votes: uint256(comp.getPriorVotes(account, blockNumbers[i]))
});
}
return res;
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
}
pragma solidity ^0.5.16;
import "./CToken.sol";
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CToken cToken) external view returns (uint);
}
|
@dev Keep in sync with CNftInterface080.sol.
|
contract CNftInterface {
address public underlying;
bool is1155;
address public comptroller;
bool public constant isCNft = true;
mapping(address => uint256) public totalBalance;
event Mint(address minter, uint[] mintIds, uint[] mintAmounts);
event Redeem(address redeemer, uint[] redeemIds, uint[] redeemAmounts);
function seize(address liquidator, address borrower, uint256[] calldata seizeIds, uint256[] calldata seizeAmounts) external;
pragma solidity ^0.5.16;
}
| 11,903,095 |
[
1,
11523,
316,
3792,
598,
13326,
1222,
1358,
20,
3672,
18,
18281,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
13326,
1222,
1358,
288,
203,
565,
1758,
1071,
6808,
31,
203,
565,
1426,
353,
2499,
2539,
31,
203,
565,
1758,
1071,
532,
337,
1539,
31,
203,
565,
1426,
1071,
5381,
353,
12821,
1222,
273,
638,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
2078,
13937,
31,
203,
203,
565,
871,
490,
474,
12,
2867,
1131,
387,
16,
2254,
8526,
312,
474,
2673,
16,
2254,
8526,
312,
474,
6275,
87,
1769,
203,
203,
565,
871,
868,
24903,
12,
2867,
283,
24903,
264,
16,
2254,
8526,
283,
24903,
2673,
16,
2254,
8526,
283,
24903,
6275,
87,
1769,
203,
203,
565,
445,
695,
554,
12,
2867,
4501,
26595,
639,
16,
1758,
29759,
264,
16,
2254,
5034,
8526,
745,
892,
695,
554,
2673,
16,
2254,
5034,
8526,
745,
892,
695,
554,
6275,
87,
13,
3903,
31,
203,
683,
9454,
18035,
560,
3602,
20,
18,
25,
18,
2313,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
* Lottery oracle
*
* Copyright (C) 2017-2019 Hubii AS
*/
pragma solidity ^0.5.11;
import {Resolvable} from "./Resolvable.sol";
import {RBACed} from "./RBACed.sol";
import {Able} from "./Able.sol";
import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import {VerificationPhaseLib} from "./VerificationPhaseLib.sol";
import {BountyFund} from "./BountyFund.sol";
import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
/// @title ResolutionEngine
/// @author Jens Ivar Jørdre <[email protected]>
/// @notice A resolution engine base contract
contract ResolutionEngine is Resolvable, RBACed, Able {
using SafeMath for uint256;
using VerificationPhaseLib for VerificationPhaseLib.VerificationPhase;
event Frozen();
event BountyAllocatorSet(address indexed _bountyAllocator);
event Staked(address indexed _wallet, uint256 indexed _verificationPhaseNumber, bool _status,
uint256 _amount);
event BountyWithdrawn(address indexed _wallet, uint256 _bountyAmount);
event VerificationPhaseOpened(uint256 indexed _verificationPhaseNumber, uint256 _bountyAmount);
event VerificationPhaseClosed(uint256 indexed _verificationPhaseNumber);
event PayoutStaged(address indexed _wallet, uint256 indexed _firstVerificationPhaseNumber,
uint256 indexed _lastVerificationPhaseNumber, uint256 _payout);
event StakeStaged(address indexed _wallet, uint _amount);
event Staged(address indexed _wallet, uint _amount);
event Withdrawn(address indexed _wallet, uint _amount);
string constant public STAKE_ACTION = "STAKE";
string constant public RESOLVE_ACTION = "RESOLVE";
address public oracle;
address public operator;
address public bountyAllocator;
BountyFund public bountyFund;
ERC20 public token;
bool public frozen;
uint256 public verificationPhaseNumber;
mapping(uint256 => VerificationPhaseLib.VerificationPhase) public verificationPhaseByPhaseNumber;
mapping(address => mapping(bool => uint256)) public stakedAmountByWalletStatus;
mapping(uint256 => mapping(bool => uint256)) public stakedAmountByBlockStatus;
VerificationPhaseLib.Status public verificationStatus;
mapping(address => mapping(uint256 => bool)) public payoutStagedByWalletPhase;
mapping(address => uint256) public stagedAmountByWallet;
/// @notice `msg.sender` will be added as accessor to the owner role
constructor(address _oracle, address _operator, address _bountyFund)
public
{
// Initialize oracle and operator
oracle = _oracle;
operator = _operator;
// Initialize bounty fund
bountyFund = BountyFund(_bountyFund);
bountyFund.setResolutionEngine(address(this));
// Initialize token to the one of bounty fund
token = ERC20(bountyFund.token());
}
modifier onlyOracle() {
require(msg.sender == oracle, "ResolutionEngine: sender is not the defined oracle");
_;
}
modifier onlyOperator() {
require(msg.sender == operator, "ResolutionEngine: sender is not the defined operator");
_;
}
modifier onlyNotFrozen() {
require(!frozen, "ResolutionEngine: is frozen");
_;
}
/// @notice Freeze updates to this resolution engine
/// @dev This operation can not be undone
function freeze()
public
onlyRoleAccessor(OWNER_ROLE)
{
// Set the frozen flag
frozen = true;
// Emit event
emit Frozen();
}
/// @notice Set the bounty allocator
/// @param _bountyAllocator The bounty allocator to be set
function setBountyAllocator(address _bountyAllocator)
public
onlyRoleAccessor(OWNER_ROLE)
{
// Set the bounty allocator
bountyAllocator = _bountyAllocator;
// Emit event
emit BountyAllocatorSet(bountyAllocator);
}
/// @notice Initialize the engine
function initialize()
public
onlyRoleAccessor(OWNER_ROLE)
{
// Require no previous initialization
require(0 == verificationPhaseNumber, "ResolutionEngine: already initialized");
// Open verification phase
_openVerificationPhase();
}
/// @notice Disable the given action
/// @param _action The action to disable
function disable(string memory _action)
public
onlyOperator
{
// Disable
super.disable(_action);
}
/// @notice Enable the given action
/// @param _action The action to enable
function enable(string memory _action)
public
onlyOperator
{
// Enable
super.enable(_action);
}
/// @notice Stake by updating metrics
/// @dev The function can only be called by oracle.
/// @param _wallet The concerned wallet
/// @param _status The status staked at
/// @param _amount The amount staked
function stake(address _wallet, bool _status, uint256 _amount)
public
onlyOracle
onlyEnabled(STAKE_ACTION)
{
// Update metrics
stakedAmountByWalletStatus[_wallet][_status] = stakedAmountByWalletStatus[_wallet][_status].add(_amount);
stakedAmountByBlockStatus[block.number][_status] = stakedAmountByBlockStatus[block.number][_status]
.add(_amount);
verificationPhaseByPhaseNumber[verificationPhaseNumber].stake(_wallet, _status, _amount);
// Emit event
emit Staked(_wallet, verificationPhaseNumber, _status, _amount);
}
/// @notice Resolve the market in the current verification phase if resolution criteria have been met
/// @dev The function can only be called by oracle.
/// be the current verification phase number
function resolveIfCriteriaMet()
public
onlyOracle
onlyEnabled(RESOLVE_ACTION)
{
// If resolution criteria are met...
if (resolutionCriteriaMet()) {
// Close existing verification phase
_closeVerificationPhase();
// Open new verification phase
_openVerificationPhase();
}
}
/// @notice Get the metrics for the given verification phase number
/// @param _verificationPhaseNumber The concerned verification phase number
/// @return the metrics
function metricsByVerificationPhaseNumber(uint256 _verificationPhaseNumber)
public
view
returns (VerificationPhaseLib.State state, uint256 trueStakeAmount, uint256 falseStakeAmount,
uint256 stakeAmount, uint256 numberOfWallets, uint256 bountyAmount, bool bountyAwarded,
uint256 startBlock, uint256 endBlock, uint256 numberOfBlocks)
{
state = verificationPhaseByPhaseNumber[_verificationPhaseNumber].state;
trueStakeAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber].stakedAmountByStatus[true];
falseStakeAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber].stakedAmountByStatus[false];
stakeAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber].stakedAmount;
numberOfWallets = verificationPhaseByPhaseNumber[_verificationPhaseNumber].stakingWallets;
bountyAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber].bountyAmount;
bountyAwarded = verificationPhaseByPhaseNumber[_verificationPhaseNumber].bountyAwarded;
startBlock = verificationPhaseByPhaseNumber[_verificationPhaseNumber].startBlock;
endBlock = verificationPhaseByPhaseNumber[_verificationPhaseNumber].endBlock;
numberOfBlocks = (startBlock > 0 && endBlock == 0 ? block.number : endBlock).sub(startBlock);
}
/// @notice Get the metrics for the given verification phase number and wallet
/// @dev Reverts if provided verification phase number is higher than current verification phase number
/// @param _verificationPhaseNumber The concerned verification phase number
/// @param _wallet The address of the concerned wallet
/// @return the metrics
function metricsByVerificationPhaseNumberAndWallet(uint256 _verificationPhaseNumber, address _wallet)
public
view
returns (uint256 trueStakeAmount, uint256 falseStakeAmount, uint256 stakeAmount)
{
trueStakeAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber]
.stakedAmountByWalletStatus[_wallet][true];
falseStakeAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber]
.stakedAmountByWalletStatus[_wallet][false];
stakeAmount = trueStakeAmount.add(falseStakeAmount);
}
/// @notice Get the metrics for the wallet
/// @param _wallet The address of the concerned wallet
/// @return the metrics
function metricsByWallet(address _wallet)
public
view
returns (uint256 trueStakeAmount, uint256 falseStakeAmount, uint256 stakeAmount)
{
trueStakeAmount = stakedAmountByWalletStatus[_wallet][true];
falseStakeAmount = stakedAmountByWalletStatus[_wallet][false];
stakeAmount = trueStakeAmount.add(falseStakeAmount);
}
/// @notice Get the metrics for the block
/// @dev Reverts if provided block number is higher than current block number
/// @param _blockNumber The concerned block number
/// @return the metrics
function metricsByBlockNumber(uint256 _blockNumber)
public
view
returns (uint256 trueStakeAmount, uint256 falseStakeAmount, uint256 stakeAmount)
{
trueStakeAmount = stakedAmountByBlockStatus[_blockNumber][true];
falseStakeAmount = stakedAmountByBlockStatus[_blockNumber][false];
stakeAmount = trueStakeAmount.add(falseStakeAmount);
}
/// @notice Calculate the payout accrued by given wallet in the inclusive range of given verification phase numbers
/// @param _firstVerificationPhaseNumber The first verification phase number to stage payout from
/// @param _lastVerificationPhaseNumber The last verification phase number to stage payout from
/// @param _wallet The address of the concerned wallet
/// @return the payout
function calculatePayout(address _wallet, uint256 _firstVerificationPhaseNumber,
uint256 _lastVerificationPhaseNumber)
public
view
returns (uint256)
{
// For each verification phase number in the inclusive range calculate payout
uint256 payout = 0;
for (uint256 i = _firstVerificationPhaseNumber; i <= _lastVerificationPhaseNumber; i++)
payout = payout.add(_calculatePayout(_wallet, i));
// Return payout
return payout;
}
/// @notice Stage the payout accrued by given wallet in the inclusive range of given verification phase numbers
/// @dev The function can only be called by oracle.
/// @param _wallet The address of the concerned wallet
/// @param _firstVerificationPhaseNumber The first verification phase number to stage payout from
/// @param _lastVerificationPhaseNumber The last verification phase number to stage payout from
function stagePayout(address _wallet, uint256 _firstVerificationPhaseNumber,
uint256 _lastVerificationPhaseNumber)
public
onlyOracle
{
// For each verification phase number in the inclusive range stage payout
uint256 amount = 0;
for (uint256 i = _firstVerificationPhaseNumber; i <= _lastVerificationPhaseNumber; i++)
amount = amount.add(_stagePayout(_wallet, i));
// Emit event
emit PayoutStaged(_wallet, _firstVerificationPhaseNumber, _lastVerificationPhaseNumber, amount);
}
/// @notice Stage the amount staked in the current verification phase
/// @dev The function can only be called by oracle and when resolve action has been disabled
/// @param _wallet The address of the concerned wallet
function stageStake(address _wallet)
public
onlyOracle
onlyDisabled(RESOLVE_ACTION)
{
// Calculate the amount staked by the wallet
uint256 amount = verificationPhaseByPhaseNumber[verificationPhaseNumber]
.stakedAmountByWalletStatus[_wallet][true].add(
verificationPhaseByPhaseNumber[verificationPhaseNumber]
.stakedAmountByWalletStatus[_wallet][false]
);
// Require no previous stage stage
require(0 < amount, "ResolutionEngine: stake is zero");
// Reset wallet's stakes
verificationPhaseByPhaseNumber[verificationPhaseNumber].stakedAmountByWalletStatus[_wallet][true] = 0;
verificationPhaseByPhaseNumber[verificationPhaseNumber].stakedAmountByWalletStatus[_wallet][false] = 0;
// Stage the amount
_stage(_wallet, amount);
// Emit event
emit StakeStaged(_wallet, amount);
}
/// @notice Stage the given amount
/// @dev The function can only be called by oracle.
/// @param _wallet The address of the concerned wallet
/// @param _amount The amount to be staged
function stage(address _wallet, uint256 _amount)
public
onlyOracle
{
// Stage the amount
_stage(_wallet, _amount);
// Emit event
emit Staged(_wallet, _amount);
}
/// @notice Withdraw the given amount
/// @dev The function can only be called by oracle.
/// @param _wallet The address of the concerned wallet
/// @param _amount The amount to be withdrawn
function withdraw(address _wallet, uint256 _amount)
public
onlyOracle
{
// Require that the withdrawal amount is smaller than the wallet's staged amount
require(_amount <= stagedAmountByWallet[_wallet], "ResolutionEngine: amount is greater than staged amount");
// Unstage the amount
stagedAmountByWallet[_wallet] = stagedAmountByWallet[_wallet].sub(_amount);
// Transfer the amount
token.transfer(_wallet, _amount);
// Emit event
emit Withdrawn(_wallet, _amount);
}
/// @notice Stage the bounty to the given address
/// @param _wallet The recipient address of the bounty transfer
function withdrawBounty(address _wallet)
public
onlyOperator
onlyDisabled(RESOLVE_ACTION)
{
// Require no previous bounty withdrawal
require(0 < verificationPhaseByPhaseNumber[verificationPhaseNumber].bountyAmount,
"ResolutionEngine: bounty is zero");
// Store the bounty amount locally
uint256 amount = verificationPhaseByPhaseNumber[verificationPhaseNumber].bountyAmount;
// Reset the bounty amount
verificationPhaseByPhaseNumber[verificationPhaseNumber].bountyAmount = 0;
// Transfer the amount
token.transfer(_wallet, amount);
// Emit event
emit BountyWithdrawn(_wallet, amount);
}
/// @notice Open verification phase
function _openVerificationPhase()
internal
{
// Require that verification phase is not open
require(
verificationPhaseByPhaseNumber[verificationPhaseNumber.add(1)].state == VerificationPhaseLib.State.Unopened,
"ResolutionEngine: verification phase is not in unopened state"
);
// Bump verification phase number
verificationPhaseNumber = verificationPhaseNumber.add(1);
// Allocate from bounty fund using the set bounty allocator
uint256 bountyAmount = bountyFund.allocateTokens(bountyAllocator);
// Open the verification phase
verificationPhaseByPhaseNumber[verificationPhaseNumber].open(bountyAmount);
// Add criteria params
_addVerificationCriteria();
// Emit event
emit VerificationPhaseOpened(verificationPhaseNumber, bountyAmount);
}
/// @notice Augment the verification phase with verification criteria params
function _addVerificationCriteria() internal;
/// @notice Close verification phase
function _closeVerificationPhase()
internal
{
// Require that verification phase is open
require(verificationPhaseByPhaseNumber[verificationPhaseNumber].state == VerificationPhaseLib.State.Opened,
"ResolutionEngine: verification phase is not in opened state");
// Close the verification phase
verificationPhaseByPhaseNumber[verificationPhaseNumber].close();
// If new verification status...
if (verificationPhaseByPhaseNumber[verificationPhaseNumber].result != verificationStatus) {
// Update verification status of this resolution engine
verificationStatus = verificationPhaseByPhaseNumber[verificationPhaseNumber].result;
// Award bounty to this verification phase
verificationPhaseByPhaseNumber[verificationPhaseNumber].bountyAwarded = true;
}
// Emit event
emit VerificationPhaseClosed(verificationPhaseNumber);
}
/// @notice Calculate payout of given wallet and verification phase number
function _calculatePayout(address _wallet, uint256 _verificationPhaseNumber)
internal
view
returns (uint256)
{
// Return 0 if no non-null verification status has been obtained
if (VerificationPhaseLib.Status.Null == verificationPhaseByPhaseNumber[_verificationPhaseNumber].result)
return 0;
// Get the status obtained by the verification phase
bool status =
verificationPhaseByPhaseNumber[_verificationPhaseNumber].result == VerificationPhaseLib.Status.True;
// Get the lot staked opposite of status
uint256 lot = verificationPhaseByPhaseNumber[_verificationPhaseNumber].stakedAmountByStatus[!status];
// If bounty was awarded add bounty to the total lot
if (verificationPhaseByPhaseNumber[_verificationPhaseNumber].bountyAwarded)
lot = lot.add(verificationPhaseByPhaseNumber[_verificationPhaseNumber].bountyAmount);
// Get the amount the wallet staked and total amount staked on the obtained status
uint256 walletStatusAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber]
.stakedAmountByWalletStatus[_wallet][status];
uint256 statusAmount = verificationPhaseByPhaseNumber[_verificationPhaseNumber]
.stakedAmountByStatus[status];
// Return the lot scaled by the fractional contribution that wallet staked on the obtained status and
// to this added the wallet's own staked amount
return lot.mul(walletStatusAmount).div(statusAmount).add(walletStatusAmount);
}
/// @notice Stage payout of given wallet and verification phase number
function _stagePayout(address _wallet, uint256 _verificationPhaseNumber)
internal
returns (uint256)
{
// Return if the verification phase has not been closed
if (VerificationPhaseLib.State.Closed != verificationPhaseByPhaseNumber[_verificationPhaseNumber].state)
return 0;
// Return wallet payout has already been staged for this verification phase number
if (payoutStagedByWalletPhase[_wallet][_verificationPhaseNumber])
return 0;
// Register payout of wallet and verification phase number
payoutStagedByWalletPhase[_wallet][_verificationPhaseNumber] = true;
// Calculate payout
uint256 payout = _calculatePayout(_wallet, _verificationPhaseNumber);
// Stage the payout
_stage(_wallet, payout);
// Return payout amount
return payout;
}
/// @notice Stage the given amount for the given wallet
function _stage(address _wallet, uint256 _amount)
internal
{
stagedAmountByWallet[_wallet] = stagedAmountByWallet[_wallet].add(_amount);
}
}
|
@notice Enable the given action @param _action The action to enable Enable
|
function enable(string memory _action)
public
onlyOperator
{
super.enable(_action);
}
| 2,545,666 |
[
1,
8317,
326,
864,
1301,
225,
389,
1128,
1021,
1301,
358,
4237,
9677,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4237,
12,
1080,
3778,
389,
1128,
13,
203,
565,
1071,
203,
565,
1338,
5592,
203,
565,
288,
203,
3639,
2240,
18,
7589,
24899,
1128,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/100/0x3De1dC9D45Eaaf22c3006BAa580f2d612A940b99/sources/StakingAuRa.sol
|
rewardWasTaken[stakingAddress][stakingAddress][epoch] = false;
|
function stakeAmountByCurrentEpoch(address _poolStakingAddress, address _delegatorOrZero)
public
view
returns(uint256)
}
}
for (uint256 p = 0; p < poolsNumber; p++) {
address stakingAddress = _pools[p];
for (uint256 epoch = 0; epoch < currentStakingEpoch; epoch++) {
bool rewardTaken = rewardWasTaken[stakingAddress][stakingAddress][epoch];
if (rewardTaken) {
rewardWasTaken[stakingAddress][address(0)][epoch] = rewardTaken;
}
}
}
| 16,648,451 |
[
1,
266,
2913,
14992,
27486,
63,
334,
6159,
1887,
6362,
334,
6159,
1887,
6362,
12015,
65,
273,
629,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
384,
911,
6275,
858,
3935,
14638,
12,
2867,
389,
6011,
510,
6159,
1887,
16,
1758,
389,
3771,
1332,
639,
1162,
7170,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
12,
11890,
5034,
13,
203,
565,
289,
203,
203,
565,
289,
203,
203,
3639,
364,
261,
11890,
5034,
293,
273,
374,
31,
293,
411,
16000,
1854,
31,
293,
27245,
288,
203,
5411,
1758,
384,
6159,
1887,
273,
389,
27663,
63,
84,
15533,
203,
203,
5411,
364,
261,
11890,
5034,
7632,
273,
374,
31,
7632,
411,
783,
510,
6159,
14638,
31,
7632,
27245,
288,
203,
7734,
1426,
19890,
27486,
273,
19890,
14992,
27486,
63,
334,
6159,
1887,
6362,
334,
6159,
1887,
6362,
12015,
15533,
203,
7734,
309,
261,
266,
2913,
27486,
13,
288,
203,
10792,
19890,
14992,
27486,
63,
334,
6159,
1887,
6362,
2867,
12,
20,
13,
6362,
12015,
65,
273,
19890,
27486,
31,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xaE5ee66910b1cd843638B3B23C997F33590d34A9/sources/project_/contracts/UserOperation.sol
|
lighter signature scheme. must match UserOp.ts#packUserOp copy directly the userOp from calldata up to (but not including) the signature. this encoding depends on the ABI encoding of calldata, but is much lighter to copy than referencing each field separately.
|
function pack(UserOperation calldata userOp)
internal
pure
returns (bytes memory ret)
{
bytes calldata sig = userOp.signature;
assembly {
let ofs := userOp
let len := sub(sub(sig.offset, ofs), 32)
ret := mload(0x40)
mstore(0x40, add(ret, add(len, 32)))
mstore(ret, len)
calldatacopy(add(ret, 32), ofs, len)
}
}
| 11,603,875 |
[
1,
23624,
3372,
4355,
18,
1297,
845,
2177,
3817,
18,
88,
1752,
484,
1299,
3817,
1610,
5122,
326,
729,
3817,
628,
745,
892,
731,
358,
261,
12885,
486,
6508,
13,
326,
3372,
18,
333,
2688,
10935,
603,
326,
10336,
45,
2688,
434,
745,
892,
16,
1496,
353,
9816,
328,
18117,
358,
1610,
2353,
24509,
1517,
652,
18190,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2298,
12,
1299,
2988,
745,
892,
729,
3817,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
3890,
3778,
325,
13,
203,
565,
288,
203,
3639,
1731,
745,
892,
3553,
273,
729,
3817,
18,
8195,
31,
203,
3639,
19931,
288,
203,
5411,
2231,
26927,
519,
729,
3817,
203,
5411,
2231,
562,
519,
720,
12,
1717,
12,
7340,
18,
3348,
16,
26927,
3631,
3847,
13,
203,
5411,
325,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
5411,
312,
2233,
12,
20,
92,
7132,
16,
527,
12,
1349,
16,
527,
12,
1897,
16,
3847,
20349,
203,
5411,
312,
2233,
12,
1349,
16,
562,
13,
203,
5411,
745,
892,
3530,
12,
1289,
12,
1349,
16,
3847,
3631,
26927,
16,
562,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xA3abb32c657adA8803bF6AEEF6Eb42B29c74bf28/sources/contracts/SmartYield.sol
|
burns Junior locked tokens reducing the jToken supply
|
_burn(address(this), jBondsAt.tokens);
| 2,993,940 |
[
1,
70,
321,
87,
804,
318,
9659,
8586,
2430,
9299,
2822,
326,
525,
1345,
14467,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
389,
70,
321,
12,
2867,
12,
2211,
3631,
525,
26090,
861,
18,
7860,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// hevm: flattened sources of src/DssSpell.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.6.12 >=0.6.12 <0.7.0;
// pragma experimental ABIEncoderV2;
////// lib/dss-exec-lib/src/CollateralOpts.sol
/* pragma solidity ^0.6.12; */
struct CollateralOpts {
bytes32 ilk;
address gem;
address join;
address clip;
address calc;
address pip;
bool isLiquidatable;
bool isOSM;
bool whitelistOSM;
uint256 ilkDebtCeiling;
uint256 minVaultAmount;
uint256 maxLiquidationAmount;
uint256 liquidationPenalty;
uint256 ilkStabilityFee;
uint256 startingPriceFactor;
uint256 breakerTolerance;
uint256 auctionDuration;
uint256 permittedDrop;
uint256 liquidationRatio;
uint256 kprFlatReward;
uint256 kprPctReward;
}
////// lib/dss-exec-lib/src/DssExecLib.sol
//
// DssExecLib.sol -- MakerDAO Executive Spellcrafting Library
//
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc.
//
// 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.6.12; */
/* // pragma experimental ABIEncoderV2; */
/* import { CollateralOpts } from "./CollateralOpts.sol"; */
interface Initializable {
function init(bytes32) external;
}
interface Authorizable {
function rely(address) external;
function deny(address) external;
}
interface Fileable {
function file(bytes32, address) external;
function file(bytes32, uint256) external;
function file(bytes32, bytes32, uint256) external;
function file(bytes32, bytes32, address) external;
}
interface Drippable {
function drip() external returns (uint256);
function drip(bytes32) external returns (uint256);
}
interface Pricing {
function poke(bytes32) external;
}
interface ERC20 {
function decimals() external returns (uint8);
}
interface DssVat {
function hope(address) external;
function nope(address) external;
function ilks(bytes32) external returns (uint256 Art, uint256 rate, uint256 spot, uint256 line, uint256 dust);
function Line() external view returns (uint256);
function suck(address, address, uint) external;
}
interface ClipLike {
function vat() external returns (address);
function dog() external returns (address);
function spotter() external view returns (address);
function calc() external view returns (address);
function ilk() external returns (bytes32);
}
interface DogLike {
function ilks(bytes32) external returns (address clip, uint256 chop, uint256 hole, uint256 dirt);
}
interface JoinLike {
function vat() external returns (address);
function ilk() external returns (bytes32);
function gem() external returns (address);
function dec() external returns (uint256);
function join(address, uint) external;
function exit(address, uint) external;
}
// Includes Median and OSM functions
interface OracleLike_2 {
function src() external view returns (address);
function lift(address[] calldata) external;
function drop(address[] calldata) external;
function setBar(uint256) external;
function kiss(address) external;
function diss(address) external;
function kiss(address[] calldata) external;
function diss(address[] calldata) external;
function orb0() external view returns (address);
function orb1() external view returns (address);
}
interface MomLike {
function setOsm(bytes32, address) external;
function setPriceTolerance(address, uint256) external;
}
interface RegistryLike {
function add(address) external;
function xlip(bytes32) external view returns (address);
}
// https://github.com/makerdao/dss-chain-log
interface ChainlogLike {
function setVersion(string calldata) external;
function setIPFS(string calldata) external;
function setSha256sum(string calldata) external;
function getAddress(bytes32) external view returns (address);
function setAddress(bytes32, address) external;
function removeAddress(bytes32) external;
}
interface IAMLike {
function ilks(bytes32) external view returns (uint256,uint256,uint48,uint48,uint48);
function setIlk(bytes32,uint256,uint256,uint256) external;
function remIlk(bytes32) external;
function exec(bytes32) external returns (uint256);
}
interface LerpFactoryLike {
function newLerp(bytes32 name_, address target_, bytes32 what_, uint256 startTime_, uint256 start_, uint256 end_, uint256 duration_) external returns (address);
function newIlkLerp(bytes32 name_, address target_, bytes32 ilk_, bytes32 what_, uint256 startTime_, uint256 start_, uint256 end_, uint256 duration_) external returns (address);
}
interface LerpLike {
function tick() external returns (uint256);
}
library DssExecLib {
/* WARNING
The following library code acts as an interface to the actual DssExecLib
library, which can be found in its own deployed contract. Only trust the actual
library's implementation.
*/
address constant public LOG = 0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F;
uint256 constant internal WAD = 10 ** 18;
uint256 constant internal RAY = 10 ** 27;
uint256 constant internal RAD = 10 ** 45;
uint256 constant internal THOUSAND = 10 ** 3;
uint256 constant internal MILLION = 10 ** 6;
uint256 constant internal BPS_ONE_PCT = 100;
uint256 constant internal BPS_ONE_HUNDRED_PCT = 100 * BPS_ONE_PCT;
uint256 constant internal RATES_ONE_HUNDRED_PCT = 1000000021979553151239153027;
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {}
function cat() public view returns (address) { return getChangelogAddress("MCD_CAT"); }
function dog() public view returns (address) { return getChangelogAddress("MCD_DOG"); }
function end() public view returns (address) { return getChangelogAddress("MCD_END"); }
function reg() public view returns (address) { return getChangelogAddress("ILK_REGISTRY"); }
function autoLine() public view returns (address) { return getChangelogAddress("MCD_IAM_AUTO_LINE"); }
function lerpFab() public view returns (address) { return getChangelogAddress("LERP_FAB"); }
function clip(bytes32 _ilk) public view returns (address _clip) {}
function flip(bytes32 _ilk) public view returns (address _flip) {}
function calc(bytes32 _ilk) public view returns (address _calc) {}
function getChangelogAddress(bytes32 _key) public view returns (address) {}
function canCast(uint40 _ts, bool _officeHours) public pure returns (bool) {}
function nextCastTime(uint40 _eta, uint40 _ts, bool _officeHours) public pure returns (uint256 castTime) {}
function setValue(address _base, bytes32 _what, uint256 _amt) public {}
function setValue(address _base, bytes32 _ilk, bytes32 _what, uint256 _amt) public {}
function setIlkAutoLineParameters(bytes32 _ilk, uint256 _amount, uint256 _gap, uint256 _ttl) public {}
function setIlkMaxLiquidationAmount(bytes32 _ilk, uint256 _amount) public {}
function setStartingPriceMultiplicativeFactor(bytes32 _ilk, uint256 _pct_bps) public {}
function linearInterpolation(bytes32 _name, address _target, bytes32 _ilk, bytes32 _what, uint256 _startTime, uint256 _start, uint256 _end, uint256 _duration) public returns (address) {}
}
////// lib/dss-exec-lib/src/DssAction.sol
//
// DssAction.sol -- DSS Executive Spell Actions
//
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc.
//
// 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.6.12; */
/* import { DssExecLib } from "./DssExecLib.sol"; */
/* import { CollateralOpts } from "./CollateralOpts.sol"; */
interface OracleLike_1 {
function src() external view returns (address);
}
abstract contract DssAction {
using DssExecLib for *;
// Modifier used to limit execution time when office hours is enabled
modifier limited {
require(DssExecLib.canCast(uint40(block.timestamp), officeHours()), "Outside office hours");
_;
}
// Office Hours defaults to true by default.
// To disable office hours, override this function and
// return false in the inherited action.
function officeHours() public virtual returns (bool) {
return true;
}
// DssExec calls execute. We limit this function subject to officeHours modifier.
function execute() external limited {
actions();
}
// DssAction developer must override `actions()` and place all actions to be called inside.
// The DssExec function will call this subject to the officeHours limiter
// By keeping this function public we allow simulations of `execute()` on the actions outside of the cast time.
function actions() public virtual;
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)"
function description() external virtual view returns (string memory);
// Returns the next available cast time
function nextCastTime(uint256 eta) external returns (uint256 castTime) {
require(eta <= uint40(-1));
castTime = DssExecLib.nextCastTime(uint40(eta), uint40(block.timestamp), officeHours());
}
}
////// lib/dss-exec-lib/src/DssExec.sol
//
// DssExec.sol -- MakerDAO Executive Spell Template
//
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc.
//
// 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.6.12; */
interface PauseAbstract {
function delay() external view returns (uint256);
function plot(address, bytes32, bytes calldata, uint256) external;
function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory);
}
interface Changelog {
function getAddress(bytes32) external view returns (address);
}
interface SpellAction {
function officeHours() external view returns (bool);
function description() external view returns (string memory);
function nextCastTime(uint256) external view returns (uint256);
}
contract DssExec {
Changelog constant public log = Changelog(0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F);
uint256 public eta;
bytes public sig;
bool public done;
bytes32 immutable public tag;
address immutable public action;
uint256 immutable public expiration;
PauseAbstract immutable public pause;
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)"
function description() external view returns (string memory) {
return SpellAction(action).description();
}
function officeHours() external view returns (bool) {
return SpellAction(action).officeHours();
}
function nextCastTime() external view returns (uint256 castTime) {
return SpellAction(action).nextCastTime(eta);
}
// @param _description A string description of the spell
// @param _expiration The timestamp this spell will expire. (Ex. now + 30 days)
// @param _spellAction The address of the spell action
constructor(uint256 _expiration, address _spellAction) public {
pause = PauseAbstract(log.getAddress("MCD_PAUSE"));
expiration = _expiration;
action = _spellAction;
sig = abi.encodeWithSignature("execute()");
bytes32 _tag; // Required for assembly access
address _action = _spellAction; // Required for assembly access
assembly { _tag := extcodehash(_action) }
tag = _tag;
}
function schedule() public {
require(now <= expiration, "This contract has expired");
require(eta == 0, "This spell has already been scheduled");
eta = now + PauseAbstract(pause).delay();
pause.plot(action, tag, sig, eta);
}
function cast() public {
require(!done, "spell-already-cast");
done = true;
pause.exec(action, tag, sig, eta);
}
}
////// src/DssSpell.sol
//
// Copyright (C) 2021 Dai Foundation
//
// 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.6.12; */
/* import "dss-exec-lib/DssExec.sol"; */
/* import "dss-exec-lib/DssAction.sol"; */
interface TokenLike {
function approve(address, uint256) external returns (bool);
}
interface DssVestLike {
function yank(uint256) external;
function restrict(uint256) external;
function create(
address _usr,
uint256 _tot,
uint256 _bgn,
uint256 _tau,
uint256 _eta,
address _mgr
) external returns (uint256);
}
contract DssSpellAction is DssAction {
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/3224f50b0b5a9301831213ed858bc1d206de8e40/governance/votes/Executive%20vote%20-%20December%2010%2C%202021.md -q -O - 2>/dev/null)"
string public constant override description =
"2021-12-10 MakerDAO Executive Spell | Hash: 0x9cc240b4c1027d3dc1abb24ecc598703352d8135c8a1670a6591e9a334836e5d";
// --- Math ---
uint256 constant MILLION = 10**6;
// --- Ilks ---
bytes32 constant WSTETH_A = "WSTETH-A";
bytes32 constant MATIC_A = "MATIC-A";
// --- Wallet addresses ---
address constant GRO_WALLET = 0x7800C137A645c07132886539217ce192b9F0528e;
address constant ORA_WALLET = 0x2d09B7b95f3F312ba6dDfB77bA6971786c5b50Cf;
address constant PE_WALLET = 0xe2c16c308b843eD02B09156388Cb240cEd58C01c;
// --- Dates ---
uint256 constant MAY_01_2021 = 1619827200;
uint256 constant JUN_21_2021 = 1624233600;
uint256 constant JUL_01_2021 = 1625097600;
uint256 constant SEP_13_2021 = 1631491200;
uint256 constant SEP_20_2021 = 1632096000;
function officeHours() public override returns (bool) {
return false;
}
function actions() public override {
// ------------- Transfer vesting streams from MCD_VEST_MKR to MCD_VEST_MKR_TREASURY -------------
// https://vote.makerdao.com/polling/QmYdDTsn
address MCD_VEST_MKR = DssExecLib.getChangelogAddress("MCD_VEST_MKR");
address MCD_VEST_MKR_TREASURY = DssExecLib.getChangelogAddress("MCD_VEST_MKR_TREASURY");
TokenLike(DssExecLib.getChangelogAddress("MCD_GOV")).approve(MCD_VEST_MKR_TREASURY, 16_484.43 * 10**18);
// Growth MKR whole team vesting
DssVestLike(MCD_VEST_MKR).yank(1);
DssVestLike(MCD_VEST_MKR_TREASURY).restrict(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: GRO_WALLET,
_tot: 803.18 * 10**18,
_bgn: JUL_01_2021,
_tau: 365 days,
_eta: 365 days,
_mgr: address(0)
})
);
// Oracles MKR whole team vesting
DssVestLike(MCD_VEST_MKR).yank(2);
DssVestLike(MCD_VEST_MKR_TREASURY).restrict(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: ORA_WALLET,
_tot: 1_051.25 * 10**18,
_bgn: JUL_01_2021,
_tau: 365 days,
_eta: 365 days,
_mgr: address(0)
})
);
// PE MKR vestings (per individual)
DssVestLike(MCD_VEST_MKR).yank(3);
(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0xfDB9F5e045D7326C1da87d0e199a05CDE5378EdD,
_tot: 995.00 * 10**18,
_bgn: MAY_01_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(4);
DssVestLike(MCD_VEST_MKR_TREASURY).restrict(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0xBe4De3E151D52668c2C0610C985b4297833239C8,
_tot: 995.00 * 10**18,
_bgn: MAY_01_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(5);
DssVestLike(MCD_VEST_MKR_TREASURY).restrict(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0x58EA3C96a8b81abC01EB78B98deCe2AD1e5fd7fc,
_tot: 995.00 * 10**18,
_bgn: MAY_01_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(6);
DssVestLike(MCD_VEST_MKR_TREASURY).restrict(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0xBAB4Cd1cB31Cd28f842335973712a6015eB0EcD5,
_tot: 995.00 * 10**18,
_bgn: MAY_01_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(7);
(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0xB5c86aff90944CFB3184902482799bD5fA3B18dD,
_tot: 995.00 * 10**18,
_bgn: MAY_01_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(8);
DssVestLike(MCD_VEST_MKR_TREASURY).restrict(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0x780f478856ebE01e46d9A432e8776bAAB5A81b5b,
_tot: 995.00 * 10**18,
_bgn: MAY_01_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(9);
DssVestLike(MCD_VEST_MKR_TREASURY).restrict(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0x34364E234b3DD02FF5c8A2ad9ba86bbD3D3D3284,
_tot: 995.00 * 10**18,
_bgn: MAY_01_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(10);
DssVestLike(MCD_VEST_MKR_TREASURY).restrict(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0x46E5DBad3966453Af57e90Ec2f3548a0e98ec979,
_tot: 995.00 * 10**18,
_bgn: MAY_01_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(11);
DssVestLike(MCD_VEST_MKR_TREASURY).restrict(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0x18CaE82909C31b60Fe0A9656D76406345C9cb9FB,
_tot: 995.00 * 10**18,
_bgn: MAY_01_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(12);
(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0x301dD8eB831ddb93F128C33b9d9DC333210d9B25,
_tot: 995.00 * 10**18,
_bgn: MAY_01_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(13);
(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0xBFC47D0D7452a25b7d3AA4d7379c69A891bD5d43,
_tot: 995.00 * 10**18,
_bgn: MAY_01_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(14);
(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0xcD16aa978A89Aa26b3121Fc8dd32228d7D0fcF4a,
_tot: 995.00 * 10**18,
_bgn: SEP_13_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(15);
DssVestLike(MCD_VEST_MKR_TREASURY).restrict(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0x3189cfe40CF011AAb13aDD8aE7284deD4CD30602,
_tot: 995.00 * 10**18,
_bgn: JUN_21_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
DssVestLike(MCD_VEST_MKR).yank(16);
DssVestLike(MCD_VEST_MKR_TREASURY).restrict(
DssVestLike(MCD_VEST_MKR_TREASURY).create({
_usr: 0x29b37159C09a65af6a7CFb062998B169879442B6,
_tot: 995.00 * 10**18,
_bgn: SEP_20_2021,
_tau: 4 * 365 days,
_eta: 365 days,
_mgr: PE_WALLET
})
);
// -------------------- wstETH-A Parameter Changes ------------------------
// https://vote.makerdao.com/polling/QmYuK441
DssExecLib.setIlkAutoLineParameters({
_ilk: WSTETH_A,
_amount: 200 * MILLION,
_gap: 20 * MILLION,
_ttl: 6 hours
});
DssExecLib.setStartingPriceMultiplicativeFactor(WSTETH_A, 120_00);
DssExecLib.setIlkMaxLiquidationAmount(WSTETH_A, 15 * MILLION);
// ------------------- MATIC-A Parameter Changes --------------------------
// https://vote.makerdao.com/polling/QmdzwZyS
DssExecLib.setIlkAutoLineParameters({
_ilk: MATIC_A,
_amount: 35 * MILLION,
_gap: 10 * MILLION,
_ttl: 8 hours
});
}
}
contract DssSpell is DssExec {
constructor() DssExec(block.timestamp + 30 days, address(new DssSpellAction())) public {}
}
|
Oracles MKR whole team vesting
|
DssVestLike(MCD_VEST_MKR).yank(2);
| 12,243,809 |
[
1,
51,
354,
9558,
490,
47,
54,
7339,
5927,
331,
10100,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
463,
1049,
58,
395,
8804,
12,
49,
10160,
67,
3412,
882,
67,
49,
47,
54,
2934,
93,
2304,
12,
22,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0xAEcd4105078f7556fc22Cd403bdA3573b9Fb0c55/sources/browser/contracts/1_ERC20Contract.sol
|
* @title XXXXXXX @dev Implementation of the XXXXXXX/
|
contract XXXXXXX is ERC20Capped, ERC20Mintable, Ownable {
constructor (
string memory name,
string memory symbol,
uint8 decimals,
uint256 cap,
uint256 initialBalance
)
ERC20(name, symbol)
ERC20Capped(cap)
{
_setupDecimals(decimals);
_mint(_msgSender(), initialBalance);
}
function _mint(address account, uint256 amount) internal override onlyOwner {
super._mint(account, amount);
}
function _finishMinting() internal override onlyOwner {
super._finishMinting();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Capped) {
super._beforeTokenTransfer(from, to, amount);
}
}
| 8,205,686 |
[
1,
24303,
15639,
225,
25379,
434,
326,
11329,
24303,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
11329,
24303,
353,
4232,
39,
3462,
4664,
1845,
16,
4232,
39,
3462,
49,
474,
429,
16,
14223,
6914,
288,
203,
203,
565,
3885,
261,
203,
3639,
533,
3778,
508,
16,
203,
3639,
533,
3778,
3273,
16,
203,
3639,
2254,
28,
15105,
16,
203,
3639,
2254,
5034,
3523,
16,
203,
3639,
2254,
5034,
2172,
13937,
203,
565,
262,
203,
3639,
4232,
39,
3462,
12,
529,
16,
3273,
13,
203,
3639,
4232,
39,
3462,
4664,
1845,
12,
5909,
13,
203,
565,
288,
203,
3639,
389,
8401,
31809,
12,
31734,
1769,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
2172,
13937,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
81,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
3849,
1338,
5541,
288,
203,
3639,
2240,
6315,
81,
474,
12,
4631,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
13749,
49,
474,
310,
1435,
2713,
3849,
1338,
5541,
288,
203,
3639,
2240,
6315,
13749,
49,
474,
310,
5621,
203,
565,
289,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
3844,
13,
2713,
3849,
12,
654,
39,
3462,
16,
4232,
39,
3462,
4664,
1845,
13,
288,
203,
3639,
2240,
6315,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
3844,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/41/0x85BF07EB7Edc772fb3B72895C69366f3C5Fa9Be2/sources/omnidex-core/OmnidexERC20.sol
|
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
|
contract OmnidexERC20 is IOmnidexERC20 {
using SafeMath for uint;
string public constant name = 'Omnidex LPs';
string public constant symbol = 'Charm-LP';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
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 returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'Omnidex: EXPIRED');
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'Omnidex: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
| 16,378,454 |
[
1,
79,
24410,
581,
5034,
2932,
9123,
305,
12,
2867,
3410,
16,
2867,
17571,
264,
16,
11890,
5034,
460,
16,
11890,
5034,
7448,
16,
11890,
5034,
14096,
2225,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
531,
13607,
77,
561,
654,
39,
3462,
353,
1665,
13607,
77,
561,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
565,
533,
1071,
5381,
508,
273,
296,
51,
13607,
77,
561,
511,
18124,
13506,
203,
565,
533,
1071,
5381,
3273,
273,
296,
22980,
17,
14461,
13506,
203,
565,
2254,
28,
1071,
5381,
15105,
273,
6549,
31,
203,
565,
2254,
225,
1071,
2078,
3088,
1283,
31,
203,
565,
2874,
12,
2867,
516,
2254,
13,
1071,
11013,
951,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
1071,
1699,
1359,
31,
203,
203,
565,
1731,
1578,
1071,
27025,
67,
4550,
31,
203,
565,
1731,
1578,
1071,
5381,
10950,
6068,
67,
2399,
15920,
273,
374,
92,
26,
73,
11212,
329,
8906,
2138,
70,
21,
70,
10580,
74,
24,
72,
21,
74,
26,
4630,
7301,
3030,
74,
15168,
6260,
507,
22,
507,
8906,
1611,
5558,
22214,
69,
26035,
71,
1105,
5193,
25,
72,
26,
25452,
71,
29,
31,
203,
565,
2874,
12,
2867,
516,
2254,
13,
1071,
1661,
764,
31,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
460,
1769,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
460,
1769,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
2254,
2687,
548,
31,
203,
3639,
19931,
288,
203,
5411,
2687,
548,
519,
2687,
350,
203,
3639,
289,
203,
3639,
27025,
67,
4550,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
2
] |
./partial_match/42/0x2C7BB8a4D6C7345dE0a187dB6E93e4bd41f593FC/sources/PynthetixBridgeToOptimism.sol
|
Transfer PERI to L2 First, move the PERI into this contract create message payload for L2 relay the message to this contract on L2 via L1 Messenger
|
function _initiateDeposit(uint256 _depositAmount) private {
PynthetixERC20().transferFrom(msg.sender, address(this), _depositAmount);
IPynthetixBridgeToBase bridgeToBase;
bytes memory messageData = abi.encodeWithSelector(bridgeToBase.completeDeposit.selector, msg.sender, _depositAmount);
messenger().sendMessage(
PynthetixBridgeToBase(),
messageData,
uint32(getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits.Deposit))
);
emit Deposit(msg.sender, _depositAmount);
}
| 9,053,441 |
[
1,
5912,
10950,
45,
358,
511,
22,
5783,
16,
3635,
326,
10950,
45,
1368,
333,
6835,
752,
883,
2385,
364,
511,
22,
18874,
326,
883,
358,
333,
6835,
603,
511,
22,
3970,
511,
21,
490,
18912,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
2738,
3840,
758,
1724,
12,
11890,
5034,
389,
323,
1724,
6275,
13,
3238,
288,
203,
3639,
453,
878,
451,
278,
697,
654,
39,
3462,
7675,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
323,
1724,
6275,
1769,
203,
3639,
2971,
878,
451,
278,
697,
13691,
774,
2171,
10105,
774,
2171,
31,
203,
3639,
1731,
3778,
883,
751,
273,
24126,
18,
3015,
1190,
4320,
12,
18337,
774,
2171,
18,
6226,
758,
1724,
18,
9663,
16,
1234,
18,
15330,
16,
389,
323,
1724,
6275,
1769,
203,
203,
3639,
31086,
7675,
4661,
1079,
12,
203,
5411,
453,
878,
451,
278,
697,
13691,
774,
2171,
9334,
203,
5411,
883,
751,
16,
203,
5411,
2254,
1578,
12,
588,
13941,
3748,
1079,
27998,
3039,
12,
13941,
3748,
1079,
27998,
12768,
18,
758,
1724,
3719,
203,
3639,
11272,
203,
3639,
3626,
4019,
538,
305,
12,
3576,
18,
15330,
16,
389,
323,
1724,
6275,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// simple planet invitation management contract
// https://azimuth.network
pragma solidity 0.4.24;
////////////////////////////////////////////////////////////////////////////////
// Imports
////////////////////////////////////////////////////////////////////////////////
// OpenZeppelin's Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// Azimuth's SafeMath8.sol
/**
* @title SafeMath8
* @dev Math operations for uint8 with safety checks that throw on error
*/
library SafeMath8 {
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint8 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
assert(c >= a);
return c;
}
}
// Azimuth's SafeMath16.sol
/**
* @title SafeMath16
* @dev Math operations for uint16 with safety checks that throw on error
*/
library SafeMath16 {
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint16 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
}
// OpenZeppelin's SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// OpenZeppelin's ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// OpenZeppelin's SupportsInterfaceWithLookup.sol
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
// OpenZeppelin's ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// OpenZeppelin's ERC721.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// OpenZeppelin's ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
// OpenZeppelin's AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// Azimuth's Azimuth.sol
// Azimuth: point state data contract
//
// This contract is used for storing all data related to Azimuth points
// and their ownership. Consider this contract the Azimuth ledger.
//
// It also contains permissions data, which ties in to ERC721
// functionality. Operators of an address are allowed to transfer
// ownership of all points owned by their associated address
// (ERC721's approveAll()). A transfer proxy is allowed to transfer
// ownership of a single point (ERC721's approve()).
// Separate from ERC721 are managers, assigned per point. They are
// allowed to perform "low-impact" operations on the owner's points,
// like configuring public keys and making escape requests.
//
// Since data stores are difficult to upgrade, this contract contains
// as little actual business logic as possible. Instead, the data stored
// herein can only be modified by this contract's owner, which can be
// changed and is thus upgradable/replaceable.
//
// This contract will be owned by the Ecliptic contract.
//
contract Azimuth is Ownable
{
//
// Events
//
// OwnerChanged: :point is now owned by :owner
//
event OwnerChanged(uint32 indexed point, address indexed owner);
// Activated: :point is now active
//
event Activated(uint32 indexed point);
// Spawned: :prefix has spawned :child
//
event Spawned(uint32 indexed prefix, uint32 indexed child);
// EscapeRequested: :point has requested a new :sponsor
//
event EscapeRequested(uint32 indexed point, uint32 indexed sponsor);
// EscapeCanceled: :point's :sponsor request was canceled or rejected
//
event EscapeCanceled(uint32 indexed point, uint32 indexed sponsor);
// EscapeAccepted: :point confirmed with a new :sponsor
//
event EscapeAccepted(uint32 indexed point, uint32 indexed sponsor);
// LostSponsor: :point's :sponsor is now refusing it service
//
event LostSponsor(uint32 indexed point, uint32 indexed sponsor);
// ChangedKeys: :point has new network public keys
//
event ChangedKeys( uint32 indexed point,
bytes32 encryptionKey,
bytes32 authenticationKey,
uint32 cryptoSuiteVersion,
uint32 keyRevisionNumber );
// BrokeContinuity: :point has a new continuity number, :number
//
event BrokeContinuity(uint32 indexed point, uint32 number);
// ChangedSpawnProxy: :spawnProxy can now spawn using :point
//
event ChangedSpawnProxy(uint32 indexed point, address indexed spawnProxy);
// ChangedTransferProxy: :transferProxy can now transfer ownership of :point
//
event ChangedTransferProxy( uint32 indexed point,
address indexed transferProxy );
// ChangedManagementProxy: :managementProxy can now manage :point
//
event ChangedManagementProxy( uint32 indexed point,
address indexed managementProxy );
// ChangedVotingProxy: :votingProxy can now vote using :point
//
event ChangedVotingProxy(uint32 indexed point, address indexed votingProxy);
// ChangedDns: dnsDomains have been updated
//
event ChangedDns(string primary, string secondary, string tertiary);
//
// Structures
//
// Size: kinds of points registered on-chain
//
// NOTE: the order matters, because of Solidity enum numbering
//
enum Size
{
Galaxy, // = 0
Star, // = 1
Planet // = 2
}
// Point: state of a point
//
// While the ordering of the struct members is semantically chaotic,
// they are ordered to tightly pack them into Ethereum's 32-byte storage
// slots, which reduces gas costs for some function calls.
// The comment ticks indicate assumed slot boundaries.
//
struct Point
{
// encryptionKey: (curve25519) encryption public key, or 0 for none
//
bytes32 encryptionKey;
//
// authenticationKey: (ed25519) authentication public key, or 0 for none
//
bytes32 authenticationKey;
//
// spawned: for stars and galaxies, all :active children
//
uint32[] spawned;
//
// hasSponsor: true if the sponsor still supports the point
//
bool hasSponsor;
// active: whether point can be linked
//
// false: point belongs to prefix, cannot be configured or linked
// true: point no longer belongs to prefix, can be configured and linked
//
bool active;
// escapeRequested: true if the point has requested to change sponsors
//
bool escapeRequested;
// sponsor: the point that supports this one on the network, or,
// if :hasSponsor is false, the last point that supported it.
// (by default, the point's half-width prefix)
//
uint32 sponsor;
// escapeRequestedTo: if :escapeRequested is true, new sponsor requested
//
uint32 escapeRequestedTo;
// cryptoSuiteVersion: version of the crypto suite used for the pubkeys
//
uint32 cryptoSuiteVersion;
// keyRevisionNumber: incremented every time the public keys change
//
uint32 keyRevisionNumber;
// continuityNumber: incremented to indicate network-side state loss
//
uint32 continuityNumber;
}
// Deed: permissions for a point
//
struct Deed
{
// owner: address that owns this point
//
address owner;
// managementProxy: 0, or another address with the right to perform
// low-impact, managerial operations on this point
//
address managementProxy;
// spawnProxy: 0, or another address with the right to spawn children
// of this point
//
address spawnProxy;
// votingProxy: 0, or another address with the right to vote as this point
//
address votingProxy;
// transferProxy: 0, or another address with the right to transfer
// ownership of this point
//
address transferProxy;
}
//
// General state
//
// points: per point, general network-relevant point state
//
mapping(uint32 => Point) public points;
// rights: per point, on-chain ownership and permissions
//
mapping(uint32 => Deed) public rights;
// operators: per owner, per address, has the right to transfer ownership
// of all the owner's points (ERC721)
//
mapping(address => mapping(address => bool)) public operators;
// dnsDomains: base domains for contacting galaxies
//
// dnsDomains[0] is primary, the others are used as fallbacks
//
string[3] public dnsDomains;
//
// Lookups
//
// sponsoring: per point, the points they are sponsoring
//
mapping(uint32 => uint32[]) public sponsoring;
// sponsoringIndexes: per point, per point, (index + 1) in
// the sponsoring array
//
mapping(uint32 => mapping(uint32 => uint256)) public sponsoringIndexes;
// escapeRequests: per point, the points they have open escape requests from
//
mapping(uint32 => uint32[]) public escapeRequests;
// escapeRequestsIndexes: per point, per point, (index + 1) in
// the escapeRequests array
//
mapping(uint32 => mapping(uint32 => uint256)) public escapeRequestsIndexes;
// pointsOwnedBy: per address, the points they own
//
mapping(address => uint32[]) public pointsOwnedBy;
// pointOwnerIndexes: per owner, per point, (index + 1) in
// the pointsOwnedBy array
//
// We delete owners by moving the last entry in the array to the
// newly emptied slot, which is (n - 1) where n is the value of
// pointOwnerIndexes[owner][point].
//
mapping(address => mapping(uint32 => uint256)) public pointOwnerIndexes;
// managerFor: per address, the points they are the management proxy for
//
mapping(address => uint32[]) public managerFor;
// managerForIndexes: per address, per point, (index + 1) in
// the managerFor array
//
mapping(address => mapping(uint32 => uint256)) public managerForIndexes;
// spawningFor: per address, the points they can spawn with
//
mapping(address => uint32[]) public spawningFor;
// spawningForIndexes: per address, per point, (index + 1) in
// the spawningFor array
//
mapping(address => mapping(uint32 => uint256)) public spawningForIndexes;
// votingFor: per address, the points they can vote with
//
mapping(address => uint32[]) public votingFor;
// votingForIndexes: per address, per point, (index + 1) in
// the votingFor array
//
mapping(address => mapping(uint32 => uint256)) public votingForIndexes;
// transferringFor: per address, the points they can transfer
//
mapping(address => uint32[]) public transferringFor;
// transferringForIndexes: per address, per point, (index + 1) in
// the transferringFor array
//
mapping(address => mapping(uint32 => uint256)) public transferringForIndexes;
//
// Logic
//
// constructor(): configure default dns domains
//
constructor()
public
{
setDnsDomains("example.com", "example.com", "example.com");
}
// setDnsDomains(): set the base domains used for contacting galaxies
//
// Note: since a string is really just a byte[], and Solidity can't
// work with two-dimensional arrays yet, we pass in the three
// domains as individual strings.
//
function setDnsDomains(string _primary, string _secondary, string _tertiary)
onlyOwner
public
{
dnsDomains[0] = _primary;
dnsDomains[1] = _secondary;
dnsDomains[2] = _tertiary;
emit ChangedDns(_primary, _secondary, _tertiary);
}
//
// Point reading
//
// isActive(): return true if _point is active
//
function isActive(uint32 _point)
view
external
returns (bool equals)
{
return points[_point].active;
}
// getKeys(): returns the public keys and their details, as currently
// registered for _point
//
function getKeys(uint32 _point)
view
external
returns (bytes32 crypt, bytes32 auth, uint32 suite, uint32 revision)
{
Point storage point = points[_point];
return (point.encryptionKey,
point.authenticationKey,
point.cryptoSuiteVersion,
point.keyRevisionNumber);
}
// getKeyRevisionNumber(): gets the revision number of _point's current
// public keys
//
function getKeyRevisionNumber(uint32 _point)
view
external
returns (uint32 revision)
{
return points[_point].keyRevisionNumber;
}
// hasBeenLinked(): returns true if the point has ever been assigned keys
//
function hasBeenLinked(uint32 _point)
view
external
returns (bool result)
{
return ( points[_point].keyRevisionNumber > 0 );
}
// isLive(): returns true if _point currently has keys properly configured
//
function isLive(uint32 _point)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.encryptionKey != 0 &&
point.authenticationKey != 0 &&
point.cryptoSuiteVersion != 0 );
}
// getContinuityNumber(): returns _point's current continuity number
//
function getContinuityNumber(uint32 _point)
view
external
returns (uint32 continuityNumber)
{
return points[_point].continuityNumber;
}
// getSpawnCount(): return the number of children spawned by _point
//
function getSpawnCount(uint32 _point)
view
external
returns (uint32 spawnCount)
{
uint256 len = points[_point].spawned.length;
assert(len < 2**32);
return uint32(len);
}
// getSpawned(): return array of points created under _point
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawned(uint32 _point)
view
external
returns (uint32[] spawned)
{
return points[_point].spawned;
}
// hasSponsor(): returns true if _point's sponsor is providing it service
//
function hasSponsor(uint32 _point)
view
external
returns (bool has)
{
return points[_point].hasSponsor;
}
// getSponsor(): returns _point's current (or most recent) sponsor
//
function getSponsor(uint32 _point)
view
external
returns (uint32 sponsor)
{
return points[_point].sponsor;
}
// isSponsor(): returns true if _sponsor is currently providing service
// to _point
//
function isSponsor(uint32 _point, uint32 _sponsor)
view
external
returns (bool result)
{
Point storage point = points[_point];
return ( point.hasSponsor &&
(point.sponsor == _sponsor) );
}
// getSponsoringCount(): returns the number of points _sponsor is
// providing service to
//
function getSponsoringCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return sponsoring[_sponsor].length;
}
// getSponsoring(): returns a list of points _sponsor is providing
// service to
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSponsoring(uint32 _sponsor)
view
external
returns (uint32[] sponsees)
{
return sponsoring[_sponsor];
}
// escaping
// isEscaping(): returns true if _point has an outstanding escape request
//
function isEscaping(uint32 _point)
view
external
returns (bool escaping)
{
return points[_point].escapeRequested;
}
// getEscapeRequest(): returns _point's current escape request
//
// the returned escape request is only valid as long as isEscaping()
// returns true
//
function getEscapeRequest(uint32 _point)
view
external
returns (uint32 escape)
{
return points[_point].escapeRequestedTo;
}
// isRequestingEscapeTo(): returns true if _point has an outstanding
// escape request targetting _sponsor
//
function isRequestingEscapeTo(uint32 _point, uint32 _sponsor)
view
public
returns (bool equals)
{
Point storage point = points[_point];
return (point.escapeRequested && (point.escapeRequestedTo == _sponsor));
}
// getEscapeRequestsCount(): returns the number of points _sponsor
// is providing service to
//
function getEscapeRequestsCount(uint32 _sponsor)
view
external
returns (uint256 count)
{
return escapeRequests[_sponsor].length;
}
// getEscapeRequests(): get the points _sponsor has received escape
// requests from
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getEscapeRequests(uint32 _sponsor)
view
external
returns (uint32[] requests)
{
return escapeRequests[_sponsor];
}
//
// Point writing
//
// activatePoint(): activate a point, register it as spawned by its prefix
//
function activatePoint(uint32 _point)
onlyOwner
external
{
// make a point active, setting its sponsor to its prefix
//
Point storage point = points[_point];
require(!point.active);
point.active = true;
registerSponsor(_point, true, getPrefix(_point));
emit Activated(_point);
}
// setKeys(): set network public keys of _point to _encryptionKey and
// _authenticationKey, with the specified _cryptoSuiteVersion
//
function setKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion)
onlyOwner
external
{
Point storage point = points[_point];
if ( point.encryptionKey == _encryptionKey &&
point.authenticationKey == _authenticationKey &&
point.cryptoSuiteVersion == _cryptoSuiteVersion )
{
return;
}
point.encryptionKey = _encryptionKey;
point.authenticationKey = _authenticationKey;
point.cryptoSuiteVersion = _cryptoSuiteVersion;
point.keyRevisionNumber++;
emit ChangedKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion,
point.keyRevisionNumber);
}
// incrementContinuityNumber(): break continuity for _point
//
function incrementContinuityNumber(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
point.continuityNumber++;
emit BrokeContinuity(_point, point.continuityNumber);
}
// registerSpawn(): add a point to its prefix's list of spawned points
//
function registerSpawned(uint32 _point)
onlyOwner
external
{
// if a point is its own prefix (a galaxy) then don't register it
//
uint32 prefix = getPrefix(_point);
if (prefix == _point)
{
return;
}
// register a new spawned point for the prefix
//
points[prefix].spawned.push(_point);
emit Spawned(prefix, _point);
}
// loseSponsor(): indicates that _point's sponsor is no longer providing
// it service
//
function loseSponsor(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.hasSponsor)
{
return;
}
registerSponsor(_point, false, point.sponsor);
emit LostSponsor(_point, point.sponsor);
}
// setEscapeRequest(): for _point, start an escape request to _sponsor
//
function setEscapeRequest(uint32 _point, uint32 _sponsor)
onlyOwner
external
{
if (isRequestingEscapeTo(_point, _sponsor))
{
return;
}
registerEscapeRequest(_point, true, _sponsor);
emit EscapeRequested(_point, _sponsor);
}
// cancelEscape(): for _point, stop the current escape request, if any
//
function cancelEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
if (!point.escapeRequested)
{
return;
}
uint32 request = point.escapeRequestedTo;
registerEscapeRequest(_point, false, 0);
emit EscapeCanceled(_point, request);
}
// doEscape(): perform the requested escape
//
function doEscape(uint32 _point)
onlyOwner
external
{
Point storage point = points[_point];
require(point.escapeRequested);
registerSponsor(_point, true, point.escapeRequestedTo);
registerEscapeRequest(_point, false, 0);
emit EscapeAccepted(_point, point.sponsor);
}
//
// Point utils
//
// getPrefix(): compute prefix ("parent") of _point
//
function getPrefix(uint32 _point)
pure
public
returns (uint16 prefix)
{
if (_point < 0x10000)
{
return uint16(_point % 0x100);
}
return uint16(_point % 0x10000);
}
// getPointSize(): return the size of _point
//
function getPointSize(uint32 _point)
external
pure
returns (Size _size)
{
if (_point < 0x100) return Size.Galaxy;
if (_point < 0x10000) return Size.Star;
return Size.Planet;
}
// internal use
// registerSponsor(): set the sponsorship state of _point and update the
// reverse lookup for sponsors
//
function registerSponsor(uint32 _point, bool _hasSponsor, uint32 _sponsor)
internal
{
Point storage point = points[_point];
bool had = point.hasSponsor;
uint32 prev = point.sponsor;
// if we didn't have a sponsor, and won't get one,
// or if we get the sponsor we already have,
// nothing will change, so jump out early.
//
if ( (!had && !_hasSponsor) ||
(had && _hasSponsor && prev == _sponsor) )
{
return;
}
// if the point used to have a different sponsor, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (had)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = sponsoringIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :sponsoringIndexes reference
//
uint32[] storage prevSponsoring = sponsoring[prev];
uint256 last = prevSponsoring.length - 1;
uint32 moved = prevSponsoring[last];
prevSponsoring[i] = moved;
sponsoringIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSponsoring[last]);
prevSponsoring.length = last;
sponsoringIndexes[prev][_point] = 0;
}
if (_hasSponsor)
{
uint32[] storage newSponsoring = sponsoring[_sponsor];
newSponsoring.push(_point);
sponsoringIndexes[_sponsor][_point] = newSponsoring.length;
}
point.sponsor = _sponsor;
point.hasSponsor = _hasSponsor;
}
// registerEscapeRequest(): set the escape state of _point and update the
// reverse lookup for sponsors
//
function registerEscapeRequest( uint32 _point,
bool _isEscaping, uint32 _sponsor )
internal
{
Point storage point = points[_point];
bool was = point.escapeRequested;
uint32 prev = point.escapeRequestedTo;
// if we weren't escaping, and won't be,
// or if we were escaping, and the new target is the same,
// nothing will change, so jump out early.
//
if ( (!was && !_isEscaping) ||
(was && _isEscaping && prev == _sponsor) )
{
return;
}
// if the point used to have a different request, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the old
// sponsor's list, then fill that gap with the list tail.
//
if (was)
{
// i: current index in previous sponsor's list of sponsored points
//
uint256 i = escapeRequestsIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :escapeRequestsIndexes reference
//
uint32[] storage prevRequests = escapeRequests[prev];
uint256 last = prevRequests.length - 1;
uint32 moved = prevRequests[last];
prevRequests[i] = moved;
escapeRequestsIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevRequests[last]);
prevRequests.length = last;
escapeRequestsIndexes[prev][_point] = 0;
}
if (_isEscaping)
{
uint32[] storage newRequests = escapeRequests[_sponsor];
newRequests.push(_point);
escapeRequestsIndexes[_sponsor][_point] = newRequests.length;
}
point.escapeRequestedTo = _sponsor;
point.escapeRequested = _isEscaping;
}
//
// Deed reading
//
// owner
// getOwner(): return owner of _point
//
function getOwner(uint32 _point)
view
external
returns (address owner)
{
return rights[_point].owner;
}
// isOwner(): true if _point is owned by _address
//
function isOwner(uint32 _point, address _address)
view
external
returns (bool result)
{
return (rights[_point].owner == _address);
}
// getOwnedPointCount(): return length of array of points that _whose owns
//
function getOwnedPointCount(address _whose)
view
external
returns (uint256 count)
{
return pointsOwnedBy[_whose].length;
}
// getOwnedPoints(): return array of points that _whose owns
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getOwnedPoints(address _whose)
view
external
returns (uint32[] ownedPoints)
{
return pointsOwnedBy[_whose];
}
// getOwnedPointAtIndex(): get point at _index from array of points that
// _whose owns
//
function getOwnedPointAtIndex(address _whose, uint256 _index)
view
external
returns (uint32 point)
{
uint32[] storage owned = pointsOwnedBy[_whose];
require(_index < owned.length);
return owned[_index];
}
// management proxy
// getManagementProxy(): returns _point's current management proxy
//
function getManagementProxy(uint32 _point)
view
external
returns (address manager)
{
return rights[_point].managementProxy;
}
// isManagementProxy(): returns true if _proxy is _point's management proxy
//
function isManagementProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].managementProxy == _proxy);
}
// canManage(): true if _who is the owner or manager of _point
//
function canManage(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.managementProxy) ) );
}
// getManagerForCount(): returns the amount of points _proxy can manage
//
function getManagerForCount(address _proxy)
view
external
returns (uint256 count)
{
return managerFor[_proxy].length;
}
// getManagerFor(): returns the points _proxy can manage
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getManagerFor(address _proxy)
view
external
returns (uint32[] mfor)
{
return managerFor[_proxy];
}
// spawn proxy
// getSpawnProxy(): returns _point's current spawn proxy
//
function getSpawnProxy(uint32 _point)
view
external
returns (address spawnProxy)
{
return rights[_point].spawnProxy;
}
// isSpawnProxy(): returns true if _proxy is _point's spawn proxy
//
function isSpawnProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].spawnProxy == _proxy);
}
// canSpawnAs(): true if _who is the owner or spawn proxy of _point
//
function canSpawnAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.spawnProxy) ) );
}
// getSpawningForCount(): returns the amount of points _proxy
// can spawn with
//
function getSpawningForCount(address _proxy)
view
external
returns (uint256 count)
{
return spawningFor[_proxy].length;
}
// getSpawningFor(): get the points _proxy can spawn with
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getSpawningFor(address _proxy)
view
external
returns (uint32[] sfor)
{
return spawningFor[_proxy];
}
// voting proxy
// getVotingProxy(): returns _point's current voting proxy
//
function getVotingProxy(uint32 _point)
view
external
returns (address voter)
{
return rights[_point].votingProxy;
}
// isVotingProxy(): returns true if _proxy is _point's voting proxy
//
function isVotingProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].votingProxy == _proxy);
}
// canVoteAs(): true if _who is the owner of _point,
// or the voting proxy of _point's owner
//
function canVoteAs(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.votingProxy) ) );
}
// getVotingForCount(): returns the amount of points _proxy can vote as
//
function getVotingForCount(address _proxy)
view
external
returns (uint256 count)
{
return votingFor[_proxy].length;
}
// getVotingFor(): returns the points _proxy can vote as
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getVotingFor(address _proxy)
view
external
returns (uint32[] vfor)
{
return votingFor[_proxy];
}
// transfer proxy
// getTransferProxy(): returns _point's current transfer proxy
//
function getTransferProxy(uint32 _point)
view
external
returns (address transferProxy)
{
return rights[_point].transferProxy;
}
// isTransferProxy(): returns true if _proxy is _point's transfer proxy
//
function isTransferProxy(uint32 _point, address _proxy)
view
external
returns (bool result)
{
return (rights[_point].transferProxy == _proxy);
}
// canTransfer(): true if _who is the owner or transfer proxy of _point,
// or is an operator for _point's current owner
//
function canTransfer(uint32 _point, address _who)
view
external
returns (bool result)
{
Deed storage deed = rights[_point];
return ( (0x0 != _who) &&
( (_who == deed.owner) ||
(_who == deed.transferProxy) ||
operators[deed.owner][_who] ) );
}
// getTransferringForCount(): returns the amount of points _proxy
// can transfer
//
function getTransferringForCount(address _proxy)
view
external
returns (uint256 count)
{
return transferringFor[_proxy].length;
}
// getTransferringFor(): get the points _proxy can transfer
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getTransferringFor(address _proxy)
view
external
returns (uint32[] tfor)
{
return transferringFor[_proxy];
}
// isOperator(): returns true if _operator is allowed to transfer
// ownership of _owner's points
//
function isOperator(address _owner, address _operator)
view
external
returns (bool result)
{
return operators[_owner][_operator];
}
//
// Deed writing
//
// setOwner(): set owner of _point to _owner
//
// Note: setOwner() only implements the minimal data storage
// logic for a transfer; the full transfer is implemented in
// Ecliptic.
//
// Note: _owner must not be the zero address.
//
function setOwner(uint32 _point, address _owner)
onlyOwner
external
{
// prevent burning of points by making zero the owner
//
require(0x0 != _owner);
// prev: previous owner, if any
//
address prev = rights[_point].owner;
if (prev == _owner)
{
return;
}
// if the point used to have a different owner, do some gymnastics to
// keep the list of owned points gapless. delete this point from the
// list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous owner's list of owned points
//
uint256 i = pointOwnerIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :pointOwnerIndexes reference
//
uint32[] storage owner = pointsOwnedBy[prev];
uint256 last = owner.length - 1;
uint32 moved = owner[last];
owner[i] = moved;
pointOwnerIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(owner[last]);
owner.length = last;
pointOwnerIndexes[prev][_point] = 0;
}
// update the owner list and the owner's index list
//
rights[_point].owner = _owner;
pointsOwnedBy[_owner].push(_point);
pointOwnerIndexes[_owner][_point] = pointsOwnedBy[_owner].length;
emit OwnerChanged(_point, _owner);
}
// setManagementProxy(): makes _proxy _point's management proxy
//
function setManagementProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.managementProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different manager, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old manager's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous manager's list of managed points
//
uint256 i = managerForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :managerForIndexes reference
//
uint32[] storage prevMfor = managerFor[prev];
uint256 last = prevMfor.length - 1;
uint32 moved = prevMfor[last];
prevMfor[i] = moved;
managerForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevMfor[last]);
prevMfor.length = last;
managerForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage mfor = managerFor[_proxy];
mfor.push(_point);
managerForIndexes[_proxy][_point] = mfor.length;
}
deed.managementProxy = _proxy;
emit ChangedManagementProxy(_point, _proxy);
}
// setSpawnProxy(): makes _proxy _point's spawn proxy
//
function setSpawnProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.spawnProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different spawn proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of spawning points
//
uint256 i = spawningForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :spawningForIndexes reference
//
uint32[] storage prevSfor = spawningFor[prev];
uint256 last = prevSfor.length - 1;
uint32 moved = prevSfor[last];
prevSfor[i] = moved;
spawningForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevSfor[last]);
prevSfor.length = last;
spawningForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage sfor = spawningFor[_proxy];
sfor.push(_point);
spawningForIndexes[_proxy][_point] = sfor.length;
}
deed.spawnProxy = _proxy;
emit ChangedSpawnProxy(_point, _proxy);
}
// setVotingProxy(): makes _proxy _point's voting proxy
//
function setVotingProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.votingProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different voter, do some gymnastics
// to keep the reverse lookup gapless. delete the point from the
// old voter's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous voter's list of points it was
// voting for
//
uint256 i = votingForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :votingForIndexes reference
//
uint32[] storage prevVfor = votingFor[prev];
uint256 last = prevVfor.length - 1;
uint32 moved = prevVfor[last];
prevVfor[i] = moved;
votingForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevVfor[last]);
prevVfor.length = last;
votingForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage vfor = votingFor[_proxy];
vfor.push(_point);
votingForIndexes[_proxy][_point] = vfor.length;
}
deed.votingProxy = _proxy;
emit ChangedVotingProxy(_point, _proxy);
}
// setManagementProxy(): makes _proxy _point's transfer proxy
//
function setTransferProxy(uint32 _point, address _proxy)
onlyOwner
external
{
Deed storage deed = rights[_point];
address prev = deed.transferProxy;
if (prev == _proxy)
{
return;
}
// if the point used to have a different transfer proxy, do some
// gymnastics to keep the reverse lookup gapless. delete the point
// from the old proxy's list, then fill that gap with the list tail.
//
if (0x0 != prev)
{
// i: current index in previous proxy's list of transferable points
//
uint256 i = transferringForIndexes[prev][_point];
// we store index + 1, because 0 is the solidity default value
//
assert(i > 0);
i--;
// copy the last item in the list into the now-unused slot,
// making sure to update its :transferringForIndexes reference
//
uint32[] storage prevTfor = transferringFor[prev];
uint256 last = prevTfor.length - 1;
uint32 moved = prevTfor[last];
prevTfor[i] = moved;
transferringForIndexes[prev][moved] = i + 1;
// delete the last item
//
delete(prevTfor[last]);
prevTfor.length = last;
transferringForIndexes[prev][_point] = 0;
}
if (0x0 != _proxy)
{
uint32[] storage tfor = transferringFor[_proxy];
tfor.push(_point);
transferringForIndexes[_proxy][_point] = tfor.length;
}
deed.transferProxy = _proxy;
emit ChangedTransferProxy(_point, _proxy);
}
// setOperator(): dis/allow _operator to transfer ownership of all points
// owned by _owner
//
// operators are part of the ERC721 standard
//
function setOperator(address _owner, address _operator, bool _approved)
onlyOwner
external
{
operators[_owner][_operator] = _approved;
}
}
// Azimuth's ReadsAzimuth.sol
// ReadsAzimuth: referring to and testing against the Azimuth
// data contract
//
// To avoid needless repetition, this contract provides common
// checks and operations using the Azimuth contract.
//
contract ReadsAzimuth
{
// azimuth: points data storage contract.
//
Azimuth public azimuth;
// constructor(): set the Azimuth data contract's address
//
constructor(Azimuth _azimuth)
public
{
azimuth = _azimuth;
}
// activePointOwner(): require that :msg.sender is the owner of _point,
// and that _point is active
//
modifier activePointOwner(uint32 _point)
{
require( azimuth.isOwner(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
// activePointManager(): require that :msg.sender can manage _point,
// and that _point is active
//
modifier activePointManager(uint32 _point)
{
require( azimuth.canManage(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
}
// Azimuth's Polls.sol
// Polls: proposals & votes data contract
//
// This contract is used for storing all data related to the proposals
// of the senate (galaxy owners) and their votes on those proposals.
// It keeps track of votes and uses them to calculate whether a majority
// is in favor of a proposal.
//
// Every galaxy can only vote on a proposal exactly once. Votes cannot
// be changed. If a proposal fails to achieve majority within its
// duration, it can be restarted after its cooldown period has passed.
//
// The requirements for a proposal to achieve majority are as follows:
// - At least 1/4 of the currently active voters (rounded down) must have
// voted in favor of the proposal,
// - More than half of the votes cast must be in favor of the proposal,
// and this can no longer change, either because
// - the poll duration has passed, or
// - not enough voters remain to take away the in-favor majority.
// As soon as these conditions are met, no further interaction with
// the proposal is possible. Achieving majority is permanent.
//
// Since data stores are difficult to upgrade, all of the logic unrelated
// to the voting itself (that is, determining who is eligible to vote)
// is expected to be implemented by this contract's owner.
//
// This contract will be owned by the Ecliptic contract.
//
contract Polls is Ownable
{
using SafeMath for uint256;
using SafeMath16 for uint16;
using SafeMath8 for uint8;
// UpgradePollStarted: a poll on :proposal has opened
//
event UpgradePollStarted(address proposal);
// DocumentPollStarted: a poll on :proposal has opened
//
event DocumentPollStarted(bytes32 proposal);
// UpgradeMajority: :proposal has achieved majority
//
event UpgradeMajority(address proposal);
// DocumentMajority: :proposal has achieved majority
//
event DocumentMajority(bytes32 proposal);
// Poll: full poll state
//
struct Poll
{
// start: the timestamp at which the poll was started
//
uint256 start;
// voted: per galaxy, whether they have voted on this poll
//
bool[256] voted;
// yesVotes: amount of votes in favor of the proposal
//
uint16 yesVotes;
// noVotes: amount of votes against the proposal
//
uint16 noVotes;
// duration: amount of time during which the poll can be voted on
//
uint256 duration;
// cooldown: amount of time before the (non-majority) poll can be reopened
//
uint256 cooldown;
}
// pollDuration: duration set for new polls. see also Poll.duration above
//
uint256 public pollDuration;
// pollCooldown: cooldown set for new polls. see also Poll.cooldown above
//
uint256 public pollCooldown;
// totalVoters: amount of active galaxies
//
uint16 public totalVoters;
// upgradeProposals: list of all upgrades ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
address[] public upgradeProposals;
// upgradePolls: per address, poll held to determine if that address
// will become the new ecliptic
//
mapping(address => Poll) public upgradePolls;
// upgradeHasAchievedMajority: per address, whether that address
// has ever achieved majority
//
// If we did not store this, we would have to look at old poll data
// to see whether or not a proposal has ever achieved majority.
// Since the outcome of a poll is calculated based on :totalVoters,
// which may not be consistent across time, we need to store outcomes
// explicitly instead of re-calculating them. This allows us to always
// tell with certainty whether or not a majority was achieved,
// regardless of the current :totalVoters.
//
mapping(address => bool) public upgradeHasAchievedMajority;
// documentProposals: list of all documents ever proposed
//
// this allows clients to discover the existence of polls.
// from there, they can do liveness checks on the polls themselves.
//
bytes32[] public documentProposals;
// documentPolls: per hash, poll held to determine if the corresponding
// document is accepted by the galactic senate
//
mapping(bytes32 => Poll) public documentPolls;
// documentHasAchievedMajority: per hash, whether that hash has ever
// achieved majority
//
// the note for upgradeHasAchievedMajority above applies here as well
//
mapping(bytes32 => bool) public documentHasAchievedMajority;
// documentMajorities: all hashes that have achieved majority
//
bytes32[] public documentMajorities;
// constructor(): initial contract configuration
//
constructor(uint256 _pollDuration, uint256 _pollCooldown)
public
{
reconfigure(_pollDuration, _pollCooldown);
}
// reconfigure(): change poll duration and cooldown
//
function reconfigure(uint256 _pollDuration, uint256 _pollCooldown)
public
onlyOwner
{
require( (5 days <= _pollDuration) && (_pollDuration <= 90 days) &&
(5 days <= _pollCooldown) && (_pollCooldown <= 90 days) );
pollDuration = _pollDuration;
pollCooldown = _pollCooldown;
}
// incrementTotalVoters(): increase the amount of registered voters
//
function incrementTotalVoters()
external
onlyOwner
{
require(totalVoters < 256);
totalVoters = totalVoters.add(1);
}
// getAllUpgradeProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getUpgradeProposals()
external
view
returns (address[] proposals)
{
return upgradeProposals;
}
// getUpgradeProposalCount(): get the number of unique proposed upgrades
//
function getUpgradeProposalCount()
external
view
returns (uint256 count)
{
return upgradeProposals.length;
}
// getAllDocumentProposals(): return array of all upgrade proposals ever made
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentProposals()
external
view
returns (bytes32[] proposals)
{
return documentProposals;
}
// getDocumentProposalCount(): get the number of unique proposed upgrades
//
function getDocumentProposalCount()
external
view
returns (uint256 count)
{
return documentProposals.length;
}
// getDocumentMajorities(): return array of all document majorities
//
// Note: only useful for clients, as Solidity does not currently
// support returning dynamic arrays.
//
function getDocumentMajorities()
external
view
returns (bytes32[] majorities)
{
return documentMajorities;
}
// hasVotedOnUpgradePoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnUpgradePoll(uint8 _galaxy, address _proposal)
external
view
returns (bool result)
{
return upgradePolls[_proposal].voted[_galaxy];
}
// hasVotedOnDocumentPoll(): returns true if _galaxy has voted
// on the _proposal
//
function hasVotedOnDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
view
returns (bool result)
{
return documentPolls[_proposal].voted[_galaxy];
}
// startUpgradePoll(): open a poll on making _proposal the new ecliptic
//
function startUpgradePoll(address _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
Poll storage poll = upgradePolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
upgradeProposals.push(_proposal);
}
startPoll(poll);
emit UpgradePollStarted(_proposal);
}
// startDocumentPoll(): open a poll on accepting the document
// whose hash is _proposal
//
function startDocumentPoll(bytes32 _proposal)
external
onlyOwner
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
Poll storage poll = documentPolls[_proposal];
// if the proposal is being made for the first time, register it.
//
if (0 == poll.start)
{
documentProposals.push(_proposal);
}
startPoll(poll);
emit DocumentPollStarted(_proposal);
}
// startPoll(): open a new poll, or re-open an old one
//
function startPoll(Poll storage _poll)
internal
{
// check that the poll has cooled down enough to be started again
//
// for completely new polls, the values used will be zero
//
require( block.timestamp > ( _poll.start.add(
_poll.duration.add(
_poll.cooldown )) ) );
// set started poll state
//
_poll.start = block.timestamp;
delete _poll.voted;
_poll.yesVotes = 0;
_poll.noVotes = 0;
_poll.duration = pollDuration;
_poll.cooldown = pollCooldown;
}
// castUpgradeVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castUpgradeVote(uint8 _as, address _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = upgradePolls[_proposal];
processVote(poll, _as, _vote);
return updateUpgradePoll(_proposal);
}
// castDocumentVote(): as galaxy _as, cast a vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _as, bytes32 _proposal, bool _vote)
external
onlyOwner
returns (bool majority)
{
Poll storage poll = documentPolls[_proposal];
processVote(poll, _as, _vote);
return updateDocumentPoll(_proposal);
}
// processVote(): record a vote from _as on the _poll
//
function processVote(Poll storage _poll, uint8 _as, bool _vote)
internal
{
// assist symbolic execution tools
//
assert(block.timestamp >= _poll.start);
require( // may only vote once
//
!_poll.voted[_as] &&
//
// may only vote when the poll is open
//
(block.timestamp < _poll.start.add(_poll.duration)) );
// update poll state to account for the new vote
//
_poll.voted[_as] = true;
if (_vote)
{
_poll.yesVotes = _poll.yesVotes.add(1);
}
else
{
_poll.noVotes = _poll.noVotes.add(1);
}
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, updating state, sending an event,
// and returning true if it has
//
function updateUpgradePoll(address _proposal)
public
onlyOwner
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!upgradeHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = upgradePolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update the state and send an event
//
if (majority)
{
upgradeHasAchievedMajority[_proposal] = true;
emit UpgradeMajority(_proposal);
}
return majority;
}
// updateDocumentPoll(): check whether the _proposal has achieved majority,
// updating the state and sending an event if it has
//
// this can be called by anyone, because the ecliptic does not
// need to be aware of the result
//
function updateDocumentPoll(bytes32 _proposal)
public
returns (bool majority)
{
// _proposal must not have achieved majority before
//
require(!documentHasAchievedMajority[_proposal]);
// check for majority in the poll
//
Poll storage poll = documentPolls[_proposal];
majority = checkPollMajority(poll);
// if majority was achieved, update state and send an event
//
if (majority)
{
documentHasAchievedMajority[_proposal] = true;
documentMajorities.push(_proposal);
emit DocumentMajority(_proposal);
}
return majority;
}
// checkPollMajority(): returns true if the majority is in favor of
// the subject of the poll
//
function checkPollMajority(Poll _poll)
internal
view
returns (bool majority)
{
return ( // poll must have at least the minimum required yes-votes
//
(_poll.yesVotes >= (totalVoters / 4)) &&
//
// and have a majority...
//
(_poll.yesVotes > _poll.noVotes) &&
//
// ...that is indisputable
//
( // either because the poll has ended
//
(block.timestamp > _poll.start.add(_poll.duration)) ||
//
// or there are more yes votes than there can be no votes
//
( _poll.yesVotes > totalVoters.sub(_poll.yesVotes) ) ) );
}
}
// Azimuth's Claims.sol
// Claims: simple identity management
//
// This contract allows points to document claims about their owner.
// Most commonly, these are about identity, with a claim's protocol
// defining the context or platform of the claim, and its dossier
// containing proof of its validity.
// Points are limited to a maximum of 16 claims.
//
// For existing claims, the dossier can be updated, or the claim can
// be removed entirely. It is recommended to remove any claims associated
// with a point when it is about to be transferred to a new owner.
// For convenience, the owner of the Azimuth contract (the Ecliptic)
// is allowed to clear claims for any point, allowing it to do this for
// you on-transfer.
//
contract Claims is ReadsAzimuth
{
// ClaimAdded: a claim was added by :by
//
event ClaimAdded( uint32 indexed by,
string _protocol,
string _claim,
bytes _dossier );
// ClaimRemoved: a claim was removed by :by
//
event ClaimRemoved(uint32 indexed by, string _protocol, string _claim);
// maxClaims: the amount of claims that can be registered per point
//
uint8 constant maxClaims = 16;
// Claim: claim details
//
struct Claim
{
// protocol: context of the claim
//
string protocol;
// claim: the claim itself
//
string claim;
// dossier: data relating to the claim, as proof
//
bytes dossier;
}
// per point, list of claims
//
mapping(uint32 => Claim[maxClaims]) public claims;
// constructor(): register the azimuth contract.
//
constructor(Azimuth _azimuth)
ReadsAzimuth(_azimuth)
public
{
//
}
// addClaim(): register a claim as _point
//
function addClaim(uint32 _point,
string _protocol,
string _claim,
bytes _dossier)
external
activePointManager(_point)
{
// cur: index + 1 of the claim if it already exists, 0 otherwise
//
uint8 cur = findClaim(_point, _protocol, _claim);
// if the claim doesn't yet exist, store it in state
//
if (cur == 0)
{
// if there are no empty slots left, this throws
//
uint8 empty = findEmptySlot(_point);
claims[_point][empty] = Claim(_protocol, _claim, _dossier);
}
//
// if the claim has been made before, update the version in state
//
else
{
claims[_point][cur-1] = Claim(_protocol, _claim, _dossier);
}
emit ClaimAdded(_point, _protocol, _claim, _dossier);
}
// removeClaim(): unregister a claim as _point
//
function removeClaim(uint32 _point, string _protocol, string _claim)
external
activePointManager(_point)
{
// i: current index + 1 in _point's list of claims
//
uint256 i = findClaim(_point, _protocol, _claim);
// we store index + 1, because 0 is the eth default value
// can only delete an existing claim
//
require(i > 0);
i--;
// clear out the claim
//
delete claims[_point][i];
emit ClaimRemoved(_point, _protocol, _claim);
}
// clearClaims(): unregister all of _point's claims
//
// can also be called by the ecliptic during point transfer
//
function clearClaims(uint32 _point)
external
{
// both point owner and ecliptic may do this
//
// We do not necessarily need to check for _point's active flag here,
// since inactive points cannot have claims set. Doing the check
// anyway would make this function slightly harder to think about due
// to its relation to Ecliptic's transferPoint().
//
require( azimuth.canManage(_point, msg.sender) ||
( msg.sender == azimuth.owner() ) );
Claim[maxClaims] storage currClaims = claims[_point];
// clear out all claims
//
for (uint8 i = 0; i < maxClaims; i++)
{
delete currClaims[i];
}
}
// findClaim(): find the index of the specified claim
//
// returns 0 if not found, index + 1 otherwise
//
function findClaim(uint32 _whose, string _protocol, string _claim)
public
view
returns (uint8 index)
{
// we use hashes of the string because solidity can't do string
// comparison yet
//
bytes32 protocolHash = keccak256(bytes(_protocol));
bytes32 claimHash = keccak256(bytes(_claim));
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( ( protocolHash == keccak256(bytes(thisClaim.protocol)) ) &&
( claimHash == keccak256(bytes(thisClaim.claim)) ) )
{
return i+1;
}
}
return 0;
}
// findEmptySlot(): find the index of the first empty claim slot
//
// returns the index of the slot, throws if there are no empty slots
//
function findEmptySlot(uint32 _whose)
internal
view
returns (uint8 index)
{
Claim[maxClaims] storage theirClaims = claims[_whose];
for (uint8 i = 0; i < maxClaims; i++)
{
Claim storage thisClaim = theirClaims[i];
if ( (0 == bytes(thisClaim.protocol).length) &&
(0 == bytes(thisClaim.claim).length) )
{
return i;
}
}
revert();
}
}
// Azimuth's EclipticBase.sol
// EclipticBase: upgradable ecliptic
//
// This contract implements the upgrade logic for the Ecliptic.
// Newer versions of the Ecliptic are expected to provide at least
// the onUpgrade() function. If they don't, upgrading to them will
// fail.
//
// Note that even though this contract doesn't specify any required
// interface members aside from upgrade() and onUpgrade(), contracts
// and clients may still rely on the presence of certain functions
// provided by the Ecliptic proper. Keep this in mind when writing
// new versions of it.
//
contract EclipticBase is Ownable, ReadsAzimuth
{
// Upgraded: _to is the new canonical Ecliptic
//
event Upgraded(address to);
// polls: senate voting contract
//
Polls public polls;
// previousEcliptic: address of the previous ecliptic this
// instance expects to upgrade from, stored and
// checked for to prevent unexpected upgrade paths
//
address public previousEcliptic;
constructor( address _previous,
Azimuth _azimuth,
Polls _polls )
ReadsAzimuth(_azimuth)
internal
{
previousEcliptic = _previous;
polls = _polls;
}
// onUpgrade(): called by previous ecliptic when upgrading
//
// in future ecliptics, this might perform more logic than
// just simple checks and verifications.
// when overriding this, make sure to call this original as well.
//
function onUpgrade()
external
{
// make sure this is the expected upgrade path,
// and that we have gotten the ownership we require
//
require( msg.sender == previousEcliptic &&
this == azimuth.owner() &&
this == polls.owner() );
}
// upgrade(): transfer ownership of the ecliptic data to the new
// ecliptic contract, notify it, then self-destruct.
//
// Note: any eth that have somehow ended up in this contract
// are also sent to the new ecliptic.
//
function upgrade(EclipticBase _new)
internal
{
// transfer ownership of the data contracts
//
azimuth.transferOwnership(_new);
polls.transferOwnership(_new);
// trigger upgrade logic on the target contract
//
_new.onUpgrade();
// emit event and destroy this contract
//
emit Upgraded(_new);
selfdestruct(_new);
}
}
// Azimuth's Ecliptic
// Ecliptic: logic for interacting with the Azimuth ledger
//
// This contract is the point of entry for all operations on the Azimuth
// ledger as stored in the Azimuth data contract. The functions herein
// are responsible for performing all necessary business logic.
// Examples of such logic include verifying permissions of the caller
// and ensuring a requested change is actually valid.
// Point owners can always operate on their own points. Ethereum addresses
// can also perform specific operations if they've been given the
// appropriate permissions. (For example, managers for general management,
// spawn proxies for spawning child points, etc.)
//
// This contract uses external contracts (Azimuth, Polls) for data storage
// so that it itself can easily be replaced in case its logic needs to
// be changed. In other words, it can be upgraded. It does this by passing
// ownership of the data contracts to a new Ecliptic contract.
//
// Because of this, it is advised for clients to not store this contract's
// address directly, but rather ask the Azimuth contract for its owner
// attribute to ensure transactions get sent to the latest Ecliptic.
// Alternatively, the ENS name ecliptic.eth will resolve to the latest
// Ecliptic as well.
//
// Upgrading happens based on polls held by the senate (galaxy owners).
// Through this contract, the senate can submit proposals, opening polls
// for the senate to cast votes on. These proposals can be either hashes
// of documents or addresses of new Ecliptics.
// If an ecliptic proposal gains majority, this contract will transfer
// ownership of the data storage contracts to that address, so that it may
// operate on the data they contain. This contract will selfdestruct at
// the end of the upgrade process.
//
// This contract implements the ERC721 interface for non-fungible tokens,
// allowing points to be managed using generic clients that support the
// standard. It also implements ERC165 to allow this to be discovered.
//
contract Ecliptic is EclipticBase, SupportsInterfaceWithLookup, ERC721Metadata
{
using SafeMath for uint256;
using AddressUtils for address;
// Transfer: This emits when ownership of any NFT changes by any mechanism.
// This event emits when NFTs are created (`from` == 0) and
// destroyed (`to` == 0). At the time of any transfer, the
// approved address for that NFT (if any) is reset to none.
//
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
// Approval: This emits when the approved address for an NFT is changed or
// reaffirmed. The zero address indicates there is no approved
// address. When a Transfer event emits, this also indicates that
// the approved address for that NFT (if any) is reset to none.
//
event Approval(address indexed _owner, address indexed _approved,
uint256 _tokenId);
// ApprovalForAll: This emits when an operator is enabled or disabled for an
// owner. The operator can manage all NFTs of the owner.
//
event ApprovalForAll(address indexed _owner, address indexed _operator,
bool _approved);
// erc721Received: equal to:
// bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))
// which can be also obtained as:
// ERC721Receiver(0).onERC721Received.selector`
bytes4 constant erc721Received = 0x150b7a02;
// claims: contract reference, for clearing claims on-transfer
//
Claims public claims;
// constructor(): set data contract addresses and signal interface support
//
// Note: during first deploy, ownership of these data contracts must
// be manually transferred to this contract.
//
constructor(address _previous,
Azimuth _azimuth,
Polls _polls,
Claims _claims)
EclipticBase(_previous, _azimuth, _polls)
public
{
claims = _claims;
// register supported interfaces for ERC165
//
_registerInterface(0x80ac58cd); // ERC721
_registerInterface(0x5b5e139f); // ERC721Metadata
_registerInterface(0x7f5828d0); // ERC173 (ownership)
}
//
// ERC721 interface
//
// balanceOf(): get the amount of points owned by _owner
//
function balanceOf(address _owner)
public
view
returns (uint256 balance)
{
require(0x0 != _owner);
return azimuth.getOwnedPointCount(_owner);
}
// ownerOf(): get the current owner of point _tokenId
//
function ownerOf(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address owner)
{
uint32 id = uint32(_tokenId);
// this will throw if the owner is the zero address,
// active points always have a valid owner.
//
require(azimuth.isActive(id));
return azimuth.getOwner(id);
}
// exists(): returns true if point _tokenId is active
//
function exists(uint256 _tokenId)
public
view
returns (bool doesExist)
{
return ( (_tokenId < 0x100000000) &&
azimuth.isActive(uint32(_tokenId)) );
}
// safeTransferFrom(): transfer point _tokenId from _from to _to
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public
{
// transfer with empty data
//
safeTransferFrom(_from, _to, _tokenId, "");
}
// safeTransferFrom(): transfer point _tokenId from _from to _to,
// and call recipient if it's a contract
//
function safeTransferFrom(address _from, address _to, uint256 _tokenId,
bytes _data)
public
{
// perform raw transfer
//
transferFrom(_from, _to, _tokenId);
// do the callback last to avoid re-entrancy
//
if (_to.isContract())
{
bytes4 retval = ERC721Receiver(_to)
.onERC721Received(msg.sender, _from, _tokenId, _data);
//
// standard return idiom to confirm contract semantics
//
require(retval == erc721Received);
}
}
// transferFrom(): transfer point _tokenId from _from to _to,
// WITHOUT notifying recipient contract
//
function transferFrom(address _from, address _to, uint256 _tokenId)
public
validPointId(_tokenId)
{
uint32 id = uint32(_tokenId);
require(azimuth.isOwner(id, _from));
// the ERC721 operator/approved address (if any) is
// accounted for in transferPoint()
//
transferPoint(id, _to, true);
}
// approve(): allow _approved to transfer ownership of point
// _tokenId
//
function approve(address _approved, uint256 _tokenId)
public
validPointId(_tokenId)
{
setTransferProxy(uint32(_tokenId), _approved);
}
// setApprovalForAll(): allow or disallow _operator to
// transfer ownership of ALL points
// owned by :msg.sender
//
function setApprovalForAll(address _operator, bool _approved)
public
{
require(0x0 != _operator);
azimuth.setOperator(msg.sender, _operator, _approved);
emit ApprovalForAll(msg.sender, _operator, _approved);
}
// getApproved(): get the approved address for point _tokenId
//
function getApproved(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (address approved)
{
//NOTE redundant, transfer proxy cannot be set for
// inactive points
//
require(azimuth.isActive(uint32(_tokenId)));
return azimuth.getTransferProxy(uint32(_tokenId));
}
// isApprovedForAll(): returns true if _operator is an
// operator for _owner
//
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool result)
{
return azimuth.isOperator(_owner, _operator);
}
//
// ERC721Metadata interface
//
// name(): returns the name of a collection of points
//
function name()
external
view
returns (string)
{
return "Azimuth Points";
}
// symbol(): returns an abbreviates name for points
//
function symbol()
external
view
returns (string)
{
return "AZP";
}
// tokenURI(): returns a URL to an ERC-721 standard JSON file
//
function tokenURI(uint256 _tokenId)
public
view
validPointId(_tokenId)
returns (string _tokenURI)
{
_tokenURI = "https://azimuth.network/erc721/0000000000.json";
bytes memory _tokenURIBytes = bytes(_tokenURI);
_tokenURIBytes[31] = byte(48+(_tokenId / 1000000000) % 10);
_tokenURIBytes[32] = byte(48+(_tokenId / 100000000) % 10);
_tokenURIBytes[33] = byte(48+(_tokenId / 10000000) % 10);
_tokenURIBytes[34] = byte(48+(_tokenId / 1000000) % 10);
_tokenURIBytes[35] = byte(48+(_tokenId / 100000) % 10);
_tokenURIBytes[36] = byte(48+(_tokenId / 10000) % 10);
_tokenURIBytes[37] = byte(48+(_tokenId / 1000) % 10);
_tokenURIBytes[38] = byte(48+(_tokenId / 100) % 10);
_tokenURIBytes[39] = byte(48+(_tokenId / 10) % 10);
_tokenURIBytes[40] = byte(48+(_tokenId / 1) % 10);
}
//
// Points interface
//
// configureKeys(): configure _point with network public keys
// _encryptionKey, _authenticationKey,
// and corresponding _cryptoSuiteVersion,
// incrementing the point's continuity number if needed
//
function configureKeys(uint32 _point,
bytes32 _encryptionKey,
bytes32 _authenticationKey,
uint32 _cryptoSuiteVersion,
bool _discontinuous)
external
activePointManager(_point)
{
if (_discontinuous)
{
azimuth.incrementContinuityNumber(_point);
}
azimuth.setKeys(_point,
_encryptionKey,
_authenticationKey,
_cryptoSuiteVersion);
}
// spawn(): spawn _point, then either give, or allow _target to take,
// ownership of _point
//
// if _target is the :msg.sender, _targets owns the _point right away.
// otherwise, _target becomes the transfer proxy of _point.
//
// Requirements:
// - _point must not be active
// - _point must not be a planet with a galaxy prefix
// - _point's prefix must be linked and under its spawn limit
// - :msg.sender must be either the owner of _point's prefix,
// or an authorized spawn proxy for it
//
function spawn(uint32 _point, address _target)
external
{
// only currently unowned (and thus also inactive) points can be spawned
//
require(azimuth.isOwner(_point, 0x0));
// prefix: half-width prefix of _point
//
uint16 prefix = azimuth.getPrefix(_point);
// only allow spawning of points of the size directly below the prefix
//
// this is possible because of how the address space works,
// but supporting it introduces complexity through broken assumptions.
//
// example:
// 0x0000.0000 - galaxy zero
// 0x0000.0100 - the first star of galaxy zero
// 0x0001.0100 - the first planet of the first star
// 0x0001.0000 - the first planet of galaxy zero
//
require( (uint8(azimuth.getPointSize(prefix)) + 1) ==
uint8(azimuth.getPointSize(_point)) );
// prefix point must be linked and able to spawn
//
require( (azimuth.hasBeenLinked(prefix)) &&
( azimuth.getSpawnCount(prefix) <
getSpawnLimit(prefix, block.timestamp) ) );
// the owner of a prefix can always spawn its children;
// other addresses need explicit permission (the role
// of "spawnProxy" in the Azimuth contract)
//
require( azimuth.canSpawnAs(prefix, msg.sender) );
// if the caller is spawning the point to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_point, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern
// making the _point prefix's owner the _point owner in the mean time
//
else
{
doSpawn(_point, _target, false, azimuth.getOwner(prefix));
}
}
// doSpawn(): actual spawning logic, used in spawn(). creates _point,
// making the _target its owner if _direct, or making the
// _holder the owner and the _target the transfer proxy
// if not _direct.
//
function doSpawn( uint32 _point,
address _target,
bool _direct,
address _holder )
internal
{
// register the spawn for _point's prefix, incrementing spawn count
//
azimuth.registerSpawned(_point);
// if the spawn is _direct, assume _target knows what they're doing
// and resolve right away
//
if (_direct)
{
// make the point active and set its new owner
//
azimuth.activatePoint(_point);
azimuth.setOwner(_point, _target);
emit Transfer(0x0, _target, uint256(_point));
}
//
// when spawning indirectly, enforce a withdraw pattern by approving
// the _target for transfer of the _point instead.
// we make the _holder the owner of this _point in the mean time,
// so that it may cancel the transfer (un-approve) if _target flakes.
// we don't make _point active yet, because it still doesn't really
// belong to anyone.
//
else
{
// have _holder hold on to the _point while _target gets to transfer
// ownership of it
//
azimuth.setOwner(_point, _holder);
azimuth.setTransferProxy(_point, _target);
emit Transfer(0x0, _holder, uint256(_point));
emit Approval(_holder, _target, uint256(_point));
}
}
// transferPoint(): transfer _point to _target, clearing all permissions
// data and keys if _reset is true
//
// Note: the _reset flag is useful when transferring the point to
// a recipient who doesn't trust the previous owner.
//
// Requirements:
// - :msg.sender must be either _point's current owner, authorized
// to transfer _point, or authorized to transfer the current
// owner's points (as in ERC721's operator)
// - _target must not be the zero address
//
function transferPoint(uint32 _point, address _target, bool _reset)
public
{
// transfer is legitimate if the caller is the current owner, or
// an operator for the current owner, or the _point's transfer proxy
//
require(azimuth.canTransfer(_point, msg.sender));
// if the point wasn't active yet, that means transferring it
// is part of the "spawn" flow, so we need to activate it
//
if ( !azimuth.isActive(_point) )
{
azimuth.activatePoint(_point);
}
// if the owner would actually change, change it
//
// the only time this deliberately wouldn't be the case is when a
// prefix owner wants to activate a spawned but untransferred child.
//
if ( !azimuth.isOwner(_point, _target) )
{
// remember the previous owner, to be included in the Transfer event
//
address old = azimuth.getOwner(_point);
azimuth.setOwner(_point, _target);
// according to ERC721, the approved address (here, transfer proxy)
// gets cleared during every Transfer event
//
azimuth.setTransferProxy(_point, 0);
emit Transfer(old, _target, uint256(_point));
}
// reset sensitive data
// used when transferring the point to a new owner
//
if ( _reset )
{
// clear the network public keys and break continuity,
// but only if the point has already been linked
//
if ( azimuth.hasBeenLinked(_point) )
{
azimuth.incrementContinuityNumber(_point);
azimuth.setKeys(_point, 0, 0, 0);
}
// clear management proxy
//
azimuth.setManagementProxy(_point, 0);
// clear voting proxy
//
azimuth.setVotingProxy(_point, 0);
// clear transfer proxy
//
// in most cases this is done above, during the ownership transfer,
// but we might not hit that and still be expected to reset the
// transfer proxy.
// doing it a second time is a no-op in Azimuth.
//
azimuth.setTransferProxy(_point, 0);
// clear spawning proxy
//
azimuth.setSpawnProxy(_point, 0);
// clear claims
//
claims.clearClaims(_point);
}
}
// escape(): request escape as _point to _sponsor
//
// if an escape request is already active, this overwrites
// the existing request
//
// Requirements:
// - :msg.sender must be the owner or manager of _point,
// - _point must be able to escape to _sponsor as per to canEscapeTo()
//
function escape(uint32 _point, uint32 _sponsor)
external
activePointManager(_point)
{
require(canEscapeTo(_point, _sponsor));
azimuth.setEscapeRequest(_point, _sponsor);
}
// cancelEscape(): cancel the currently set escape for _point
//
function cancelEscape(uint32 _point)
external
activePointManager(_point)
{
azimuth.cancelEscape(_point);
}
// adopt(): as the relevant sponsor, accept the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function adopt(uint32 _point)
external
{
require( azimuth.isEscaping(_point) &&
azimuth.canManage( azimuth.getEscapeRequest(_point),
msg.sender ) );
// _sponsor becomes _point's sponsor
// its escape request is reset to "not escaping"
//
azimuth.doEscape(_point);
}
// reject(): as the relevant sponsor, deny the _point's request
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's requested sponsor
//
function reject(uint32 _point)
external
{
require( azimuth.isEscaping(_point) &&
azimuth.canManage( azimuth.getEscapeRequest(_point),
msg.sender ) );
// reset the _point's escape request to "not escaping"
//
azimuth.cancelEscape(_point);
}
// detach(): as the _sponsor, stop sponsoring the _point
//
// Requirements:
// - :msg.sender must be the owner or management proxy
// of _point's current sponsor
//
function detach(uint32 _point)
external
{
require( azimuth.hasSponsor(_point) &&
azimuth.canManage(azimuth.getSponsor(_point), msg.sender) );
// signal that its sponsor no longer supports _point
//
azimuth.loseSponsor(_point);
}
//
// Point rules
//
// getSpawnLimit(): returns the total number of children the _point
// is allowed to spawn at _time.
//
function getSpawnLimit(uint32 _point, uint256 _time)
public
view
returns (uint32 limit)
{
Azimuth.Size size = azimuth.getPointSize(_point);
if ( size == Azimuth.Size.Galaxy )
{
return 255;
}
else if ( size == Azimuth.Size.Star )
{
// in 2019, stars may spawn at most 1024 planets. this limit doubles
// for every subsequent year.
//
// Note: 1546300800 corresponds to 2019-01-01
//
uint256 yearsSince2019 = (_time - 1546300800) / 365 days;
if (yearsSince2019 < 6)
{
limit = uint32( 1024 * (2 ** yearsSince2019) );
}
else
{
limit = 65535;
}
return limit;
}
else // size == Azimuth.Size.Planet
{
// planets can create moons, but moons aren't on the chain
//
return 0;
}
}
// canEscapeTo(): true if _point could try to escape to _sponsor
//
function canEscapeTo(uint32 _point, uint32 _sponsor)
public
view
returns (bool canEscape)
{
// can't escape to a sponsor that hasn't been linked
//
if ( !azimuth.hasBeenLinked(_sponsor) ) return false;
// Can only escape to a point one size higher than ourselves,
// except in the special case where the escaping point hasn't
// been linked yet -- in that case we may escape to points of
// the same size, to support lightweight invitation chains.
//
// The use case for lightweight invitations is that a planet
// owner should be able to invite their friends onto an
// Azimuth network in a two-party transaction, without a new
// star relationship.
// The lightweight invitation process works by escaping your
// own active (but never linked) point to one of your own
// points, then transferring the point to your friend.
//
// These planets can, in turn, sponsor other unlinked planets,
// so the "planet sponsorship chain" can grow to arbitrary
// length. Most users, especially deep down the chain, will
// want to improve their performance by switching to direct
// star sponsors eventually.
//
Azimuth.Size pointSize = azimuth.getPointSize(_point);
Azimuth.Size sponsorSize = azimuth.getPointSize(_sponsor);
return ( // normal hierarchical escape structure
//
( (uint8(sponsorSize) + 1) == uint8(pointSize) ) ||
//
// special peer escape
//
( (sponsorSize == pointSize) &&
//
// peer escape is only for points that haven't been linked
// yet, because it's only for lightweight invitation chains
//
!azimuth.hasBeenLinked(_point) ) );
}
//
// Permission management
//
// setManagementProxy(): configure the management proxy for _point
//
// The management proxy may perform "reversible" operations on
// behalf of the owner. This includes public key configuration and
// operations relating to sponsorship.
//
function setManagementProxy(uint32 _point, address _manager)
external
activePointOwner(_point)
{
azimuth.setManagementProxy(_point, _manager);
}
// setSpawnProxy(): give _spawnProxy the right to spawn points
// with the prefix _prefix
//
function setSpawnProxy(uint16 _prefix, address _spawnProxy)
external
activePointOwner(_prefix)
{
azimuth.setSpawnProxy(_prefix, _spawnProxy);
}
// setVotingProxy(): configure the voting proxy for _galaxy
//
// the voting proxy is allowed to start polls and cast votes
// on the point's behalf.
//
function setVotingProxy(uint8 _galaxy, address _voter)
external
activePointOwner(_galaxy)
{
azimuth.setVotingProxy(_galaxy, _voter);
}
// setTransferProxy(): give _transferProxy the right to transfer _point
//
// Requirements:
// - :msg.sender must be either _point's current owner,
// or be an operator for the current owner
//
function setTransferProxy(uint32 _point, address _transferProxy)
public
{
// owner: owner of _point
//
address owner = azimuth.getOwner(_point);
// caller must be :owner, or an operator designated by the owner.
//
require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender));
// set transfer proxy field in Azimuth contract
//
azimuth.setTransferProxy(_point, _transferProxy);
// emit Approval event
//
emit Approval(owner, _transferProxy, uint256(_point));
}
//
// Poll actions
//
// startUpgradePoll(): as _galaxy, start a poll for the ecliptic
// upgrade _proposal
//
// Requirements:
// - :msg.sender must be the owner or voting proxy of _galaxy,
// - the _proposal must expect to be upgraded from this specific
// contract, as indicated by its previousEcliptic attribute
//
function startUpgradePoll(uint8 _galaxy, EclipticBase _proposal)
external
activePointVoter(_galaxy)
{
// ensure that the upgrade target expects this contract as the source
//
require(_proposal.previousEcliptic() == address(this));
polls.startUpgradePoll(_proposal);
}
// startDocumentPoll(): as _galaxy, start a poll for the _proposal
//
// the _proposal argument is the keccak-256 hash of any arbitrary
// document or string of text
//
function startDocumentPoll(uint8 _galaxy, bytes32 _proposal)
external
activePointVoter(_galaxy)
{
polls.startDocumentPoll(_proposal);
}
// castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic
// upgrade _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
// If this vote results in a majority for the _proposal, it will
// be upgraded to immediately.
//
function castUpgradeVote(uint8 _galaxy,
EclipticBase _proposal,
bool _vote)
external
activePointVoter(_galaxy)
{
// majority: true if the vote resulted in a majority, false otherwise
//
bool majority = polls.castUpgradeVote(_galaxy, _proposal, _vote);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// castDocumentVote(): as _galaxy, cast a _vote on the _proposal
//
// _vote is true when in favor of the proposal, false otherwise
//
function castDocumentVote(uint8 _galaxy, bytes32 _proposal, bool _vote)
external
activePointVoter(_galaxy)
{
polls.castDocumentVote(_galaxy, _proposal, _vote);
}
// updateUpgradePoll(): check whether the _proposal has achieved
// majority, upgrading to it if it has
//
function updateUpgradePoll(EclipticBase _proposal)
external
{
// majority: true if the poll ended in a majority, false otherwise
//
bool majority = polls.updateUpgradePoll(_proposal);
// if a majority is in favor of the upgrade, it happens as defined
// in the ecliptic base contract
//
if (majority)
{
upgrade(_proposal);
}
}
// updateDocumentPoll(): check whether the _proposal has achieved majority
//
// Note: the polls contract publicly exposes the function this calls,
// but we offer it in the ecliptic interface as a convenience
//
function updateDocumentPoll(bytes32 _proposal)
external
{
polls.updateDocumentPoll(_proposal);
}
//
// Contract owner operations
//
// createGalaxy(): grant _target ownership of the _galaxy and register
// it for voting
//
function createGalaxy(uint8 _galaxy, address _target)
external
onlyOwner
{
// only currently unowned (and thus also inactive) galaxies can be
// created, and only to non-zero addresses
//
require( azimuth.isOwner(_galaxy, 0x0) &&
0x0 != _target );
// new galaxy means a new registered voter
//
polls.incrementTotalVoters();
// if the caller is sending the galaxy to themselves,
// assume it knows what it's doing and resolve right away
//
if (msg.sender == _target)
{
doSpawn(_galaxy, _target, true, 0x0);
}
//
// when sending to a "foreign" address, enforce a withdraw pattern,
// making the caller the owner in the mean time
//
else
{
doSpawn(_galaxy, _target, false, msg.sender);
}
}
function setDnsDomains(string _primary, string _secondary, string _tertiary)
external
onlyOwner
{
azimuth.setDnsDomains(_primary, _secondary, _tertiary);
}
//
// Function modifiers for this contract
//
// validPointId(): require that _id is a valid point
//
modifier validPointId(uint256 _id)
{
require(_id < 0x100000000);
_;
}
// activePointVoter(): require that :msg.sender can vote as _point,
// and that _point is active
//
modifier activePointVoter(uint32 _point)
{
require( azimuth.canVoteAs(_point, msg.sender) &&
azimuth.isActive(_point) );
_;
}
}
////////////////////////////////////////////////////////////////////////////////
// DelegatedSending
////////////////////////////////////////////////////////////////////////////////
// DelegatedSending: invite-like point sending
//
// This contract allows planet owners to gift planets to their friends,
// if their prefix has allowed it.
//
// Star owners can set a limit, the amount of "invite planets" each of
// their planets is allowed to send. Enabling this by setting the limit
// to a value higher than zero can help the network grow by providing
// regular users with a way to get their friends and family onto it.
//
// To allow planets to be sent by this contract, stars must set it as
// their spawnProxy using the Ecliptic.
//
contract DelegatedSending is ReadsAzimuth
{
// Sent: :by sent :point
//
event Sent( uint16 indexed prefix,
uint64 indexed fromPool,
uint32 by,
uint32 point,
address to);
// limits: per star, the maximum amount of planets any of its planets may
// give away
//
mapping(uint16 => uint16) public limits;
// pools: per pool, the amount of planets that have been given away by
// the pool's planet itself or the ones it invited
//
// pools are associated with planets by number, pool n belongs to
// planet n - 1.
// pool 0 does not exist, and is used symbolically by :fromPool.
//
mapping(uint64 => uint16) public pools;
// fromPool: per planet, the pool from which they were sent/invited
//
// when invited by planet n, the invitee is registered in pool n + 1.
// a pool of 0 means the planet has its own invite pool.
// this is done so that all planets that were born outside of this
// contract start out with their own pool (0, solidity default),
// while we configure planets created through this contract to use
// their inviter's pool.
//
mapping(uint32 => uint64) public fromPool;
// constructor(): register the azimuth contract
//
constructor(Azimuth _azimuth)
ReadsAzimuth(_azimuth)
public
{
//
}
// configureLimit(): as the owner of a star, configure the amount of
// planets that may be given away per point.
//
function configureLimit(uint16 _prefix, uint16 _limit)
external
activePointOwner(_prefix)
{
limits[_prefix] = _limit;
}
// resetPool(): grant _for their own invite pool in case they still
// share one and reset its counter to zero
//
function resetPool(uint32 _for)
external
activePointOwner(azimuth.getPrefix(_for))
{
fromPool[_for] = 0;
pools[uint64(_for) + 1] = 0;
}
// sendPoint(): as the point _as, spawn the point _point to _to.
//
// Requirements:
// - :msg.sender must be the owner of _as,
// - _to must not be the :msg.sender,
// - _as must be able to send the _point according to canSend()
//
function sendPoint(uint32 _as, uint32 _point, address _to)
external
activePointOwner(_as)
{
require(canSend(_as, _point));
// caller may not send to themselves
//
require(msg.sender != _to);
// recipient must be eligible to receive a planet from this contract
//
require(canReceive(_to));
// increment the sent counter for _as.
//
uint64 pool = getPool(_as);
pools[pool]++;
// associate the _point with this pool
//
fromPool[_point] = pool;
// spawn _point to _to, they still need to accept the transfer manually
//
Ecliptic(azimuth.owner()).spawn(_point, _to);
emit Sent(azimuth.getPrefix(_point), pool, _as, _point, _to);
}
// canSend(): check whether current conditions allow _as to send _point
//
function canSend(uint32 _as, uint32 _point)
public
view
returns (bool result)
{
uint16 prefix = azimuth.getPrefix(_as);
uint64 pool = getPool(_as);
return ( // can only send points with the same prefix
//
(prefix == azimuth.getPrefix(_point)) &&
//
// _as must not have hit the allowed limit yet
//
(pools[pool] < limits[prefix]) &&
//
// _point needs to not be (in the process of being) spawned
//
azimuth.isOwner(_point, 0x0) &&
//
// this contract must have permission to spawn points
//
azimuth.isSpawnProxy(prefix, this) &&
//
// the prefix must be linked
//
azimuth.hasBeenLinked(prefix) &&
//
// the prefix must not have hit its spawn limit yet
//
( azimuth.getSpawnCount(prefix) <
Ecliptic(azimuth.owner())
.getSpawnLimit(prefix, block.timestamp) ) );
}
// getPool(): get the invite pool _point belongs to
//
function getPool(uint32 _point)
internal
view
returns (uint64 pool)
{
pool = fromPool[_point];
// no pool explicitly registered means they have their own pool,
// because they either were not invited by this contract, or have
// been granted their own pool by their star.
//
if (0 == pool)
{
// the pool for planet n is n + 1, see also :fromPool
//
return uint64(_point) + 1;
}
return pool;
}
// canReceive(): whether the _recipient is eligible to receive a planet
// from this contract or not
//
// only those who don't own or are entitled to any points may receive
//
function canReceive(address _recipient)
public
view
returns (bool result)
{
return ( 0 == azimuth.getOwnedPointCount(_recipient) &&
0 == azimuth.getTransferringForCount(_recipient) );
}
}
|
setTransferProxy(): give _transferProxy the right to transfer _point Requirements: - :msg.sender must be either _point's current owner, or be an operator for the current owner owner: owner of _point caller must be :owner, or an operator designated by the owner. set transfer proxy field in Azimuth contract emit Approval event
|
function setTransferProxy(uint32 _point, address _transferProxy)
public
{
address owner = azimuth.getOwner(_point);
require((owner == msg.sender) || azimuth.isOperator(owner, msg.sender));
azimuth.setTransferProxy(_point, _transferProxy);
emit Approval(owner, _transferProxy, uint256(_point));
}
| 1,401,199 |
[
1,
542,
5912,
3886,
13332,
8492,
389,
13866,
3886,
326,
2145,
358,
7412,
389,
1153,
565,
29076,
30,
565,
300,
294,
3576,
18,
15330,
1297,
506,
3344,
389,
1153,
1807,
783,
3410,
16,
1377,
578,
506,
392,
3726,
364,
326,
783,
3410,
225,
3410,
30,
3410,
434,
389,
1153,
225,
4894,
1297,
506,
294,
8443,
16,
578,
392,
3726,
25264,
635,
326,
3410,
18,
225,
444,
7412,
2889,
652,
316,
432,
94,
15968,
6835,
225,
3626,
1716,
685,
1125,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
5912,
3886,
12,
11890,
1578,
389,
1153,
16,
1758,
389,
13866,
3886,
13,
203,
1377,
1071,
203,
565,
288,
203,
1377,
1758,
3410,
273,
23090,
18,
588,
5541,
24899,
1153,
1769,
203,
203,
1377,
2583,
12443,
8443,
422,
1234,
18,
15330,
13,
747,
23090,
18,
291,
5592,
12,
8443,
16,
1234,
18,
15330,
10019,
203,
203,
1377,
23090,
18,
542,
5912,
3886,
24899,
1153,
16,
389,
13866,
3886,
1769,
203,
203,
1377,
3626,
1716,
685,
1125,
12,
8443,
16,
389,
13866,
3886,
16,
2254,
5034,
24899,
1153,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0xFFCAaE2a77254B4cd72356B27377408ab31155b4/sources/CallMarket.sol
|
throws exception if the buylist is empty
|
require (buyList.length != 0,'buyList is empty!');
| 8,538,348 |
[
1,
15069,
1520,
309,
326,
30143,
1098,
353,
1008,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
2583,
261,
70,
9835,
682,
18,
2469,
480,
374,
11189,
70,
9835,
682,
353,
1008,
5124,
1769,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// solhint-disable
pragma solidity ^0.5.5;
/// @dev This contract documents the revert reasons used in the AssetProxy contracts.
/// This contract is intended to serve as a reference, but is not actually used for efficiency reasons.
contract LibAssetProxyErrors {
/// Authorizable errors ///
string constant internal SENDER_NOT_AUTHORIZED = "SENDER_NOT_AUTHORIZED"; // Sender not authorized to call this method.
string constant internal TARGET_NOT_AUTHORIZED = "TARGET_NOT_AUTHORIZED"; // Target address not authorized to call this method.
string constant internal TARGET_ALREADY_AUTHORIZED = "TARGET_ALREADY_AUTHORIZED"; // Target address must not already be authorized.
string constant internal INDEX_OUT_OF_BOUNDS = "INDEX_OUT_OF_BOUNDS"; // Specified array index is out of bounds.
string constant internal AUTHORIZED_ADDRESS_MISMATCH = "AUTHORIZED_ADDRESS_MISMATCH"; // Address at index does not match given target address.
/// Transfer errors ///
string constant internal INVALID_AMOUNT = "INVALID_AMOUNT"; // Transfer amount must equal 1.
string constant internal TRANSFER_FAILED = "TRANSFER_FAILED"; // Transfer failed.
string constant internal LENGTH_GREATER_THAN_131_REQUIRED = "LENGTH_GREATER_THAN_131_REQUIRED"; // Byte array must have a length greater than 0.
}
|
Specified array index is out of bounds.
|
string constant internal INDEX_OUT_OF_BOUNDS = "INDEX_OUT_OF_BOUNDS";
| 7,313,768 |
[
1,
17068,
526,
770,
353,
596,
434,
4972,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
533,
5381,
2713,
12425,
67,
5069,
67,
3932,
67,
5315,
2124,
3948,
273,
315,
9199,
67,
5069,
67,
3932,
67,
5315,
2124,
3948,
14432,
11794,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xc45865b235a7c6693b9db5fed46ea8a3022d9b07
//Contract name: KATXDcorpMemberProxy
//Balance: 0 Ether
//Verification Date: 11/26/2017
//Transacion Count: 4
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* IOwnership
*
* Perminent ownership
*
* #created 01/10/2017
* #author Frank Bonnet
*/
interface IOwnership {
/**
* Returns true if `_account` is the current owner
*
* @param _account The address to test against
*/
function isOwner(address _account) public view returns (bool);
/**
* Gets the current owner
*
* @return address The current owner
*/
function getOwner() public view returns (address);
}
/**
* Ownership
*
* Perminent ownership
*
* #created 01/10/2017
* #author Frank Bonnet
*/
contract Ownership is IOwnership {
// Owner
address internal owner;
/**
* Access is restricted to the current owner
*/
modifier only_owner() {
require(msg.sender == owner);
_;
}
/**
* The publisher is the inital owner
*/
function Ownership() public {
owner = msg.sender;
}
/**
* Returns true if `_account` is the current owner
*
* @param _account The address to test against
*/
function isOwner(address _account) public view returns (bool) {
return _account == owner;
}
/**
* Gets the current owner
*
* @return address The current owner
*/
function getOwner() public view returns (address) {
return owner;
}
}
/**
* ERC20 compatible token interface
*
* - Implements ERC 20 Token standard
* - Implements short address attack fix
*
* #created 29/09/2017
* #author Frank Bonnet
*/
interface IToken {
/**
* Get the total supply of tokens
*
* @return The total supply
*/
function totalSupply() public view returns (uint);
/**
* Get balance of `_owner`
*
* @param _owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address _owner) public view returns (uint);
/**
* 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, uint _value) public returns (bool);
/**
* 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, uint _value) public returns (bool);
/**
* `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, uint _value) public returns (bool);
/**
* Get the amount of remaining tokens that `_spender` is allowed to spend from `_owner`
*
* @param _owner The address of the account owning tokens
* @param _spender The address of the account able to transfer the tokens
* @return Amount of remaining tokens allowed to spent
*/
function allowance(address _owner, address _spender) public view returns (uint);
}
/**
* ITokenObserver
*
* Allows a token smart-contract to notify observers
* when tokens are received
*
* #created 09/10/2017
* #author Frank Bonnet
*/
interface ITokenObserver {
/**
* Called by the observed token smart-contract in order
* to notify the token observer when tokens are received
*
* @param _from The address that the tokens where send from
* @param _value The amount of tokens that was received
*/
function notifyTokensReceived(address _from, uint _value) public;
}
/**
* TokenObserver
*
* Allows observers to be notified by an observed token smart-contract
* when tokens are received
*
* #created 09/10/2017
* #author Frank Bonnet
*/
contract TokenObserver is ITokenObserver {
/**
* Called by the observed token smart-contract in order
* to notify the token observer when tokens are received
*
* @param _from The address that the tokens where send from
* @param _value The amount of tokens that was received
*/
function notifyTokensReceived(address _from, uint _value) public {
onTokensReceived(msg.sender, _from, _value);
}
/**
* Event handler
*
* Called by `_token` when a token amount is received
*
* @param _token The token contract that received the transaction
* @param _from The account or contract that send the transaction
* @param _value The value of tokens that where received
*/
function onTokensReceived(address _token, address _from, uint _value) internal;
}
/**
* ITokenRetriever
*
* Allows tokens to be retrieved from a contract
*
* #created 29/09/2017
* #author Frank Bonnet
*/
interface ITokenRetriever {
/**
* Extracts tokens from the contract
*
* @param _tokenContract The address of ERC20 compatible token
*/
function retrieveTokens(address _tokenContract) public;
}
/**
* TokenRetriever
*
* Allows tokens to be retrieved from a contract
*
* #created 18/10/2017
* #author Frank Bonnet
*/
contract TokenRetriever is ITokenRetriever {
/**
* Extracts tokens from the contract
*
* @param _tokenContract The address of ERC20 compatible token
*/
function retrieveTokens(address _tokenContract) public {
IToken tokenInstance = IToken(_tokenContract);
uint tokenBalance = tokenInstance.balanceOf(this);
if (tokenBalance > 0) {
tokenInstance.transfer(msg.sender, tokenBalance);
}
}
}
/**
* IDcorpCrowdsaleAdapter
*
* Interface that allows collective contributions from DCORP members
*
* DCORP DAO VC & Promotion https://www.dcorp.it
*
* #created 10/11/2017
* #author Frank Bonnet
*/
interface IDcorpCrowdsaleAdapter {
/**
* Receive Eth and issue tokens to the sender
*/
function isEnded() public view returns (bool);
/**
* Receive ether and issue tokens to the sender
*
* @return The accepted ether amount
*/
function contribute() public payable returns (uint);
/**
* Receive ether and issue tokens to `_beneficiary`
*
* @param _beneficiary The account that receives the tokens
* @return The accepted ether amount
*/
function contributeFor(address _beneficiary) public payable returns (uint);
/**
* Withdraw allocated tokens
*/
function withdrawTokens() public;
/**
* Withdraw allocated ether
*/
function withdrawEther() public;
/**
* Refund in the case of an unsuccessful crowdsale. The
* crowdsale is considered unsuccessful if minAmount was
* not raised before end of the crowdsale
*/
function refund() public;
}
/**
* IDcorpPersonalCrowdsaleProxy
*
* #created 22/11/2017
* #author Frank Bonnet
*/
interface IDcorpPersonalCrowdsaleProxy {
/**
* Receive ether and issue tokens
*
* This function requires that msg.sender is not a contract. This is required because it's
* not possible for a contract to specify a gas amount when calling the (internal) send()
* function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing)
*
* Contracts can call the contribute() function instead
*/
function () public payable;
}
/**
* DcorpPersonalCrowdsaleProxy
*
* Proxy that allows collective contributions from DCORP members using
* a unique address
*
* DCORP DAO VC & Promotion https://www.dcorp.it
*
* #created 22/11/2017
* #author Frank Bonnet
*/
contract DcorpPersonalCrowdsaleProxy is IDcorpPersonalCrowdsaleProxy {
address public member;
IDcorpCrowdsaleAdapter public target;
/**
* Deploy proxy
*
* @param _member Owner of the proxy
* @param _target Target crowdsale
*/
function DcorpPersonalCrowdsaleProxy(address _member, address _target) public {
target = IDcorpCrowdsaleAdapter(_target);
member = _member;
}
/**
* Receive contribution and forward to the target crowdsale
*
* This function requires that msg.sender is not a contract. This is required because it's
* not possible for a contract to specify a gas amount when calling the (internal) send()
* function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing)
*/
function () public payable {
target.contributeFor.value(msg.value)(member);
}
}
/**
* IDcorpCrowdsaleProxy
*
* #created 23/11/2017
* #author Frank Bonnet
*/
interface IDcorpCrowdsaleProxy {
/**
* Receive ether and issue tokens to the sender
*
* This function requires that msg.sender is not a contract. This is required because it's
* not possible for a contract to specify a gas amount when calling the (internal) send()
* function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing)
*
* Contracts can call the contribute() function instead
*/
function () public payable;
/**
* Receive ether and issue tokens to the sender
*
* @return The accepted ether amount
*/
function contribute() public payable returns (uint);
/**
* Receive ether and issue tokens to `_beneficiary`
*
* @param _beneficiary The account that receives the tokens
* @return The accepted ether amount
*/
function contributeFor(address _beneficiary) public payable returns (uint);
}
/**
* DcorpCrowdsaleProxy
*
* Proxy that allows collective contributions from DCORP members
*
* DCORP DAO VC & Promotion https://www.dcorp.it
*
* #created 22/11/2017
* #author Frank Bonnet
*/
contract DcorpCrowdsaleProxy is IDcorpCrowdsaleProxy, Ownership, TokenObserver, TokenRetriever {
enum Stages {
Deploying,
Attached,
Deployed
}
struct Record {
uint weight;
uint contributed;
uint withdrawnTokens;
uint index;
}
Stages public stage;
bool private updating;
// Member records
mapping (address => Record) private records;
address[] private recordIndex;
uint public totalContributed;
uint public totalTokensReceived;
uint public totalTokensWithdrawn;
uint public totalWeight;
// Weight calculation
uint public factorWeight;
uint public factorContributed;
// Target crowdsale
IDcorpCrowdsaleAdapter public crowdsale;
IToken public token;
// Dcorp tokens
IToken public drpsToken;
IToken public drpuToken;
/**
* Throw if at stage other than current stage
*
* @param _stage expected stage to test for
*/
modifier at_stage(Stages _stage) {
require(stage == _stage);
_;
}
/**
* Throw if crowdsale not ended yet
*/
modifier only_when_ended() {
require(crowdsale.isEnded());
_;
}
/**
* Prevent reentry
*/
modifier only_when_not_updating() {
require(!updating);
_;
}
// Events
event DcorpProxyCreated(address proxy, address beneficiary);
/**
* Deploy the proxy
*/
function DcorpCrowdsaleProxy() public {
stage = Stages.Deploying;
}
/**
* Setup the proxy
*
* Share calcuation is based on the drpu and drps token balances and the
* contributed amount of ether. The weight factor and contributed factor
* determin the weight of each factor
*
* @param _drpsToken 1/2 tokens used for weight calculation
* @param _drpuToken 2/2 tokens used for weight calculation
* @param _factorWeight Weight of the token balance factor
* @param _factorContributed Weight of the contributed amount factor
*/
function setup(address _drpsToken, address _drpuToken, uint _factorWeight, uint _factorContributed) public only_owner at_stage(Stages.Deploying) {
drpsToken = IToken(_drpsToken);
drpuToken = IToken(_drpuToken);
factorWeight = _factorWeight;
factorContributed = _factorContributed;
}
/**
* Attach a crowdsale and corresponding token to the proxy. Contributions are
* forwarded to `_crowdsale` and rewards are denoted in tokens located at `_token`
*
* @param _crowdsale The crowdsale to forward contributions to
* @param _token The reward token
*/
function attachCrowdsale(address _crowdsale, address _token) public only_owner at_stage(Stages.Deploying) {
stage = Stages.Attached;
crowdsale = IDcorpCrowdsaleAdapter(_crowdsale);
token = IToken(_token);
}
/**
* After calling the deploy function the proxy's
* rules become immutable
*/
function deploy() public only_owner at_stage(Stages.Attached) {
stage = Stages.Deployed;
}
/**
* Deploy a contract that serves as a proxy to
* the crowdsale
*
* Contributions through this address will be made
* for msg.sender
*
* @return The address of the deposit address
*/
function createPersonalDepositAddress() public returns (address) {
address proxy = new DcorpPersonalCrowdsaleProxy(msg.sender, this);
DcorpProxyCreated(proxy, msg.sender);
return proxy;
}
/**
* Deploy a contract that serves as a proxy to
* the crowdsale
*
* Contributions through this address will be made
* for `_beneficiary`
*
* @param _beneficiary The owner of the proxy
* @return The address of the deposit address
*/
function createPersonalDepositAddressFor(address _beneficiary) public returns (address) {
address proxy = new DcorpPersonalCrowdsaleProxy(_beneficiary, this);
DcorpProxyCreated(proxy, _beneficiary);
return proxy;
}
/**
* Returns true if `_member` has a record
*
* @param _member The account that has contributed
* @return True if there is a record that belongs to `_member`
*/
function hasRecord(address _member) public view returns (bool) {
return records[_member].index < recordIndex.length && _member == recordIndex[records[_member].index];
}
/**
* Get the recorded amount of ether that is contributed by `_member`
*
* @param _member The address from which the contributed amount will be retrieved
* @return The contributed amount
*/
function contributedAmountOf(address _member) public view returns (uint) {
return records[_member].contributed;
}
/**
* Get the allocated token balance of `_member`
*
* @param _member The address from which the allocated token balance will be retrieved
* @return The allocated token balance
*/
function balanceOf(address _member) public view returns (uint) {
Record storage r = records[_member];
uint balance = 0;
uint share = shareOf(_member);
if (share > 0 && r.withdrawnTokens < share) {
balance = share - r.withdrawnTokens;
}
return balance;
}
/**
* Get the total share of the received tokens of `_member`
*
* Share calcuation is based on the drpu and drps token balances and the
* contributed amount of ether. The weight factor and contributed factor
* determin the weight of each factor
*
* @param _member The address from which the share will be retrieved
* @return The total share
*/
function shareOf(address _member) public view returns (uint) {
Record storage r = records[_member];
// Factored totals
uint factoredTotalWeight = totalWeight * factorWeight;
uint factoredTotalContributed = totalContributed * factorContributed;
// Factored member
uint factoredWeight = r.weight * factorWeight;
uint factoredContributed = r.contributed * factorContributed;
// Calculate share (member / total * tokens)
return (factoredWeight + factoredContributed) * totalTokensReceived / (factoredTotalWeight + factoredTotalContributed);
}
/**
* Request tokens from the target crowdsale by calling
* it's withdraw token function
*/
function requestTokensFromCrowdsale() public only_when_not_updating {
crowdsale.withdrawTokens();
}
/**
* Update internal token balance
*
* Tokens that are received at the proxies address are
* recorded internally
*/
function updateBalances() public only_when_not_updating {
updating = true;
uint recordedBalance = totalTokensReceived - totalTokensWithdrawn;
uint actualBalance = token.balanceOf(this);
// Update balance intrnally
if (actualBalance > recordedBalance) {
totalTokensReceived += actualBalance - recordedBalance;
}
updating = false;
}
/**
* Withdraw allocated tokens
*/
function withdrawTokens() public only_when_ended only_when_not_updating {
address member = msg.sender;
uint balance = balanceOf(member);
// Record internally
records[member].withdrawnTokens += balance;
totalTokensWithdrawn += balance;
// Transfer share
if (!token.transfer(member, balance)) {
revert();
}
}
/**
* Receive Eth and issue tokens to the sender
*
* This function requires that msg.sender is not a contract. This is required because it's
* not possible for a contract to specify a gas amount when calling the (internal) send()
* function. Solidity imposes a maximum amount of gas (2300 gas at the time of writing)
*
* Contracts can call the contribute() function instead
*/
function () public payable {
require(msg.sender == tx.origin);
_handleTransaction(msg.sender);
}
/**
* Receive ether and issue tokens to the sender
*
* @return The accepted ether amount
*/
function contribute() public payable returns (uint) {
return _handleTransaction(msg.sender);
}
/**
* Receive ether and issue tokens to `_beneficiary`
*
* @param _beneficiary The account that receives the tokens
* @return The accepted ether amount
*/
function contributeFor(address _beneficiary) public payable returns (uint) {
return _handleTransaction(_beneficiary);
}
/**
* Failsafe mechanism
*
* Allows the owner to retrieve tokens from the contract that
* might have been send there by accident
*
* @param _tokenContract The address of ERC20 compatible token
*/
function retrieveTokens(address _tokenContract) public only_owner {
require(_tokenContract != address(token));
super.retrieveTokens(_tokenContract);
}
/**
* Event handler that processes the token received event
*
* Called by `_token` when a token amount is received on
* the address of this proxy
*
* @param _token The token contract that received the transaction
* @param _from The account or contract that send the transaction
* @param _value The value of tokens that where received
*/
function onTokensReceived(address _token, address _from, uint _value) internal {
require(_token == msg.sender);
require(_token == address(token));
require(_from == address(0));
// Record deposit
totalTokensReceived += _value;
}
/**
* Handle incoming transactions
*
* @param _beneficiary Tokens are issued to this account
* @return Accepted ether amount
*/
function _handleTransaction(address _beneficiary) private only_when_not_updating at_stage(Stages.Deployed) returns (uint) {
uint weight = _getWeight(_beneficiary);
uint received = msg.value;
// Contribute for beneficiary
uint acceptedAmount = crowdsale.contributeFor.value(received)(_beneficiary);
// Record transaction
if (!hasRecord(_beneficiary)) {
records[_beneficiary] = Record(
weight, acceptedAmount, 0, recordIndex.push(_beneficiary) - 1);
totalWeight += weight;
} else {
Record storage r = records[_beneficiary];
r.contributed += acceptedAmount;
if (weight < r.weight) {
// Adjust weight
r.weight = weight;
totalWeight -= r.weight - weight;
}
}
// Record conribution
totalContributed += acceptedAmount;
return acceptedAmount;
}
/**
* Retrieve the combined drp balances from the drpu and drps tokens
*
* @param _account Token owner
* @return Weight, drp balance
*/
function _getWeight(address _account) private view returns (uint) {
return drpsToken.balanceOf(_account) + drpuToken.balanceOf(_account);
}
}
contract KATXDcorpMemberProxy is DcorpCrowdsaleProxy {
function KATXDcorpMemberProxy() public DcorpCrowdsaleProxy() {}
}
|
* IDcorpCrowdsaleProxy #created 23/11/2017 #author Frank Bonnet/
|
interface IDcorpCrowdsaleProxy {
function () public payable;
function contribute() public payable returns (uint);
function contributeFor(address _beneficiary) public payable returns (uint);
}
| 5,547,265 |
[
1,
734,
3850,
84,
39,
492,
2377,
5349,
3886,
2522,
10213,
19,
2499,
19,
31197,
2869,
478,
11500,
605,
265,
2758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5831,
1599,
3850,
84,
39,
492,
2377,
5349,
3886,
288,
203,
203,
565,
445,
1832,
1071,
8843,
429,
31,
203,
203,
203,
565,
445,
356,
887,
1435,
1071,
8843,
429,
1135,
261,
11890,
1769,
203,
203,
203,
565,
445,
356,
887,
1290,
12,
2867,
389,
70,
4009,
74,
14463,
814,
13,
1071,
8843,
429,
1135,
261,
11890,
1769,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
import "./Events.sol";
import "./Ownable.sol";
import "./Upgradeable.sol";
import "./UpgradeableMaster.sol";
/// @title Upgrade Gatekeeper Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract UpgradeGatekeeper is UpgradeEvents, Ownable {
using SafeMath for uint256;
/// @notice Array of addresses of upgradeable contracts managed by the gatekeeper
Upgradeable[] public managedContracts;
/// @notice Upgrade mode statuses
enum UpgradeStatus {
Idle,
NoticePeriod,
Preparation
}
UpgradeStatus public upgradeStatus;
/// @notice Notice period finish timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint public noticePeriodFinishTimestamp;
/// @notice Addresses of the next versions of the contracts to be upgraded (if element of this array is equal to zero address it means that appropriate upgradeable contract wouldn't be upgraded this time)
/// @dev Will be empty in case of not active upgrade mode
address[] public nextTargets;
/// @notice Version id of contracts
uint public versionId;
/// @notice Contract which defines notice period duration and allows finish upgrade during preparation of it
UpgradeableMaster public mainContract;
/// @notice Contract constructor
/// @param _mainContract Contract which defines notice period duration and allows finish upgrade during preparation of it
/// @dev Calls Ownable contract constructor
constructor(UpgradeableMaster _mainContract) Ownable(msg.sender) public {
mainContract = _mainContract;
versionId = 0;
}
/// @notice Adds a new upgradeable contract to the list of contracts managed by the gatekeeper
/// @param addr Address of upgradeable contract to add
function addUpgradeable(address addr) external {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.Idle, "apc11"); /// apc11 - upgradeable contract can't be added during upgrade
managedContracts.push(Upgradeable(addr));
emit NewUpgradable(versionId, addr);
}
/// @notice Starts upgrade (activates notice period)
/// @param newTargets New managed contracts targets (if element of this array is equal to zero address it means that appropriate upgradeable contract wouldn't be upgraded this time)
function startUpgrade(address[] calldata newTargets) external {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.Idle, "spu11"); // spu11 - unable to activate active upgrade mode
require(newTargets.length == managedContracts.length, "spu12"); // spu12 - number of new targets must be equal to the number of managed contracts
uint noticePeriod = mainContract.getNoticePeriod();
mainContract.upgradeNoticePeriodStarted();
upgradeStatus = UpgradeStatus.NoticePeriod;
noticePeriodFinishTimestamp = now.add(noticePeriod);
nextTargets = newTargets;
emit NoticePeriodStart(versionId, newTargets, noticePeriod);
}
/// @notice Cancels upgrade
function cancelUpgrade() external {
requireMaster(msg.sender);
require(upgradeStatus != UpgradeStatus.Idle, "cpu11"); // cpu11 - unable to cancel not active upgrade mode
mainContract.upgradeCanceled();
upgradeStatus = UpgradeStatus.Idle;
noticePeriodFinishTimestamp = 0;
delete nextTargets;
emit UpgradeCancel(versionId);
}
/// @notice Activates preparation status
/// @return Bool flag indicating that preparation status has been successfully activated
function startPreparation() external returns (bool) {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.NoticePeriod, "ugp11"); // ugp11 - unable to activate preparation status in case of not active notice period status
if (now >= noticePeriodFinishTimestamp) {
upgradeStatus = UpgradeStatus.Preparation;
mainContract.upgradePreparationStarted();
emit PreparationStart(versionId);
return true;
} else {
return false;
}
}
/// @notice Finishes upgrade
/// @param targetsUpgradeParameters New targets upgrade parameters per each upgradeable contract
function finishUpgrade(bytes[] calldata targetsUpgradeParameters) external {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.Preparation, "fpu11"); // fpu11 - unable to finish upgrade without preparation status active
require(targetsUpgradeParameters.length == managedContracts.length, "fpu12"); // fpu12 - number of new targets upgrade parameters must be equal to the number of managed contracts
require(mainContract.isReadyForUpgrade(), "fpu13"); // fpu13 - main contract is not ready for upgrade
mainContract.upgradeFinishes();
for (uint64 i = 0; i < managedContracts.length; i++) {
address newTarget = nextTargets[i];
if (newTarget != address(0)) {
managedContracts[i].upgradeTarget(newTarget, targetsUpgradeParameters[i]);
}
}
versionId++;
emit UpgradeComplete(versionId, nextTargets);
upgradeStatus = UpgradeStatus.Idle;
noticePeriodFinishTimestamp = 0;
delete nextTargets;
}
}
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;
}
}
pragma solidity ^0.5.0;
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title ZKSwap events
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface Events {
/// @notice Event emitted when a block is committed
event BlockCommit(uint32 indexed blockNumber);
/// @notice Event emitted when a block is verified
event BlockVerification(uint32 indexed blockNumber);
/// @notice Event emitted when a sequence of blocks is verified
event MultiblockVerification(uint32 indexed blockNumberFrom, uint32 indexed blockNumberTo);
/// @notice Event emitted when user send a transaction to withdraw her funds from onchain balance
event OnchainWithdrawal(
address indexed owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Event emitted when user send a transaction to deposit her funds
event OnchainDeposit(
address indexed sender,
uint16 indexed tokenId,
uint128 amount,
address indexed owner
);
/// @notice Event emitted when user send a transaction to deposit her NFT
event OnchainDepositNFT(
address indexed sender,
address indexed token,
uint256 tokenId,
address indexed owner
);
/// @notice Event emitted when user send a transaction to full exit her NFT
event OnchainFullExitNFT(
uint32 indexed accountId,
address indexed owner,
uint64 indexed globalId
);
event OnchainCreatePair(
uint16 indexed tokenAId,
uint16 indexed tokenBId,
uint16 indexed pairId,
address pair
);
/// @notice Event emitted when user sends a authentication fact (e.g. pub-key hash)
event FactAuth(
address indexed sender,
uint32 nonce,
bytes fact
);
/// @notice Event emitted when blocks are reverted
event BlocksRevert(
uint32 indexed totalBlocksVerified,
uint32 indexed totalBlocksCommitted
);
/// @notice Exodus mode entered event
event ExodusMode();
/// @notice New priority request event. Emitted when a request is placed into mapping
event NewPriorityRequest(
address sender,
uint64 serialId,
Operations.OpType opType,
bytes pubData,
bytes userData,
uint256 expirationBlock
);
/// @notice Deposit committed event.
event DepositCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Deposit committed event.
event DepositNFTCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint64 indexed globalId
);
/// @notice Full exit committed event.
event FullExitCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Full exit committed event.
event FullExitNFTCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint64 indexed globalId
);
/// @notice Pending withdrawals index range that were added in the verifyBlock operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsAdd(
uint32 queueStartIndex,
uint32 queueEndIndex
);
/// @notice Pending withdrawals index range that were executed in the completeWithdrawals operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsComplete(
uint32 queueStartIndex,
uint32 queueEndIndex
);
event CreatePairCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
uint16 tokenAId,
uint16 tokenBId,
uint16 indexed tokenPairId,
address pair
);
}
/// @title Upgrade events
/// @author Matter Labs
interface UpgradeEvents {
/// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts
event NewUpgradable(
uint indexed versionId,
address indexed upgradeable
);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint indexed versionId,
address[] newTargets,
uint noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(
uint indexed versionId
);
/// @notice Upgrade mode preparation status event
event PreparationStart(
uint indexed versionId
);
/// @notice Upgrade mode complete event
event UpgradeComplete(
uint indexed versionId,
address[] newTargets
);
}
pragma solidity ^0.5.0;
/// @title Ownable Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Ownable {
/// @notice Storage position of the masters address (keccak256('eip1967.proxy.admin') - 1)
bytes32 private constant masterPosition = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/// @notice Contract constructor
/// @dev Sets msg sender address as masters address
/// @param masterAddress Master address
constructor(address masterAddress) public {
setMaster(masterAddress);
}
/// @notice Check if specified address is master
/// @param _address Address to check
function requireMaster(address _address) internal view {
require(_address == getMaster(), "oro11"); // oro11 - only by master
}
/// @notice Returns contract masters address
/// @return Masters address
function getMaster() public view returns (address master) {
bytes32 position = masterPosition;
assembly {
master := sload(position)
}
}
/// @notice Sets new masters address
/// @param _newMaster New masters address
function setMaster(address _newMaster) internal {
bytes32 position = masterPosition;
assembly {
sstore(position, _newMaster)
}
}
/// @notice Transfer mastership of the contract to new master
/// @param _newMaster New masters address
function transferMastership(address _newMaster) external {
requireMaster(msg.sender);
require(_newMaster != address(0), "otp11"); // otp11 - new masters address can't be zero address
setMaster(_newMaster);
}
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface Upgradeable {
/// @notice Upgrades target of upgradeable contract
/// @param newTarget New target
/// @param newTargetInitializationParameters New target initialization parameters
function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint);
/// @notice Notifies contract that notice period started
function upgradeNoticePeriodStarted() external;
/// @notice Notifies contract that upgrade preparation status is activated
function upgradePreparationStarted() external;
/// @notice Notifies contract that upgrade canceled
function upgradeCanceled() external;
/// @notice Notifies contract that upgrade finishes
function upgradeFinishes() external;
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool);
}
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./Bytes.sol";
/// @title ZKSwap operations tools
library Operations {
// Circuit ops and their pubdata (chunks * bytes)
/// @notice ZKSwap circuit operation type
enum OpType {
Noop,
Deposit,
TransferToNew,
PartialExit,
_CloseAccount, // used for correct op id offset
Transfer,
FullExit,
ChangePubKey,
CreatePair,
AddLiquidity,
RemoveLiquidity,
Swap,
DepositNFT,
MintNFT,
TransferNFT,
TransferToNewNFT,
PartialExitNFT,
FullExitNFT,
ApproveNFT,
ExchangeNFT
}
// Byte lengths
uint8 constant TOKEN_BYTES = 2;
uint8 constant PUBKEY_BYTES = 32;
uint8 constant NONCE_BYTES = 4;
uint8 constant PUBKEY_HASH_BYTES = 20;
uint8 constant ADDRESS_BYTES = 20;
/// @notice Packed fee bytes lengths
uint8 constant FEE_BYTES = 2;
/// @notice ZKSwap account id bytes lengths
uint8 constant ACCOUNT_ID_BYTES = 4;
uint8 constant AMOUNT_BYTES = 16;
/// @notice Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
/// @notice nft uri bytes lengths
uint8 constant NFT_URI_BYTES = 32;
/// @notice nft seq id bytes lengths
uint8 constant NFT_SEQUENCE_ID_BYTES = 4;
/// @notice nft creator bytes lengths
uint8 constant NFT_CREATOR_ID_BYTES = 4;
/// @notice nft priority op id bytes lengths
uint8 constant NFT_PRIORITY_OP_ID_BYTES = 8;
/// @notice nft global id bytes lengths
uint8 constant NFT_GLOBAL_ID_BYTES = 8;
/// @notic withdraw nft use fee token id bytes lengths
uint8 constant NFT_FEE_TOKEN_ID = 1;
/// @notic fullexit nft success bytes lengths
uint8 constant NFT_SUCCESS = 1;
// Deposit pubdata
struct Deposit {
uint32 accountId;
uint16 tokenId;
uint128 amount;
address owner;
}
uint public constant PACKED_DEPOSIT_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES;
/// Deserialize deposit pubdata
function readDepositPubdata(bytes memory _data) internal pure
returns (Deposit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "rdp10"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
function writeDepositPubdata(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner // owner
);
}
/// @notice Check that deposit pubdata from request and block matches
function depositPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
// FullExit pubdata
struct FullExit {
uint32 accountId;
address owner;
uint16 tokenId;
uint128 amount;
}
uint public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES;
function readFullExitPubdata(bytes memory _data) internal pure
returns (FullExit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "rfp10"); // reading invalid full exit pubdata size
}
function writeFullExitPubdata(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
op.amount // amount
);
}
/// @notice Check that full exit pubdata from request and block matches
function fullExitPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// `amount` is ignored because it is present in block pubdata but not in priority queue
uint lhs = Bytes.trim(_lhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
uint rhs = Bytes.trim(_rhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
return lhs == rhs;
}
// PartialExit pubdata
struct PartialExit {
//uint32 accountId; -- present in pubdata, ignored at serialization
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
}
function readPartialExitPubdata(bytes memory _data, uint _offset) internal pure
returns (PartialExit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
}
function writePartialExitPubdata(PartialExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
bytes2(0), // fee (ignored) (update when FEE_BYTES is changed)
op.owner // owner
);
}
// ChangePubKey
struct ChangePubKey {
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
}
function readChangePubKeyPubdata(bytes memory _data, uint _offset) internal pure
returns (ChangePubKey memory parsed)
{
uint offset = _offset;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce
}
// Withdrawal nft data process
struct WithdrawNFTData {
bool valid; //confirm the necessity of this field
bool pendingWithdraw;
uint64 globalId;
uint32 creatorId;
uint32 seqId;
address target;
bytes32 uri;
}
function readWithdrawalData(bytes memory _data, uint _offset) internal pure
returns (bool isNFTWithdraw, uint128 amount, uint16 _tokenId, WithdrawNFTData memory parsed)
{
uint offset = _offset;
(offset, isNFTWithdraw) = Bytes.readBool(_data, offset);
(offset, parsed.pendingWithdraw) = Bytes.readBool(_data, offset);
(offset, parsed.target) = Bytes.readAddress(_data, offset); // target
if (isNFTWithdraw) {
(offset, parsed.globalId) = Bytes.readUInt64(_data, offset);
(offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creatorId
(offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId
(offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri
(offset, parsed.valid) = Bytes.readBool(_data, offset); // is withdraw valid
} else {
(offset, _tokenId) = Bytes.readUInt16(_data, offset);
(offset, amount) = Bytes.readUInt128(_data, offset); // withdraw erc20 or eth token amount
}
}
// CreatePair pubdata
struct CreatePair {
uint32 accountId;
uint16 tokenA;
uint16 tokenB;
uint16 tokenPair;
address pair;
}
uint public constant PACKED_CREATE_PAIR_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES;
function readCreatePairPubdata(bytes memory _data) internal pure
returns (CreatePair memory parsed)
{
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId
(offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId
(offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId
(offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId
require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size
}
function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenA, // tokenAId
op.tokenB, // tokenBId
op.tokenPair, // pairId
op.pair // pair account
);
}
/// @notice Check that create pair pubdata from request and block matches
function createPairPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
// DepositNFT pubdata
struct DepositNFT {
uint64 globalId;
uint32 creatorId;
uint32 seqId;
bytes32 uri;
address owner;
uint32 accountId;
}
uint public constant PACKED_DEPOSIT_NFT_PUBDATA_BYTES = ACCOUNT_ID_BYTES +
NFT_GLOBAL_ID_BYTES + NFT_CREATOR_ID_BYTES + NFT_SEQUENCE_ID_BYTES +
NFT_URI_BYTES + ADDRESS_BYTES ;
/// Deserialize deposit nft pubdata
function readDepositNFTPubdata(bytes memory _data) internal pure
returns (DepositNFT memory parsed) {
uint offset = 0;
(offset, parsed.globalId) = Bytes.readUInt64(_data, offset); // globalId
(offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creatorId
(offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId
(offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
require(offset == PACKED_DEPOSIT_NFT_PUBDATA_BYTES, "rdnp10"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
function writeDepositNFTPubdata(DepositNFT memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
op.globalId,
op.creatorId,
op.seqId,
op.uri,
op.owner, // owner
bytes4(0)
);
}
/// @notice Check that deposit nft pubdata from request and block matches
function depositNFTPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
uint offset = 0;
uint64 globalId;
(offset, globalId) = Bytes.readUInt64(_lhs, offset); // globalId
if (globalId == 0){
bytes memory lhs_trimmed = Bytes.slice(_lhs, NFT_GLOBAL_ID_BYTES, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES - NFT_GLOBAL_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, NFT_GLOBAL_ID_BYTES, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES - NFT_GLOBAL_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}else{
bytes memory lhs_trimmed = Bytes.slice(_lhs, 0, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, 0, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
}
// FullExitNFT pubdata
struct FullExitNFT {
uint32 accountId;
uint64 globalId;
uint32 creatorId;
uint32 seqId;
bytes32 uri;
address owner;
uint8 success;
}
uint public constant PACKED_FULL_EXIT_NFT_PUBDATA_BYTES = ACCOUNT_ID_BYTES +
NFT_GLOBAL_ID_BYTES + NFT_CREATOR_ID_BYTES +
NFT_SEQUENCE_ID_BYTES + NFT_URI_BYTES + ADDRESS_BYTES + NFT_SUCCESS;
function readFullExitNFTPubdata(bytes memory _data) internal pure returns (FullExitNFT memory parsed) {
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.globalId) = Bytes.readUInt64(_data, offset); // globalId
(offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creator
(offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId
(offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.success) = Bytes.readUint8(_data, offset); // success
require(offset == PACKED_FULL_EXIT_NFT_PUBDATA_BYTES, "rfnp10"); // reading invalid deposit pubdata size
}
function writeFullExitNFTPubdata(FullExitNFT memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
op.accountId,
op.globalId, // nft id in layer2
op.creatorId,
op.seqId,
op.uri,
op.owner,
op.success
);
}
/// @notice Check that full exit pubdata from request and block matches
/// TODO check it
function fullExitNFTPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
bytes memory lhs_trimmed_1 = Bytes.slice(_lhs, 0, ACCOUNT_ID_BYTES + NFT_GLOBAL_ID_BYTES);
bytes memory rhs_trimmed_1 = Bytes.slice(_rhs, 0, ACCOUNT_ID_BYTES + NFT_GLOBAL_ID_BYTES);
bytes memory lhs_trimmed_2 = Bytes.slice(_lhs, PACKED_FULL_EXIT_NFT_PUBDATA_BYTES - ADDRESS_BYTES - NFT_SUCCESS, ADDRESS_BYTES);
bytes memory rhs_trimmed_2 = Bytes.slice(_rhs, PACKED_FULL_EXIT_NFT_PUBDATA_BYTES - ADDRESS_BYTES - NFT_SUCCESS, ADDRESS_BYTES);
return keccak256(lhs_trimmed_1) == keccak256(rhs_trimmed_1) && keccak256(lhs_trimmed_2) == keccak256(rhs_trimmed_2);
}
// PartialExitNFT pubdata
struct PartialExitNFT {
// uint32 accountId;
uint64 globalId;
uint32 creatorId;
uint32 seqId;
bytes32 uri;
address owner;
}
function readPartialExitNFTPubdata(bytes memory _data, uint _offset) internal pure
returns (PartialExitNFT memory parsed) {
uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored)
(offset, parsed.globalId) = Bytes.readUInt64(_data, offset); // globalId
(offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creatorId
(offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId
(offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
}
function writePartialExitNFTPubdata(PartialExitNFT memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.globalId, // tokenId in layer2
bytes4(0),
bytes4(0),
bytes32(0),
op.owner
);
}
}
pragma solidity ^0.5.0;
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "bt211");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint data = self << ((32 - byteLength) * 8);
assembly {
mstore(add(bts, /*BYTES_HEADER_SIZE*/32), data)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "bta11");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "btb20");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "btu02");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "btu03");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "btu04");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x8)
function bytesToUInt64(bytes memory _bytes, uint256 _start) internal pure returns (uint64 r) {
uint256 offset = _start + 0x8;
require(_bytes.length >= offset, "btu08");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "btu16");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "btu20");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "btb32");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length), "bse11"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
// TODO: Review this thoroughly.
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return new_offset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(bytes memory _data, uint _offset, uint _length) internal pure returns (uint new_offset, bytes memory data) {
data = slice(_data, _offset, _length);
new_offset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bool r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint8 r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint16 r) {
new_offset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint32 r) {
new_offset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 8)
function readUInt64(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint64 r) {
new_offset = _offset + 8;
r = bytesToUInt64(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint128 r) {
new_offset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint160 r) {
new_offset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint _offset) internal pure returns (uint new_offset, address r) {
new_offset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes20 r) {
new_offset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes32 r) {
new_offset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
// Helper function for hex conversion.
function halfByteToHex(byte _byte) internal pure returns (byte _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130)))
mstore(add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130)))
}
}
return outStringBytes;
}
/// Trim bytes into single word
function trim(bytes memory _data, uint _new_length) internal pure returns (uint r) {
require(_new_length <= 0x20, "trm10"); // new_length is longer than word
require(_data.length >= _new_length, "trm11"); // data is to short
uint a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _new_length) * 8);
}
}
|
Deserialize deposit pubdata NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
|
function readDepositPubdata(bytes memory _data) internal pure
returns (Deposit memory parsed)
{
uint offset = 0;
}
| 287,820 |
[
1,
20423,
443,
1724,
5634,
892,
5219,
30,
1915,
353,
1158,
866,
716,
2190,
8453,
854,
1967,
487,
6810,
261,
77,
18,
73,
18,
14275,
67,
13718,
3631,
2917,
309,
3323,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
855,
758,
1724,
9581,
892,
12,
3890,
3778,
389,
892,
13,
2713,
16618,
203,
3639,
1135,
261,
758,
1724,
3778,
2707,
13,
203,
565,
288,
203,
3639,
2254,
1384,
273,
374,
31,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/5/0x5DDb48141CBaDf6AC963c1e8A2A4fa14Ea51a039/sources/Crowdsale.sol
|
* @dev Must be called after crowdsale ends, to do some extra finalization work. Calls the contracts finalization function./GP: Check if the amount weiRaised() not reached, if the funds are able to be refunded
|
function finalize() public {
require(!finalized, "Crowdsale: already finalized");
require(hasClosed(), "Crowdsale: not closed");
uint256 unsoldTokens = IERC20(token).balanceOf(address(this));
if(goalReached()) {
_forwardFunds();
uint256 soldTokens = _getTokenAmount(weiRaised);
unsoldTokens = unsoldTokens.sub(soldTokens);
}
if(unsoldTokens > 0) {
_deliverTokens(wallet, unsoldTokens);
}
finalized = true;
emit CrowdsaleFinalized();
}
| 16,894,563 |
[
1,
10136,
506,
2566,
1839,
276,
492,
2377,
5349,
3930,
16,
358,
741,
2690,
2870,
727,
1588,
1440,
18,
23665,
326,
20092,
727,
1588,
445,
18,
19,
9681,
30,
2073,
309,
326,
3844,
732,
77,
12649,
5918,
1435,
486,
8675,
16,
309,
326,
284,
19156,
854,
7752,
358,
506,
1278,
12254,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
12409,
1435,
1071,
288,
203,
3639,
2583,
12,
5,
6385,
1235,
16,
315,
39,
492,
2377,
5349,
30,
1818,
727,
1235,
8863,
203,
3639,
2583,
12,
5332,
7395,
9334,
315,
39,
492,
2377,
5349,
30,
486,
4375,
8863,
203,
3639,
2254,
5034,
16804,
1673,
5157,
273,
467,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
12,
27354,
23646,
10756,
288,
203,
5411,
389,
11565,
42,
19156,
5621,
203,
5411,
2254,
5034,
272,
1673,
5157,
273,
389,
588,
1345,
6275,
12,
1814,
77,
12649,
5918,
1769,
203,
5411,
16804,
1673,
5157,
273,
16804,
1673,
5157,
18,
1717,
12,
87,
1673,
5157,
1769,
203,
3639,
289,
203,
203,
3639,
309,
12,
27595,
1673,
5157,
405,
374,
13,
288,
203,
5411,
389,
26672,
5157,
12,
19177,
16,
16804,
1673,
5157,
1769,
203,
3639,
289,
203,
203,
3639,
727,
1235,
273,
638,
31,
203,
203,
3639,
3626,
385,
492,
2377,
5349,
7951,
1235,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/ErrorReporter.sol
pragma solidity 0.4.24;
contract ErrorReporter {
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
*/
event Failure(uint256 error, uint256 info, uint256 detail);
enum Error {
NO_ERROR,
OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event
UNAUTHORIZED,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW,
DIVISION_BY_ZERO,
BAD_INPUT,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_TRANSFER_FAILED,
MARKET_NOT_SUPPORTED,
SUPPLY_RATE_CALCULATION_FAILED,
BORROW_RATE_CALCULATION_FAILED,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_OUT_FAILED,
INSUFFICIENT_LIQUIDITY,
INSUFFICIENT_BALANCE,
INVALID_COLLATERAL_RATIO,
MISSING_ASSET_PRICE,
EQUITY_INSUFFICIENT_BALANCE,
INVALID_CLOSE_AMOUNT_REQUESTED,
ASSET_NOT_PRICED,
INVALID_LIQUIDATION_DISCOUNT,
INVALID_COMBINED_RISK_PARAMETERS,
ZERO_ORACLE_ADDRESS,
CONTRACT_PAUSED,
KYC_ADMIN_CHECK_FAILED,
KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
KYC_CUSTOMER_VERIFICATION_CHECK_FAILED,
LIQUIDATOR_CHECK_FAILED,
LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
SET_WETH_ADDRESS_ADMIN_CHECK_FAILED,
WETH_ADDRESS_NOT_SET_ERROR,
ETHER_AMOUNT_MISMATCH_ERROR
}
/**
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED,
BORROW_ACCOUNT_SHORTFALL_PRESENT,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_AMOUNT_LIQUIDITY_SHORTFALL,
BORROW_AMOUNT_VALUE_CALCULATION_FAILED,
BORROW_CONTRACT_PAUSED,
BORROW_MARKET_NOT_SUPPORTED,
BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED,
BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED,
BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED,
BORROW_ORIGINATION_FEE_CALCULATION_FAILED,
BORROW_TRANSFER_OUT_FAILED,
EQUITY_WITHDRAWAL_AMOUNT_VALIDATION,
EQUITY_WITHDRAWAL_CALCULATE_EQUITY,
EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK,
EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED,
LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED,
LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET,
LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET,
LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED,
LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED,
LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH,
LIQUIDATE_CONTRACT_PAUSED,
LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED,
LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET,
LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET,
LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET,
LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET,
LIQUIDATE_FETCH_ASSET_PRICE_FAILED,
LIQUIDATE_TRANSFER_IN_FAILED,
LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_CONTRACT_PAUSED,
REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED,
REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_ASSET_PRICE_CHECK_ORACLE,
SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_ORACLE_OWNER_CHECK,
SET_ORIGINATION_FEE_OWNER_CHECK,
SET_PAUSED_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RISK_PARAMETERS_OWNER_CHECK,
SET_RISK_PARAMETERS_VALIDATION,
SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED,
SUPPLY_CONTRACT_PAUSED,
SUPPLY_MARKET_NOT_SUPPORTED,
SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED,
SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED,
SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
SUPPLY_TRANSFER_IN_FAILED,
SUPPLY_TRANSFER_IN_NOT_POSSIBLE,
SUPPORT_MARKET_FETCH_PRICE_FAILED,
SUPPORT_MARKET_OWNER_CHECK,
SUPPORT_MARKET_PRICE_CHECK,
SUSPEND_MARKET_OWNER_CHECK,
WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED,
WITHDRAW_ACCOUNT_SHORTFALL_PRESENT,
WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL,
WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED,
WITHDRAW_CAPACITY_CALCULATION_FAILED,
WITHDRAW_CONTRACT_PAUSED,
WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED,
WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED,
WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
WITHDRAW_TRANSFER_OUT_FAILED,
WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE,
KYC_ADMIN_CHECK_FAILED,
KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
KYC_CUSTOMER_VERIFICATION_CHECK_FAILED,
LIQUIDATOR_CHECK_FAILED,
LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
SET_WETH_ADDRESS_ADMIN_CHECK_FAILED,
WETH_ADDRESS_NOT_SET_ERROR,
SEND_ETHER_ADMIN_CHECK_FAILED,
ETHER_AMOUNT_MISMATCH_ERROR
}
/**
* @dev use this when reporting a known error from the Alkemi Earn Verified or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(FailureInfo info, uint256 opaqueError)
internal
returns (uint256)
{
emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError);
return uint256(Error.OPAQUE_ERROR);
}
}
// File: contracts/CarefulMath.sol
// Cloned from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol -> Commit id: 24a0bc2
// and added custom functions related to Alkemi
pragma solidity 0.4.24;
/**
* @title Careful Math
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol
*/
contract CarefulMath is ErrorReporter {
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (a == 0) {
return (Error.NO_ERROR, 0);
}
uint256 c = a * b;
if (c / a != b) {
return (Error.INTEGER_OVERFLOW, 0);
} else {
return (Error.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (b == 0) {
return (Error.DIVISION_BY_ZERO, 0);
}
return (Error.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (b <= a) {
return (Error.NO_ERROR, a - b);
} else {
return (Error.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (Error, uint256) {
uint256 c = a + b;
if (c >= a) {
return (Error.NO_ERROR, c);
} else {
return (Error.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSub(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (Error, uint256) {
(Error err0, uint256 sum) = add(a, b);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return sub(sum, c);
}
}
// File: contracts/Exponential.sol
// Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a
pragma solidity 0.4.24;
contract Exponential is ErrorReporter, CarefulMath {
// Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables
// the optimizer MAY replace the expression 10**18 with its calculated value.
uint256 constant expScale = 10**18;
uint256 constant halfExpScale = expScale / 2;
struct Exp {
uint256 mantissa;
}
uint256 constant mantissaOne = 10**18;
// Though unused, the below variable cannot be deleted as it will hinder upgradeability
// Will be cleared during the next compiler version upgrade
uint256 constant mantissaOneTenth = 10**17;
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint256 num, uint256 denom)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 scaledNumerator) = mul(num, expScale);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(Error err1, uint256 rational) = div(scaledNumerator, denom);
if (err1 != Error.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error error, uint256 result) = add(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error error, uint256 result) = sub(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint256 scalar)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint256 scalar)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint256 scalar, Exp divisor)
internal
pure
returns (Error, Exp memory)
{
/*
We are doing this as:
getExp(mul(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(Error err0, uint256 numerator) = mul(expScale, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(Error err1, uint256 doubleScaledProductWithHalfScale) = add(
halfExpScale,
doubleScaledProduct
);
if (err1 != Error.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(Error err2, uint256 product) = div(
doubleScaledProductWithHalfScale,
expScale
);
// The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == Error.NO_ERROR);
return (Error.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if first Exp is greater than second Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
}
// File: contracts/InterestRateModel.sol
pragma solidity 0.4.24;
/**
* @title InterestRateModel Interface
* @notice Any interest rate model should derive from this contract.
* @dev These functions are specifically not marked `pure` as implementations of this
* contract may read from storage variables.
*/
contract InterestRateModel {
/**
* @notice Gets the current supply interest rate based on the given asset, total cash and total borrows
* @dev The return value should be scaled by 1e18, thus a return value of
* `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*.
* @param asset The asset to get the interest rate of
* @param cash The total cash of the asset in the market
* @param borrows The total borrows of the asset in the market
* @return Success or failure and the supply interest rate per block scaled by 10e18
*/
function getSupplyRate(
address asset,
uint256 cash,
uint256 borrows
) public view returns (uint256, uint256);
/**
* @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows
* @dev The return value should be scaled by 1e18, thus a return value of
* `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*.
* @param asset The asset to get the interest rate of
* @param cash The total cash of the asset in the market
* @param borrows The total borrows of the asset in the market
* @return Success or failure and the borrow interest rate per block scaled by 10e18
*/
function getBorrowRate(
address asset,
uint256 cash,
uint256 borrows
) public view returns (uint256, uint256);
}
// File: contracts/EIP20Interface.sol
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
pragma solidity 0.4.24;
contract EIP20Interface {
/* 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;
// token decimals
uint8 public decimals; // maximum is 18 decimals
/**
* @param _owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address _owner) public view returns (uint256 balance);
/**
* @notice send `_value` token to `_to` from `msg.sender`
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transfer(address _to, uint256 _value)
public
returns (bool success);
/**
* @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool success);
/**
* @notice `msg.sender` approves `_spender` to spend `_value` tokens
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return Whether the approval was successful or not
*/
function approve(address _spender, uint256 _value)
public
returns (bool success);
/**
* @param _owner The address of the account owning tokens
* @param _spender The address of the account able to transfer the tokens
* @return Amount of remaining tokens allowed to spent
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
}
// File: contracts/EIP20NonStandardInterface.sol
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
pragma solidity 0.4.24;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
contract EIP20NonStandardInterface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
// total amount of tokens
uint256 public totalSupply;
/**
* @param _owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address _owner) public view returns (uint256 balance);
/**
* !!!!!!!!!!!!!!
* !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
* !!!!!!!!!!!!!!
*
* @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;
/**
*
* !!!!!!!!!!!!!!
* !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
* !!!!!!!!!!!!!!
*
* @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;
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value)
public
returns (bool success);
/**
* @param _owner The address of the account owning tokens
* @param _spender The address of the account able to transfer the tokens
* @return Amount of remaining tokens allowed to spent
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
}
// File: contracts/SafeToken.sol
pragma solidity 0.4.24;
contract SafeToken is ErrorReporter {
/**
* @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and
* whether or not `from` has a balance of at least `amount`. Does NOT do a transfer.
*/
function checkTransferIn(
address asset,
address from,
uint256 amount
) internal view returns (Error) {
EIP20Interface token = EIP20Interface(asset);
if (token.allowance(from, address(this)) < amount) {
return Error.TOKEN_INSUFFICIENT_ALLOWANCE;
}
if (token.balanceOf(from) < amount) {
return Error.TOKEN_INSUFFICIENT_BALANCE;
}
return Error.NO_ERROR;
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory
* error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to
* insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call,
* and it returned Error.NO_ERROR, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(
address asset,
address from,
uint256 amount
) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(asset);
bool result;
token.transferFrom(from, address(this), amount);
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Error.TOKEN_TRANSFER_FAILED;
}
return Error.NO_ERROR;
}
/**
* @dev Checks balance of this contract in asset
*/
function getCash(address asset) internal view returns (uint256) {
EIP20Interface token = EIP20Interface(asset);
return token.balanceOf(address(this));
}
/**
* @dev Checks balance of `from` in `asset`
*/
function getBalanceOf(address asset, address from)
internal
view
returns (uint256)
{
EIP20Interface token = EIP20Interface(asset);
return token.balanceOf(from);
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(
address asset,
address to,
uint256 amount
) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(asset);
bool result;
token.transfer(to, amount);
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 {
// This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Error.TOKEN_TRANSFER_OUT_FAILED;
}
return Error.NO_ERROR;
}
function doApprove(
address asset,
address to,
uint256 amount
) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(asset);
bool result;
token.approve(to, amount);
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 {
// This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Error.TOKEN_TRANSFER_OUT_FAILED;
}
return Error.NO_ERROR;
}
}
// File: contracts/AggregatorV3Interface.sol
pragma solidity 0.4.24;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File: contracts/ChainLink.sol
pragma solidity 0.4.24;
contract ChainLink {
mapping(address => AggregatorV3Interface) internal priceContractMapping;
address public admin;
bool public paused = false;
address public wethAddressVerified;
address public wethAddressPublic;
AggregatorV3Interface public USDETHPriceFeed;
uint256 constant expScale = 10**18;
uint8 constant eighteen = 18;
/**
* Sets the admin
* Add assets and set Weth Address using their own functions
*/
constructor() public {
admin = msg.sender;
}
/**
* Modifier to restrict functions only by admins
*/
modifier onlyAdmin() {
require(
msg.sender == admin,
"Only the Admin can perform this operation"
);
_;
}
/**
* Event declarations for all the operations of this contract
*/
event assetAdded(
address indexed assetAddress,
address indexed priceFeedContract
);
event assetRemoved(address indexed assetAddress);
event adminChanged(address indexed oldAdmin, address indexed newAdmin);
event verifiedWethAddressSet(address indexed wethAddressVerified);
event publicWethAddressSet(address indexed wethAddressPublic);
event contractPausedOrUnpaused(bool currentStatus);
/**
* Allows admin to add a new asset for price tracking
*/
function addAsset(address assetAddress, address priceFeedContract)
public
onlyAdmin
{
require(
assetAddress != address(0) && priceFeedContract != address(0),
"Asset or Price Feed address cannot be 0x00"
);
priceContractMapping[assetAddress] = AggregatorV3Interface(
priceFeedContract
);
emit assetAdded(assetAddress, priceFeedContract);
}
/**
* Allows admin to remove an existing asset from price tracking
*/
function removeAsset(address assetAddress) public onlyAdmin {
require(
assetAddress != address(0),
"Asset or Price Feed address cannot be 0x00"
);
priceContractMapping[assetAddress] = AggregatorV3Interface(address(0));
emit assetRemoved(assetAddress);
}
/**
* Allows admin to change the admin of the contract
*/
function changeAdmin(address newAdmin) public onlyAdmin {
require(
newAdmin != address(0),
"Asset or Price Feed address cannot be 0x00"
);
emit adminChanged(admin, newAdmin);
admin = newAdmin;
}
/**
* Allows admin to set the weth address for verified protocol
*/
function setWethAddressVerified(address _wethAddressVerified) public onlyAdmin {
require(_wethAddressVerified != address(0), "WETH address cannot be 0x00");
wethAddressVerified = _wethAddressVerified;
emit verifiedWethAddressSet(_wethAddressVerified);
}
/**
* Allows admin to set the weth address for public protocol
*/
function setWethAddressPublic(address _wethAddressPublic) public onlyAdmin {
require(_wethAddressPublic != address(0), "WETH address cannot be 0x00");
wethAddressPublic = _wethAddressPublic;
emit publicWethAddressSet(_wethAddressPublic);
}
/**
* Allows admin to pause and unpause the contract
*/
function togglePause() public onlyAdmin {
if (paused) {
paused = false;
emit contractPausedOrUnpaused(false);
} else {
paused = true;
emit contractPausedOrUnpaused(true);
}
}
/**
* Returns the latest price scaled to 1e18 scale
*/
function getAssetPrice(address asset) public view returns (uint256, uint8) {
// Return 1 * 10^18 for WETH, otherwise return actual price
if (!paused) {
if ( asset == wethAddressVerified || asset == wethAddressPublic ){
return (expScale, eighteen);
}
}
// Capture the decimals in the ERC20 token
uint8 assetDecimals = EIP20Interface(asset).decimals();
if (!paused && priceContractMapping[asset] != address(0)) {
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = priceContractMapping[asset].latestRoundData();
startedAt; // To avoid compiler warnings for unused local variable
// If the price data was not refreshed for the past 1 day, prices are considered stale
// This threshold is the maximum Chainlink uses to update the price feeds
require(timeStamp > (now - 86500 seconds), "Stale data");
// If answeredInRound is less than roundID, prices are considered stale
require(answeredInRound >= roundID, "Stale Data");
if (price > 0) {
// Magnify the result based on decimals
return (uint256(price), assetDecimals);
} else {
return (0, assetDecimals);
}
} else {
return (0, assetDecimals);
}
}
function() public payable {
require(
msg.sender.send(msg.value),
"Fallback function initiated but refund failed"
);
}
}
// File: contracts/AlkemiWETH.sol
// Cloned from https://github.com/gnosis/canonical-weth/blob/master/contracts/WETH9.sol -> Commit id: 0dd1ea3
pragma solidity 0.4.24;
contract AlkemiWETH {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function() public payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
emit Transfer(address(0), msg.sender, msg.value);
}
function withdraw(address user, uint256 wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
user.transfer(wad);
emit Withdrawal(msg.sender, wad);
emit Transfer(msg.sender, address(0), wad);
}
function totalSupply() public view returns (uint256) {
return address(this).balance;
}
function approve(address guy, uint256 wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint256 wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(
address src,
address dst,
uint256 wad
) public returns (bool) {
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
// File: contracts/RewardControlInterface.sol
pragma solidity 0.4.24;
contract RewardControlInterface {
/**
* @notice Refresh ALK supply index for the specified market and supplier
* @param market The market whose supply index to update
* @param supplier The address of the supplier to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
) external;
/**
* @notice Refresh ALK borrow index for the specified market and borrower
* @param market The market whose borrow index to update
* @param borrower The address of the borrower to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function refreshAlkBorrowIndex(
address market,
address borrower,
bool isVerified
) external;
/**
* @notice Claim all the ALK accrued by holder in all markets
* @param holder The address to claim ALK for
*/
function claimAlk(address holder) external;
/**
* @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only
* @param holder The address to claim ALK for
* @param market The address of the market to refresh the indexes for
* @param isVerified Verified / Public protocol
*/
function claimAlk(
address holder,
address market,
bool isVerified
) external;
}
// File: contracts/AlkemiEarnVerified.sol
pragma solidity 0.4.24;
contract AlkemiEarnVerified is Exponential, SafeToken {
uint256 internal initialInterestIndex;
uint256 internal defaultOriginationFee;
uint256 internal defaultCollateralRatio;
uint256 internal defaultLiquidationDiscount;
// minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability
// Values cannot be assigned directly as OpenZeppelin upgrades do not support the same
// Values can only be assigned using initializer() below
// However, there is no way to change the below values using any functions and hence they act as constants
uint256 public minimumCollateralRatioMantissa;
uint256 public maximumLiquidationDiscountMantissa;
bool private initializationDone; // To make sure initializer is called only once
/**
* @notice `AlkemiEarnVerified` is the core contract
* @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies
* @notice Hence this contract has an 'initializer' in place of a 'constructor'
* @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344
* @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade
*/
function initializer() public {
if (initializationDone == false) {
initializationDone = true;
admin = msg.sender;
initialInterestIndex = 10**18;
minimumCollateralRatioMantissa = 11 * (10**17); // 1.1
maximumLiquidationDiscountMantissa = (10**17); // 0.1
collateralRatio = Exp({mantissa: 125 * (10**16)});
originationFee = Exp({mantissa: (10**15)});
liquidationDiscount = Exp({mantissa: (10**17)});
// oracle must be configured via _adminFunctions
}
}
/**
* @notice Do not pay directly into AlkemiEarnVerified, please use `supply`.
*/
function() public payable {
revert();
}
/**
* @dev pending Administrator for this contract.
*/
address public pendingAdmin;
/**
* @dev Administrator for this contract. Initially set in constructor, but can
* be changed by the admin itself.
*/
address public admin;
/**
* @dev Managers for this contract with limited permissions. Can
* be changed by the admin.
* Though unused, the below variable cannot be deleted as it will hinder upgradeability
* Will be cleared during the next compiler version upgrade
*/
mapping(address => bool) public managers;
/**
* @dev Account allowed to set oracle prices for this contract. Initially set
* in constructor, but can be changed by the admin.
*/
address private oracle;
/**
* @dev Modifier to check if the caller is the admin of the contract
*/
modifier onlyOwner() {
require(msg.sender == admin, "Owner check failed");
_;
}
/**
* @dev Modifier to check if the caller is KYC verified
*/
modifier onlyCustomerWithKYC() {
require(
customersWithKYC[msg.sender],
"KYC_CUSTOMER_VERIFICATION_CHECK_FAILED"
);
_;
}
/**
* @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin.
*/
ChainLink public priceOracle;
/**
* @dev Container for customer balance information written to storage.
*
* struct Balance {
* principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action
* interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action
* }
*/
struct Balance {
uint256 principal;
uint256 interestIndex;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for supplies
*/
mapping(address => mapping(address => Balance)) public supplyBalances;
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for borrows
*/
mapping(address => mapping(address => Balance)) public borrowBalances;
/**
* @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key
*
* struct Market {
* isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets)
* blockNumber = when the other values in this struct were calculated
* interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset
* totalSupply = total amount of this asset supplied (in asset wei)
* supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18
* supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket
* totalBorrows = total amount of this asset borrowed (in asset wei)
* borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18
* borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket
* }
*/
struct Market {
bool isSupported;
uint256 blockNumber;
InterestRateModel interestRateModel;
uint256 totalSupply;
uint256 supplyRateMantissa;
uint256 supplyIndex;
uint256 totalBorrows;
uint256 borrowRateMantissa;
uint256 borrowIndex;
}
/**
* @dev wethAddress to hold the WETH token contract address
* set using setWethAddress function
*/
address private wethAddress;
/**
* @dev Initiates the contract for supply and withdraw Ether and conversion to WETH
*/
AlkemiWETH public WETHContract;
/**
* @dev map: assetAddress -> Market
*/
mapping(address => Market) public markets;
/**
* @dev list: collateralMarkets
*/
address[] public collateralMarkets;
/**
* @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This
* is initially set in the constructor, but can be changed by the admin.
*/
Exp public collateralRatio;
/**
* @dev originationFee for new borrows.
*
*/
Exp public originationFee;
/**
* @dev liquidationDiscount for collateral when liquidating borrows
*
*/
Exp public liquidationDiscount;
/**
* @dev flag for whether or not contract is paused
*
*/
bool public paused;
/**
* @dev Mapping to identify the list of KYC Admins
*/
mapping(address => bool) public KYCAdmins;
/**
* @dev Mapping to identify the list of customers with verified KYC
*/
mapping(address => bool) public customersWithKYC;
/**
* @dev Mapping to identify the list of customers with Liquidator roles
*/
mapping(address => bool) public liquidators;
/**
* The `SupplyLocalVars` struct is used internally in the `supply` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct SupplyLocalVars {
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
}
/**
* The `WithdrawLocalVars` struct is used internally in the `withdraw` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct WithdrawLocalVars {
uint256 withdrawAmount;
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
uint256 withdrawCapacity;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfWithdrawal;
}
// The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function.
struct AccountValueLocalVars {
address assetAddress;
uint256 collateralMarketsLength;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Exp borrowTotalValue;
Exp sumBorrows;
Exp supplyTotalValue;
Exp sumSupplies;
}
// The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function.
struct PayBorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 repayAmount;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
}
// The `BorrowLocalVars` struct is used internally in the `borrow` function.
struct BorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 borrowAmountWithFee;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfBorrowAmountWithFee;
}
// The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function.
struct LiquidateLocalVars {
// we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.`
address targetAccount;
address assetBorrow;
address liquidator;
address assetCollateral;
// borrow index and supply index are global to the asset, not specific to the user
uint256 newBorrowIndex_UnderwaterAsset;
uint256 newSupplyIndex_UnderwaterAsset;
uint256 newBorrowIndex_CollateralAsset;
uint256 newSupplyIndex_CollateralAsset;
// the target borrow's full balance with accumulated interest
uint256 currentBorrowBalance_TargetUnderwaterAsset;
// currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation
uint256 updatedBorrowBalance_TargetUnderwaterAsset;
uint256 newTotalBorrows_ProtocolUnderwaterAsset;
uint256 startingBorrowBalance_TargetUnderwaterAsset;
uint256 startingSupplyBalance_TargetCollateralAsset;
uint256 startingSupplyBalance_LiquidatorCollateralAsset;
uint256 currentSupplyBalance_TargetCollateralAsset;
uint256 updatedSupplyBalance_TargetCollateralAsset;
// If liquidator already has a balance of collateralAsset, we will accumulate
// interest on it before transferring seized collateral from the borrower.
uint256 currentSupplyBalance_LiquidatorCollateralAsset;
// This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any)
// plus the amount seized from the borrower.
uint256 updatedSupplyBalance_LiquidatorCollateralAsset;
uint256 newTotalSupply_ProtocolCollateralAsset;
uint256 currentCash_ProtocolUnderwaterAsset;
uint256 updatedCash_ProtocolUnderwaterAsset;
// cash does not change for collateral asset
uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset;
uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset;
// Why no variables for the interest rates for the collateral asset?
// We don't need to calculate new rates for the collateral asset since neither cash nor borrows change
uint256 discountedRepayToEvenAmount;
//[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral)
uint256 discountedBorrowDenominatedCollateral;
uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset;
uint256 closeBorrowAmount_TargetUnderwaterAsset;
uint256 seizeSupplyAmount_TargetCollateralAsset;
uint256 reimburseAmount;
Exp collateralPrice;
Exp underwaterAssetPrice;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows
*/
mapping(address => mapping(address => uint256))
public originationFeeBalance;
/**
* @dev Reward Control Contract address
*/
RewardControlInterface public rewardControl;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
/// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 public _guardCounter;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one `nonReentrant` function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and an `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
/**
* @dev Events to notify the frontend of all the functions below
*/
event LiquidatorChanged(address indexed Liquidator, bool newStatus);
/**
* @dev emitted when a supply is received
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyReceived(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a supply is withdrawn
* Note: startingBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyWithdrawn(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a new borrow is taken
* Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change
*/
event BorrowTaken(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 borrowAmountWithFee,
uint256 newBalance
);
/**
* @dev emitted when a borrow is repaid
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event BorrowRepaid(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a borrow is liquidated
* targetAccount = user whose borrow was liquidated
* assetBorrow = asset borrowed
* borrowBalanceBefore = borrowBalance as most recently stored before the liquidation
* borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountRepaid = amount of borrow repaid
* liquidator = account requesting the liquidation
* assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan
* borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid)
* collateralBalanceBefore = collateral balance as most recently stored before the liquidation
* collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountSeized = amount of collateral seized by liquidator
* collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized)
* assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3
*/
event BorrowLiquidated(
address indexed targetAccount,
address assetBorrow,
uint256 borrowBalanceAccumulated,
uint256 amountRepaid,
address indexed liquidator,
address assetCollateral,
uint256 amountSeized
);
/**
* @dev emitted when admin withdraws equity
* Note that `equityAvailableBefore` indicates equity before `amount` was removed.
*/
event EquityWithdrawn(
address indexed asset,
uint256 equityAvailableBefore,
uint256 amount,
address indexed owner
);
/**
* @dev KYC Integration
*/
/**
* @dev Events to notify the frontend of all the functions below
*/
event KYCAdminChanged(address indexed KYCAdmin, bool newStatus);
event KYCCustomerChanged(address indexed KYCCustomer, bool newStatus);
/**
* @dev Function for use by the admin of the contract to add or remove KYC Admins
*/
function _changeKYCAdmin(address KYCAdmin, bool newStatus)
public
onlyOwner
{
KYCAdmins[KYCAdmin] = newStatus;
emit KYCAdminChanged(KYCAdmin, newStatus);
}
/**
* @dev Function for use by the KYC admins to add or remove KYC Customers
*/
function _changeCustomerKYC(address customer, bool newStatus) public {
require(KYCAdmins[msg.sender], "KYC_ADMIN_CHECK_FAILED");
customersWithKYC[customer] = newStatus;
emit KYCCustomerChanged(customer, newStatus);
}
/**
* @dev Liquidator Integration
*/
/**
* @dev Function for use by the admin of the contract to add or remove Liquidators
*/
function _changeLiquidator(address liquidator, bool newStatus)
public
onlyOwner
{
liquidators[liquidator] = newStatus;
emit LiquidatorChanged(liquidator, newStatus);
}
/**
* @dev Simple function to calculate min between two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a < b) {
return a;
} else {
return b;
}
}
/**
* @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse.
* Note: this will not add the asset if it already exists.
*/
function addCollateralMarket(address asset) internal {
for (uint256 i = 0; i < collateralMarkets.length; i++) {
if (collateralMarkets[i] == asset) {
return;
}
}
collateralMarkets.push(asset);
}
/**
* @dev Calculates a new supply index based on the prevailing interest rates applied over time
* This is defined as `we multiply the most recent supply index by (1 + blocks times rate)`
* @return Return value is expressed in 1e18 scale
*/
function calculateInterestIndex(
uint256 startingInterestIndex,
uint256 interestRateMantissa,
uint256 blockStart,
uint256 blockEnd
) internal pure returns (Error, uint256) {
// Get the block delta
(Error err0, uint256 blockDelta) = sub(blockEnd, blockStart);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
// Scale the interest rate times number of blocks
// Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.`
(Error err1, Exp memory blocksTimesRate) = mulScalar(
Exp({mantissa: interestRateMantissa}),
blockDelta
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
// Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0)
(Error err2, Exp memory onePlusBlocksTimesRate) = addExp(
blocksTimesRate,
Exp({mantissa: mantissaOne})
);
if (err2 != Error.NO_ERROR) {
return (err2, 0);
}
// Then scale that accumulated interest by the old interest index to get the new interest index
(Error err3, Exp memory newInterestIndexExp) = mulScalar(
onePlusBlocksTimesRate,
startingInterestIndex
);
if (err3 != Error.NO_ERROR) {
return (err3, 0);
}
// Finally, truncate the interest index. This works only if interest index starts large enough
// that is can be accurately represented with a whole number.
return (Error.NO_ERROR, truncate(newInterestIndexExp));
}
/**
* @dev Calculates a new balance based on a previous balance and a pair of interest indices
* This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex
* value and divided by the user's checkpoint index value`
* @return Return value is expressed in 1e18 scale
*/
function calculateBalance(
uint256 startingBalance,
uint256 interestIndexStart,
uint256 interestIndexEnd
) internal pure returns (Error, uint256) {
if (startingBalance == 0) {
// We are accumulating interest on any previous balance; if there's no previous balance, then there is
// nothing to accumulate.
return (Error.NO_ERROR, 0);
}
(Error err0, uint256 balanceTimesIndex) = mul(
startingBalance,
interestIndexEnd
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return div(balanceTimesIndex, interestIndexStart);
}
/**
* @dev Gets the price for the amount specified of the given asset.
* @return Return value is expressed in a magnified scale per token decimals
*/
function getPriceForAssetAmount(
address asset,
uint256 assetAmount,
bool mulCollatRatio
) internal view returns (Error, Exp memory) {
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
if (isZeroExp(assetPrice)) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
if (mulCollatRatio) {
Exp memory scaledPrice;
// Now, multiply the assetValue by the collateral ratio
(err, scaledPrice) = mulExp(collateralRatio, assetPrice);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
// Get the price for the given asset amount
return mulScalar(scaledPrice, assetAmount);
}
return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth
}
/**
* @dev Calculates the origination fee added to a given borrowAmount
* This is simply `(1 + originationFee) * borrowAmount`
* @return Return value is expressed in 1e18 scale
*/
function calculateBorrowAmountWithFee(uint256 borrowAmount)
internal
view
returns (Error, uint256)
{
// When origination fee is zero, the amount with fee is simply equal to the amount
if (isZeroExp(originationFee)) {
return (Error.NO_ERROR, borrowAmount);
}
(Error err0, Exp memory originationFeeFactor) = addExp(
originationFee,
Exp({mantissa: mantissaOne})
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
(Error err1, Exp memory borrowAmountWithFee) = mulScalar(
originationFeeFactor,
borrowAmount
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
return (Error.NO_ERROR, truncate(borrowAmountWithFee));
}
/**
* @dev fetches the price of asset from the PriceOracle and converts it to Exp
* @param asset asset whose price should be fetched
* @return Return value is expressed in a magnified scale per token decimals
*/
function fetchAssetPrice(address asset)
internal
view
returns (Error, Exp memory)
{
if (priceOracle == address(0)) {
return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0}));
}
if (priceOracle.paused()) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
(uint256 priceMantissa, uint8 assetDecimals) = priceOracle
.getAssetPrice(asset);
(Error err, uint256 magnification) = sub(18, uint256(assetDecimals));
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
(err, priceMantissa) = mul(priceMantissa, 10**magnification);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: priceMantissa}));
}
/**
* @notice Reads scaled price of specified asset from the price oracle
* @dev Reads scaled price of specified asset from the price oracle.
* The plural name is to match a previous storage mapping that this function replaced.
* @param asset Asset whose price should be retrieved
* @return 0 on an error or missing price, the price scaled by 1e18 otherwise
*/
function assetPrices(address asset) public view returns (uint256) {
(Error err, Exp memory result) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return 0;
}
return result.mantissa;
}
/**
* @dev Gets the amount of the specified asset given the specified Eth value
* ethValue / oraclePrice = assetAmountWei
* If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0)
* @return Return value is expressed in a magnified scale per token decimals
*/
function getAssetAmountForValue(address asset, Exp ethValue)
internal
view
returns (Error, uint256)
{
Error err;
Exp memory assetPrice;
Exp memory assetAmount;
(err, assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, assetAmount) = divExp(ethValue, assetPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(assetAmount));
}
/**
* @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin
* @param newOracle New oracle address
* @param requestedState value to assign to `paused`
* @param originationFeeMantissa rational collateral ratio, scaled by 1e18.
* @param newCloseFactorMantissa new Close Factor, scaled by 1e18
* @param wethContractAddress WETH Contract Address
* @param _rewardControl Reward Control Address
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _adminFunctions(
address newPendingAdmin,
address newOracle,
bool requestedState,
uint256 originationFeeMantissa,
uint256 newCloseFactorMantissa,
address wethContractAddress,
address _rewardControl
) public onlyOwner returns (uint256) {
// newPendingAdmin can be 0x00, hence not checked
require(newOracle != address(0), "Cannot set weth address to 0x00");
require(
originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18,
"Invalid Origination Fee or Close Factor Mantissa"
);
// Store pendingAdmin = newPendingAdmin
pendingAdmin = newPendingAdmin;
// Verify contract at newOracle address supports assetPrices call.
// This will revert if it doesn't.
// ChainLink priceOracleTemp = ChainLink(newOracle);
// priceOracleTemp.getAssetPrice(address(0));
// Initialize the Chainlink contract in priceOracle
priceOracle = ChainLink(newOracle);
paused = requestedState;
originationFee = Exp({mantissa: originationFeeMantissa});
closeFactorMantissa = newCloseFactorMantissa;
require(
wethContractAddress != address(0),
"Cannot set weth address to 0x00"
);
wethAddress = wethContractAddress;
WETHContract = AlkemiWETH(wethAddress);
rewardControl = RewardControlInterface(_rewardControl);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() public {
// Check caller = pendingAdmin
// msg.sender can't be zero
require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK");
// Store admin = pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = 0;
}
/**
* @notice returns the liquidity for given account.
* a positive result indicates ability to borrow, whereas
* a negative result indicates a shortfall which may be liquidated
* @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0
* note: this includes interest trued up on all balances
* @param account the account to examine
* @return signed integer in terms of eth-wei (negative indicates a shortfall)
*/
function getAccountLiquidity(address account) public view returns (int256) {
(
Error err,
Exp memory accountLiquidity,
Exp memory accountShortfall
) = calculateAccountLiquidity(account);
revertIfError(err);
if (isZeroExp(accountLiquidity)) {
return -1 * int256(truncate(accountShortfall));
} else {
return int256(truncate(accountLiquidity));
}
}
/**
* @notice return supply balance with any accumulated interest for `asset` belonging to `account`
* @dev returns supply balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose supply balance belonging to `account` should be checked
* @return uint supply balance on success, throws on failed assertion otherwise
*/
function getSupplyBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[account][asset];
// Calculate the newSupplyIndex, needed to calculate user's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
newSupplyIndex
);
revertIfError(err);
return userSupplyCurrent;
}
/**
* @notice return borrow balance with any accumulated interest for `asset` belonging to `account`
* @dev returns borrow balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose borrow balance belonging to `account` should be checked
* @return uint borrow balance on success, throws on failed assertion otherwise
*/
function getBorrowBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[account][asset];
// Calculate the newBorrowIndex, needed to calculate user's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
newBorrowIndex
);
revertIfError(err);
return userBorrowCurrent;
}
/**
* @notice Supports a given market (asset) for use
* @dev Admin function to add support for a market
* @param asset Asset to support; MUST already have a non-zero price set
* @param interestRateModel InterestRateModel to use for the asset
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _supportMarket(address asset, InterestRateModel interestRateModel)
public
onlyOwner
returns (uint256)
{
// Hard cap on the maximum number of markets allowed
require(
interestRateModel != address(0) &&
collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED
"INPUT_VALIDATION_FAILED"
);
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED);
}
if (isZeroExp(assetPrice)) {
return
fail(
Error.ASSET_NOT_PRICED,
FailureInfo.SUPPORT_MARKET_PRICE_CHECK
);
}
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
// Append asset to collateralAssets if not set
addCollateralMarket(asset);
// Set market isSupported to true
markets[asset].isSupported = true;
// Default supply and borrow index to 1e18
if (markets[asset].supplyIndex == 0) {
markets[asset].supplyIndex = initialInterestIndex;
}
if (markets[asset].borrowIndex == 0) {
markets[asset].borrowIndex = initialInterestIndex;
}
return uint256(Error.NO_ERROR);
}
/**
* @notice Suspends a given *supported* market (asset) from use.
* Assets in this state do count for collateral, but users may only withdraw, payBorrow,
* and liquidate the asset. The liquidate function no longer checks collateralization.
* @dev Admin function to suspend a market
* @param asset Asset to suspend
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _suspendMarket(address asset) public onlyOwner returns (uint256) {
// If the market is not configured at all, we don't want to add any configuration for it.
// If we find !markets[asset].isSupported then either the market is not configured at all, or it
// has already been marked as unsupported. We can just return without doing anything.
// Caller is responsible for knowing the difference between not-configured and already unsupported.
if (!markets[asset].isSupported) {
return uint256(Error.NO_ERROR);
}
// If we get here, we know market is configured and is supported, so set isSupported to false
markets[asset].isSupported = false;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the risk parameters: collateral ratio and liquidation discount
* @dev Owner function to set the risk parameters
* @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1
* @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setRiskParameters(
uint256 collateralRatioMantissa,
uint256 liquidationDiscountMantissa
) public onlyOwner returns (uint256) {
// Input validations
require(
collateralRatioMantissa >= minimumCollateralRatioMantissa &&
liquidationDiscountMantissa <=
maximumLiquidationDiscountMantissa,
"Liquidation discount is more than max discount or collateral ratio is less than min ratio"
);
Exp memory newCollateralRatio = Exp({
mantissa: collateralRatioMantissa
});
Exp memory newLiquidationDiscount = Exp({
mantissa: liquidationDiscountMantissa
});
Exp memory minimumCollateralRatio = Exp({
mantissa: minimumCollateralRatioMantissa
});
Exp memory maximumLiquidationDiscount = Exp({
mantissa: maximumLiquidationDiscountMantissa
});
Error err;
Exp memory newLiquidationDiscountPlusOne;
// Make sure new collateral ratio value is not below minimum value
if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) {
return
fail(
Error.INVALID_COLLATERAL_RATIO,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the
// existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential.
if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) {
return
fail(
Error.INVALID_LIQUIDATION_DISCOUNT,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount`
// C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount`
(err, newLiquidationDiscountPlusOne) = addExp(
newLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
revertIfError(err); // We already validated that newLiquidationDiscount does not approach overflow size
if (
lessThanOrEqualExp(
newCollateralRatio,
newLiquidationDiscountPlusOne
)
) {
return
fail(
Error.INVALID_COMBINED_RISK_PARAMETERS,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Store new values
collateralRatio = newCollateralRatio;
liquidationDiscount = newLiquidationDiscount;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the interest rate model for a given market
* @dev Admin function to set interest rate model
* @param asset Asset to support
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMarketInterestRateModel(
address asset,
InterestRateModel interestRateModel
) public onlyOwner returns (uint256) {
require(interestRateModel != address(0), "Rate Model cannot be 0x00");
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply
* @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply
* @param asset asset whose equity should be withdrawn
* @param amount amount of equity to withdraw; must not exceed equity available
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _withdrawEquity(address asset, uint256 amount)
public
onlyOwner
returns (uint256)
{
// Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply.
uint256 cash = getCash(asset);
// Get supply and borrows with interest accrued till the latest block
(
uint256 supplyWithInterest,
uint256 borrowWithInterest
) = getMarketBalances(asset);
(Error err0, uint256 equity) = addThenSub(
getCash(asset),
borrowWithInterest,
supplyWithInterest
);
if (err0 != Error.NO_ERROR) {
return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY);
}
if (amount > equity) {
return
fail(
Error.EQUITY_INSUFFICIENT_BALANCE,
FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset out of the protocol to the admin
Error err2 = doTransferOut(asset, admin, amount);
if (err2 != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return
fail(
err2,
FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED
);
}
} else {
withdrawEther(admin, amount); // send Ether to user
}
(, markets[asset].supplyRateMantissa) = markets[asset]
.interestRateModel
.getSupplyRate(asset, cash - amount, markets[asset].totalSupply);
(, markets[asset].borrowRateMantissa) = markets[asset]
.interestRateModel
.getBorrowRate(asset, cash - amount, markets[asset].totalBorrows);
//event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner)
emit EquityWithdrawn(asset, equity, amount, admin);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user
* @return errors if any
* @param etherAmount Amount of ether to be converted to WETH
*/
function supplyEther(uint256 etherAmount) internal returns (uint256) {
require(wethAddress != address(0), "WETH_ADDRESS_NOT_SET_ERROR");
WETHContract.deposit.value(etherAmount)();
return uint256(Error.NO_ERROR);
}
/**
* @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason
* @param etherAmount Amount of ether to be sent back to user
* @param user User account address
*/
function revertEtherToUser(address user, uint256 etherAmount) internal {
if (etherAmount > 0) {
user.transfer(etherAmount);
}
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol
* @dev add amount of supported asset to msg.sender's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supply(address asset, uint256 amount)
public
payable
nonReentrant
onlyCustomerWithKYC
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED);
}
refreshAlkIndex(asset, msg.sender, true, true);
Market storage market = markets[asset];
Balance storage balance = supplyBalances[msg.sender][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// Fail if market not supported
if (!market.isSupported) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED
);
}
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
// Fail gracefully if asset is not approved or has insufficient balance
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
amount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex (we already had newSupplyIndex)
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(msg.value);
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
emit SupplyReceived(
msg.sender,
asset,
amount,
localResults.startingBalance,
balance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice withdraw `amount` of `ether` from sender's account to sender's address
* @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender
* @param etherAmount Amount of ether to be converted to WETH
* @param user User account address
*/
function withdrawEther(address user, uint256 etherAmount)
internal
returns (uint256)
{
WETHContract.withdraw(user, etherAmount);
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraw `amount` of `asset` from sender's account to sender's address
* @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender
* @param asset The market asset to withdraw
* @param requestedAmount The amount to withdraw (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function withdraw(address asset, uint256 requestedAmount)
public
nonReentrant
returns (uint256)
{
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.WITHDRAW_CONTRACT_PAUSED
);
}
refreshAlkIndex(asset, msg.sender, true, true);
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[msg.sender][asset];
WithdrawLocalVars memory localResults; // Holds all our calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// We calculate the user's accountLiquidity and accountShortfall.
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent
if (requestedAmount == uint256(-1)) {
(err, localResults.withdrawCapacity) = getAssetAmountForValue(
asset,
localResults.accountLiquidity
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED);
}
localResults.withdrawAmount = min(
localResults.withdrawCapacity,
localResults.userSupplyCurrent
);
} else {
localResults.withdrawAmount = requestedAmount;
}
// From here on we should NOT use requestedAmount.
// Fail gracefully if protocol has insufficient cash
// If protocol has insufficient cash, the sub operation will underflow.
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = sub(
localResults.currentCash,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE
);
}
// We check that the amount is less than or equal to supplyCurrent
// If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW
(err, localResults.userSupplyUpdated) = sub(
localResults.userSupplyCurrent,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.INSUFFICIENT_BALANCE,
FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT
);
}
// We want to know the user's withdrawCapacity, denominated in the asset
// Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth)
// Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth
(err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount(
asset,
localResults.withdrawAmount,
false
); // amount * oraclePrice = ethValueOfWithdrawal
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED);
}
// We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below)
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfWithdrawal
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply.
// Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
supplyBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event
supplyBalance.principal = localResults.userSupplyUpdated;
supplyBalance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, localResults.withdrawAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user
}
emit SupplyWithdrawn(
msg.sender,
asset,
localResults.withdrawAmount,
localResults.startingBalance,
supplyBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Gets the user's account liquidity and account shortfall balances. This includes
* any accumulated interest thus far but does NOT actually update anything in
* storage, it simply calculates the account liquidity and shortfall with liquidity being
* returned as the first Exp, ie (Error, accountLiquidity, accountShortfall).
* @return Return values are expressed in 1e18 scale
*/
function calculateAccountLiquidity(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
Error err;
Exp memory sumSupplyValuesMantissa;
Exp memory sumBorrowValuesMantissa;
(
err,
sumSupplyValuesMantissa,
sumBorrowValuesMantissa
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
Exp memory result;
Exp memory sumSupplyValuesFinal = Exp({
mantissa: sumSupplyValuesMantissa.mantissa
});
Exp memory sumBorrowValuesFinal; // need to apply collateral ratio
(err, sumBorrowValuesFinal) = mulExp(
collateralRatio,
Exp({mantissa: sumBorrowValuesMantissa.mantissa})
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall.
// else the user meets the collateral ratio and has account liquidity.
if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) {
// accountShortfall = borrows - supplies
(err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal);
revertIfError(err); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, Exp({mantissa: 0}), result);
} else {
// accountLiquidity = supplies - borrows
(err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal);
revertIfError(err); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, result, Exp({mantissa: 0}));
}
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValuesInternal(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
/** By definition, all collateralMarkets are those that contribute to the user's
* liquidity and shortfall so we need only loop through those markets.
* To handle avoiding intermediate negative results, we will sum all the user's
* supply balances and borrow balances (with collateral ratio) separately and then
* subtract the sums at the end.
*/
AccountValueLocalVars memory localResults; // Re-used for all intermediate results
localResults.sumSupplies = Exp({mantissa: 0});
localResults.sumBorrows = Exp({mantissa: 0});
Error err; // Re-used for all intermediate errors
localResults.collateralMarketsLength = collateralMarkets.length;
for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) {
localResults.assetAddress = collateralMarkets[i];
Market storage currentMarket = markets[localResults.assetAddress];
Balance storage supplyBalance = supplyBalances[userAddress][
localResults.assetAddress
];
Balance storage borrowBalance = borrowBalances[userAddress][
localResults.assetAddress
];
if (supplyBalance.principal > 0) {
// We calculate the newSupplyIndex and user’s supplyCurrent (includes interest)
(err, localResults.newSupplyIndex) = calculateInterestIndex(
currentMarket.supplyIndex,
currentMarket.supplyRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's supply balance with interest so let's multiply by the asset price to get the total value
(err, localResults.supplyTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userSupplyCurrent,
false
); // supplyCurrent * oraclePrice = supplyValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of supplies
(err, localResults.sumSupplies) = addExp(
localResults.supplyTotalValue,
localResults.sumSupplies
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
if (borrowBalance.principal > 0) {
// We perform a similar actions to get the user's borrow balance
(err, localResults.newBorrowIndex) = calculateInterestIndex(
currentMarket.borrowIndex,
currentMarket.borrowRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's borrow balance with interest so let's multiply by the asset price to get the total value
(err, localResults.borrowTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userBorrowCurrent,
false
); // borrowCurrent * oraclePrice = borrowValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of borrows
(err, localResults.sumBorrows) = addExp(
localResults.borrowTotalValue,
localResults.sumBorrows
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
}
return (
Error.NO_ERROR,
localResults.sumSupplies,
localResults.sumBorrows
);
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details),
* sum ETH value of supplies scaled by 10e18,
* sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValues(address userAddress)
public
view
returns (
uint256,
uint256,
uint256
)
{
(
Error err,
Exp memory supplyValue,
Exp memory borrowValue
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (uint256(err), 0, 0);
}
return (0, supplyValue.mantissa, borrowValue.mantissa);
}
/**
* @notice Users repay borrowed assets from their own address to the protocol.
* @param asset The market asset to repay
* @param amount The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(address asset, uint256 amount)
public
payable
nonReentrant
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.REPAY_BORROW_CONTRACT_PAUSED
);
}
refreshAlkIndex(asset, msg.sender, false, true);
PayBorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
uint256 reimburseAmount;
// If the user specifies -1 amount to repay (“max”), repayAmount =>
// the lesser of the senders ERC-20 balance and borrowCurrent
if (asset != wethAddress) {
if (amount == uint256(-1)) {
localResults.repayAmount = min(
getBalanceOf(asset, msg.sender),
localResults.userBorrowCurrent
);
} else {
localResults.repayAmount = amount;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (amount > localResults.userBorrowCurrent) {
localResults.repayAmount = localResults.userBorrowCurrent;
(err, reimburseAmount) = sub(
amount,
localResults.userBorrowCurrent
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults.repayAmount = amount;
}
}
// Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated`
// Note: this checks that repayAmount is less than borrowCurrent
(err, localResults.userBorrowUpdated) = sub(
localResults.userBorrowCurrent,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail gracefully if asset is not approved or has insufficient balance
// Note: this checks that repayAmount is less than or equal to their ERC-20 balance
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE
);
}
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(
localResults.currentCash,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(localResults.repayAmount);
//Repay excess funds
if (reimburseAmount > 0) {
revertEtherToUser(msg.sender, reimburseAmount);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
asset,
msg.sender,
localResults.repayAmount,
market.supplyIndex
);
emit BorrowRepaid(
msg.sender,
asset,
localResults.repayAmount,
localResults.startingBalance,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice users repay all or some of an underwater borrow and receive collateral
* @param targetAccount The account whose borrow should be liquidated
* @param assetBorrow The market asset to repay
* @param assetCollateral The borrower's market asset to receive in exchange
* @param requestedAmountClose The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(
address targetAccount,
address assetBorrow,
address assetCollateral,
uint256 requestedAmountClose
) public payable returns (uint256) {
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.LIQUIDATE_CONTRACT_PAUSED
);
}
require(liquidators[msg.sender], "LIQUIDATOR_CHECK_FAILED");
refreshAlkIndex(assetCollateral, targetAccount, true, true);
refreshAlkIndex(assetCollateral, msg.sender, true, true);
refreshAlkIndex(assetBorrow, targetAccount, false, true);
LiquidateLocalVars memory localResults;
// Copy these addresses into the struct for use with `emitLiquidationEvent`
// We'll use localResults.liquidator inside this function for clarity vs using msg.sender.
localResults.targetAccount = targetAccount;
localResults.assetBorrow = assetBorrow;
localResults.liquidator = msg.sender;
localResults.assetCollateral = assetCollateral;
Market storage borrowMarket = markets[assetBorrow];
Market storage collateralMarket = markets[assetCollateral];
Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[
targetAccount
][assetBorrow];
Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[
targetAccount
][assetCollateral];
// Liquidator might already hold some of the collateral asset
Balance storage supplyBalance_LiquidatorCollateralAsset
= supplyBalances[localResults.liquidator][assetCollateral];
uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls
Error err; // re-used for all intermediate errors
(err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED);
}
(err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow);
// If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice
revertIfError(err);
// We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset
(
err,
localResults.newBorrowIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.borrowIndex,
borrowMarket.borrowRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
err,
localResults.currentBorrowBalance_TargetUnderwaterAsset
) = calculateBalance(
borrowBalance_TargeUnderwaterAsset.principal,
borrowBalance_TargeUnderwaterAsset.interestIndex,
localResults.newBorrowIndex_UnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED
);
}
// We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset
(
err,
localResults.newSupplyIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.supplyIndex,
collateralMarket.supplyRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
(
err,
localResults.currentSupplyBalance_TargetCollateralAsset
) = calculateBalance(
supplyBalance_TargetCollateralAsset.principal,
supplyBalance_TargetCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Liquidator may or may not already have some collateral asset.
// If they do, we need to accumulate interest on it before adding the seized collateral to it.
// We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset
(
err,
localResults.currentSupplyBalance_LiquidatorCollateralAsset
) = calculateBalance(
supplyBalance_LiquidatorCollateralAsset.principal,
supplyBalance_LiquidatorCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated
// interest and then by adding the liquidator's accumulated interest.
// Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the target user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
collateralMarket.totalSupply,
localResults.currentSupplyBalance_TargetCollateralAsset,
supplyBalance_TargetCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the calling user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
localResults.newTotalSupply_ProtocolCollateralAsset,
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
supplyBalance_LiquidatorCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user
// This is equal to the lesser of
// 1. borrowCurrent; (already calculated)
// 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount:
// discountedRepayToEvenAmount=
// shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
// 3. discountedBorrowDenominatedCollateral
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
// Here we calculate item 3. discountedBorrowDenominatedCollateral =
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
(
err,
localResults.discountedBorrowDenominatedCollateral
) = calculateDiscountedBorrowDenominatedCollateral(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.currentSupplyBalance_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED
);
}
if (borrowMarket.isSupported) {
// Market is supported, so we calculate item 2 from above.
(
err,
localResults.discountedRepayToEvenAmount
) = calculateDiscountedRepayToEvenAmount(
targetAccount,
localResults.underwaterAssetPrice,
assetBorrow
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED
);
}
// We need to do a two-step min to select from all 3 values
// min1&3 = min(item 1, item 3)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
// min1&3&2 = min(min1&3, 2)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset,
localResults.discountedRepayToEvenAmount
);
} else {
// Market is not supported, so we don't need to calculate item 2.
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
}
// If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset
if (assetBorrow != wethAddress) {
if (requestedAmountClose == uint256(-1)) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (
requestedAmountClose >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
(err, localResults.reimburseAmount) = sub(
requestedAmountClose,
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
}
// From here on, no more use of `requestedAmountClose`
// Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset
if (
localResults.closeBorrowAmount_TargetUnderwaterAsset >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
return
fail(
Error.INVALID_CLOSE_AMOUNT_REQUESTED,
FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH
);
}
// seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount)
(
err,
localResults.seizeSupplyAmount_TargetCollateralAsset
) = calculateAmountSeize(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED
);
}
// We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol
// Fail gracefully if asset is not approved or has insufficient balance
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
err = checkTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We are going to repay the target user's borrow using the calling user's funds
// We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance,
// adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset.
// Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset`
(err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
// We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow
revertIfError(err);
// We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(
err,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
) = addThenSub(
borrowMarket.totalBorrows,
localResults.updatedBorrowBalance_TargetUnderwaterAsset,
borrowBalance_TargeUnderwaterAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET
);
}
// We need to calculate what the updated cash will be after we transfer in from liquidator
localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow);
(err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(
localResults.currentCash_ProtocolUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET
);
}
// The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow
// (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.)
// We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it.
(
err,
localResults.newSupplyIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.supplyIndex,
borrowMarket.supplyRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
rateCalculationResultCode,
localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getSupplyRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
(
rateCalculationResultCode,
localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getBorrowRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
// Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above.
// Now we need to calculate the borrow index.
// We don't need to calculate new rates for the collateral asset because we have not changed utilization:
// - accumulating interest on the target user's collateral does not change cash or borrows
// - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows.
(
err,
localResults.newBorrowIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.borrowIndex,
collateralMarket.borrowRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
// We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index
(err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub(
localResults.currentSupplyBalance_TargetCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance
// maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset
// which in turn limits seizeSupplyAmount_TargetCollateralAsset.
revertIfError(err);
// We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index
(
err,
localResults.updatedSupplyBalance_LiquidatorCollateralAsset
) = add(
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// We can't overflow here because if this would overflow, then we would have already overflowed above and failed
// with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
revertIfError(err);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save borrow market updates
borrowMarket.blockNumber = block.number;
borrowMarket.totalBorrows = localResults
.newTotalBorrows_ProtocolUnderwaterAsset;
// borrowMarket.totalSupply does not need to be updated
borrowMarket.supplyRateMantissa = localResults
.newSupplyRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset;
borrowMarket.borrowRateMantissa = localResults
.newBorrowRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset;
// Save collateral market updates
// We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply.
collateralMarket.blockNumber = block.number;
collateralMarket.totalSupply = localResults
.newTotalSupply_ProtocolCollateralAsset;
collateralMarket.supplyIndex = localResults
.newSupplyIndex_CollateralAsset;
collateralMarket.borrowIndex = localResults
.newBorrowIndex_CollateralAsset;
// Save user updates
localResults
.startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset
.principal; // save for use in event
borrowBalance_TargeUnderwaterAsset.principal = localResults
.updatedBorrowBalance_TargetUnderwaterAsset;
borrowBalance_TargeUnderwaterAsset.interestIndex = localResults
.newBorrowIndex_UnderwaterAsset;
localResults
.startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset
.principal; // save for use in event
supplyBalance_TargetCollateralAsset.principal = localResults
.updatedSupplyBalance_TargetCollateralAsset;
supplyBalance_TargetCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
localResults
.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset
.principal; // save for use in event
supplyBalance_LiquidatorCollateralAsset.principal = localResults
.updatedSupplyBalance_LiquidatorCollateralAsset;
supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == requestedAmountClose) {
uint256 supplyError = supplyEther(
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
//Repay excess funds
if (localResults.reimburseAmount > 0) {
revertEtherToUser(
localResults.liquidator,
localResults.reimburseAmount
);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.newSupplyIndex_UnderwaterAsset
);
emit BorrowLiquidated(
localResults.targetAccount,
localResults.assetBorrow,
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.liquidator,
localResults.assetCollateral,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
* If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed.
* Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO.
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedRepayToEvenAmount(
address targetAccount,
Exp memory underwaterAssetPrice,
address assetBorrow
) internal view returns (Error, uint256) {
Error err;
Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity
Exp memory accountShortfall_TargetUser;
Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount
Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1
Exp memory discountedPrice_UnderwaterAsset;
Exp memory rawResult;
// we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio
(
err,
_accountLiquidity,
accountShortfall_TargetUser
) = calculateAccountLiquidity(targetAccount);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, collateralRatioMinusLiquidationDiscount) = subExp(
collateralRatio,
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedCollateralRatioMinusOne) = subExp(
collateralRatioMinusLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedPrice_UnderwaterAsset) = mulExp(
underwaterAssetPrice,
discountedCollateralRatioMinusOne
);
// calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio
// discountedCollateralRatioMinusOne < collateralRatio
// so if underwaterAssetPrice * collateralRatio did not overflow then
// underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either
revertIfError(err);
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow);
Exp memory maxClose;
(err, maxClose) = mulScalar(
Exp({mantissa: closeFactorMantissa}),
borrowBalance
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset);
// It's theoretically possible an asset could have such a low price that it truncates to zero when discounted.
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedBorrowDenominatedCollateral(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 supplyCurrent_TargetCollateralAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end
// [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ]
Error err;
Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount)
Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral
Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow
Exp memory rawResult;
(err, onePlusLiquidationDiscount) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, supplyCurrentTimesOracleCollateral) = mulScalar(
collateralPrice,
supplyCurrent_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp(
onePlusLiquidationDiscount,
underwaterAssetPrice
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(
supplyCurrentTimesOracleCollateral,
onePlusLiquidationDiscountTimesOracleBorrow
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral
* @return Return values are expressed in 1e18 scale
*/
function calculateAmountSeize(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 closeBorrowAmount_TargetUnderwaterAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices:
// underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice
// re-used for all intermediate errors
Error err;
// (1+liquidationDiscount)
Exp memory liquidationMultiplier;
// assetPrice-of-underwaterAsset * (1+liquidationDiscount)
Exp memory priceUnderwaterAssetTimesLiquidationMultiplier;
// priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset
// or, expanded:
// underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset
Exp memory finalNumerator;
// finalNumerator / priceCollateral
Exp memory rawResult;
(err, liquidationMultiplier) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
// liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow.
revertIfError(err);
(err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(
underwaterAssetPrice,
liquidationMultiplier
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, finalNumerator) = mulScalar(
priceUnderwaterAssetTimesLiquidationMultiplier,
closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(finalNumerator, collateralPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param asset The market asset to borrow
* @param amount The amount to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(address asset, uint256 amount)
public
nonReentrant
onlyCustomerWithKYC
returns (uint256)
{
if (paused) {
return
fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED);
}
refreshAlkIndex(asset, msg.sender, false, true);
BorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// Fail if market not supported
if (!market.isSupported) {
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.BORROW_MARKET_NOT_SUPPORTED
);
}
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// Calculate origination fee.
(err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee(
amount
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED
);
}
uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount;
// Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated`
(err, localResults.userBorrowUpdated) = add(
localResults.userBorrowCurrent,
localResults.borrowAmountWithFee
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// Check customer liquidity
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT
);
}
// Would the customer have a shortfall after this borrow (including origination fee)?
// We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity.
// This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity`
(
err,
localResults.ethValueOfBorrowAmountWithFee
) = getPriceForAssetAmount(
asset,
localResults.borrowAmountWithFee,
true
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED);
}
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfBorrowAmountWithFee
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// Fail gracefully if protocol has insufficient cash
localResults.currentCash = getCash(asset);
// We need to calculate what the updated cash will be after we transfer out to the user
(err, localResults.updatedCash) = sub(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
// Note: we ignore error here and call this token insufficient cash
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
originationFeeBalance[msg.sender][asset] += orgFeeBalance;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, amount); // send Ether to user
}
emit BorrowTaken(
msg.sender,
asset,
amount,
localResults.startingBalance,
localResults.borrowAmountWithFee,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol
* @dev add amount of supported asset to admin's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supplyOriginationFeeAsAdmin(
address asset,
address user,
uint256 amount,
uint256 newSupplyIndex
) private {
refreshAlkIndex(asset, admin, true, true);
uint256 originationFeeRepaid = 0;
if (originationFeeBalance[user][asset] != 0) {
if (amount < originationFeeBalance[user][asset]) {
originationFeeRepaid = amount;
} else {
originationFeeRepaid = originationFeeBalance[user][asset];
}
Balance storage balance = supplyBalances[admin][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
originationFeeBalance[user][asset] -= originationFeeRepaid;
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
newSupplyIndex
);
revertIfError(err);
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
originationFeeRepaid
);
revertIfError(err);
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
markets[asset].totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
revertIfError(err);
// Save market updates
markets[asset].totalSupply = localResults.newTotalSupply;
// Save user updates
localResults.startingBalance = balance.principal;
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = newSupplyIndex;
emit SupplyReceived(
admin,
asset,
originationFeeRepaid,
localResults.startingBalance,
localResults.userSupplyUpdated
);
}
}
/**
* @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market
* @param market The address of the market to accrue rewards
* @param user The address of the supplier/borrower to accrue rewards
* @param isSupply Specifies if Supply or Borrow Index need to be updated
* @param isVerified Verified / Public protocol
*/
function refreshAlkIndex(
address market,
address user,
bool isSupply,
bool isVerified
) internal {
if (address(rewardControl) == address(0)) {
return;
}
if (isSupply) {
rewardControl.refreshAlkSupplyIndex(market, user, isVerified);
} else {
rewardControl.refreshAlkBorrowIndex(market, user, isVerified);
}
}
/**
* @notice Get supply and borrows for a market
* @param asset The market asset to find balances of
* @return updated supply and borrows
*/
function getMarketBalances(address asset)
public
view
returns (uint256, uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 marketSupplyCurrent;
uint256 newBorrowIndex;
uint256 marketBorrowCurrent;
Market storage market = markets[asset];
// Calculate the newSupplyIndex, needed to calculate market's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, marketSupplyCurrent) = calculateBalance(
market.totalSupply,
market.supplyIndex,
newSupplyIndex
);
revertIfError(err);
// Calculate the newBorrowIndex, needed to calculate market's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, marketBorrowCurrent) = calculateBalance(
market.totalBorrows,
market.borrowIndex,
newBorrowIndex
);
revertIfError(err);
return (marketSupplyCurrent, marketBorrowCurrent);
}
/**
* @dev Function to revert in case of an internal exception
*/
function revertIfError(Error err) internal pure {
require(
err == Error.NO_ERROR,
"Function revert due to internal exception"
);
}
}
// File: contracts/AlkemiEarnPublic.sol
pragma solidity 0.4.24;
contract AlkemiEarnPublic is Exponential, SafeToken {
uint256 internal initialInterestIndex;
uint256 internal defaultOriginationFee;
uint256 internal defaultCollateralRatio;
uint256 internal defaultLiquidationDiscount;
// minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability
// Values cannot be assigned directly as OpenZeppelin upgrades do not support the same
// Values can only be assigned using initializer() below
// However, there is no way to change the below values using any functions and hence they act as constants
uint256 public minimumCollateralRatioMantissa;
uint256 public maximumLiquidationDiscountMantissa;
bool private initializationDone; // To make sure initializer is called only once
/**
* @notice `AlkemiEarnPublic` is the core contract
* @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies
* @notice Hence this contract has an 'initializer' in place of a 'constructor'
* @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344
* @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade
*/
function initializer() public {
if (initializationDone == false) {
initializationDone = true;
admin = msg.sender;
initialInterestIndex = 10**18;
defaultOriginationFee = (10**15); // default is 0.1%
defaultCollateralRatio = 125 * (10**16); // default is 125% or 1.25
defaultLiquidationDiscount = (10**17); // default is 10% or 0.1
minimumCollateralRatioMantissa = 11 * (10**17); // 1.1
maximumLiquidationDiscountMantissa = (10**17); // 0.1
collateralRatio = Exp({mantissa: defaultCollateralRatio});
originationFee = Exp({mantissa: defaultOriginationFee});
liquidationDiscount = Exp({mantissa: defaultLiquidationDiscount});
_guardCounter = 1;
// oracle must be configured via _adminFunctions
}
}
/**
* @notice Do not pay directly into AlkemiEarnPublic, please use `supply`.
*/
function() public payable {
revert();
}
/**
* @dev pending Administrator for this contract.
*/
address public pendingAdmin;
/**
* @dev Administrator for this contract. Initially set in constructor, but can
* be changed by the admin itself.
*/
address public admin;
/**
* @dev Managers for this contract with limited permissions. Can
* be changed by the admin.
* Though unused, the below variable cannot be deleted as it will hinder upgradeability
* Will be cleared during the next compiler version upgrade
*/
mapping(address => bool) public managers;
/**
* @dev Account allowed to set oracle prices for this contract. Initially set
* in constructor, but can be changed by the admin.
*/
address private oracle;
/**
* @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin.
*/
ChainLink public priceOracle;
/**
* @dev Container for customer balance information written to storage.
*
* struct Balance {
* principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action
* interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action
* }
*/
struct Balance {
uint256 principal;
uint256 interestIndex;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for supplies
*/
mapping(address => mapping(address => Balance)) public supplyBalances;
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for borrows
*/
mapping(address => mapping(address => Balance)) public borrowBalances;
/**
* @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key
*
* struct Market {
* isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets)
* blockNumber = when the other values in this struct were calculated
* interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset
* totalSupply = total amount of this asset supplied (in asset wei)
* supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18
* supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket
* totalBorrows = total amount of this asset borrowed (in asset wei)
* borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18
* borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket
* }
*/
struct Market {
bool isSupported;
uint256 blockNumber;
InterestRateModel interestRateModel;
uint256 totalSupply;
uint256 supplyRateMantissa;
uint256 supplyIndex;
uint256 totalBorrows;
uint256 borrowRateMantissa;
uint256 borrowIndex;
}
/**
* @dev wethAddress to hold the WETH token contract address
* set using setWethAddress function
*/
address private wethAddress;
/**
* @dev Initiates the contract for supply and withdraw Ether and conversion to WETH
*/
AlkemiWETH public WETHContract;
/**
* @dev map: assetAddress -> Market
*/
mapping(address => Market) public markets;
/**
* @dev list: collateralMarkets
*/
address[] public collateralMarkets;
/**
* @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This
* is initially set in the constructor, but can be changed by the admin.
*/
Exp public collateralRatio;
/**
* @dev originationFee for new borrows.
*
*/
Exp public originationFee;
/**
* @dev liquidationDiscount for collateral when liquidating borrows
*
*/
Exp public liquidationDiscount;
/**
* @dev flag for whether or not contract is paused
*
*/
bool public paused;
/**
* The `SupplyLocalVars` struct is used internally in the `supply` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct SupplyLocalVars {
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
}
/**
* The `WithdrawLocalVars` struct is used internally in the `withdraw` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct WithdrawLocalVars {
uint256 withdrawAmount;
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
uint256 withdrawCapacity;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfWithdrawal;
}
// The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function.
struct AccountValueLocalVars {
address assetAddress;
uint256 collateralMarketsLength;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Exp supplyTotalValue;
Exp sumSupplies;
Exp borrowTotalValue;
Exp sumBorrows;
}
// The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function.
struct PayBorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 repayAmount;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
}
// The `BorrowLocalVars` struct is used internally in the `borrow` function.
struct BorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 borrowAmountWithFee;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfBorrowAmountWithFee;
}
// The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function.
struct LiquidateLocalVars {
// we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.`
address targetAccount;
address assetBorrow;
address liquidator;
address assetCollateral;
// borrow index and supply index are global to the asset, not specific to the user
uint256 newBorrowIndex_UnderwaterAsset;
uint256 newSupplyIndex_UnderwaterAsset;
uint256 newBorrowIndex_CollateralAsset;
uint256 newSupplyIndex_CollateralAsset;
// the target borrow's full balance with accumulated interest
uint256 currentBorrowBalance_TargetUnderwaterAsset;
// currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation
uint256 updatedBorrowBalance_TargetUnderwaterAsset;
uint256 newTotalBorrows_ProtocolUnderwaterAsset;
uint256 startingBorrowBalance_TargetUnderwaterAsset;
uint256 startingSupplyBalance_TargetCollateralAsset;
uint256 startingSupplyBalance_LiquidatorCollateralAsset;
uint256 currentSupplyBalance_TargetCollateralAsset;
uint256 updatedSupplyBalance_TargetCollateralAsset;
// If liquidator already has a balance of collateralAsset, we will accumulate
// interest on it before transferring seized collateral from the borrower.
uint256 currentSupplyBalance_LiquidatorCollateralAsset;
// This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any)
// plus the amount seized from the borrower.
uint256 updatedSupplyBalance_LiquidatorCollateralAsset;
uint256 newTotalSupply_ProtocolCollateralAsset;
uint256 currentCash_ProtocolUnderwaterAsset;
uint256 updatedCash_ProtocolUnderwaterAsset;
// cash does not change for collateral asset
uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset;
uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset;
// Why no variables for the interest rates for the collateral asset?
// We don't need to calculate new rates for the collateral asset since neither cash nor borrows change
uint256 discountedRepayToEvenAmount;
//[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral)
uint256 discountedBorrowDenominatedCollateral;
uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset;
uint256 closeBorrowAmount_TargetUnderwaterAsset;
uint256 seizeSupplyAmount_TargetCollateralAsset;
uint256 reimburseAmount;
Exp collateralPrice;
Exp underwaterAssetPrice;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows
*/
mapping(address => mapping(address => uint256))
public originationFeeBalance;
/**
* @dev Reward Control Contract address
*/
RewardControlInterface public rewardControl;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
/// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 public _guardCounter;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one `nonReentrant` function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and an `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
/**
* @dev emitted when a supply is received
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyReceived(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a origination fee supply is received as admin
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyOrgFeeAsAdmin(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a supply is withdrawn
* Note: startingBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyWithdrawn(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a new borrow is taken
* Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change
*/
event BorrowTaken(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 borrowAmountWithFee,
uint256 newBalance
);
/**
* @dev emitted when a borrow is repaid
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event BorrowRepaid(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a borrow is liquidated
* targetAccount = user whose borrow was liquidated
* assetBorrow = asset borrowed
* borrowBalanceBefore = borrowBalance as most recently stored before the liquidation
* borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountRepaid = amount of borrow repaid
* liquidator = account requesting the liquidation
* assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan
* borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid)
* collateralBalanceBefore = collateral balance as most recently stored before the liquidation
* collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountSeized = amount of collateral seized by liquidator
* collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized)
* assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3
*/
event BorrowLiquidated(
address indexed targetAccount,
address assetBorrow,
uint256 borrowBalanceAccumulated,
uint256 amountRepaid,
address indexed liquidator,
address assetCollateral,
uint256 amountSeized
);
/**
* @dev emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address indexed oldAdmin, address indexed newAdmin);
/**
* @dev emitted when new market is supported by admin
*/
event SupportedMarket(
address indexed asset,
address indexed interestRateModel
);
/**
* @dev emitted when risk parameters are changed by admin
*/
event NewRiskParameters(
uint256 oldCollateralRatioMantissa,
uint256 newCollateralRatioMantissa,
uint256 oldLiquidationDiscountMantissa,
uint256 newLiquidationDiscountMantissa
);
/**
* @dev emitted when origination fee is changed by admin
*/
event NewOriginationFee(
uint256 oldOriginationFeeMantissa,
uint256 newOriginationFeeMantissa
);
/**
* @dev emitted when market has new interest rate model set
*/
event SetMarketInterestRateModel(
address indexed asset,
address indexed interestRateModel
);
/**
* @dev emitted when admin withdraws equity
* Note that `equityAvailableBefore` indicates equity before `amount` was removed.
*/
event EquityWithdrawn(
address indexed asset,
uint256 equityAvailableBefore,
uint256 amount,
address indexed owner
);
/**
* @dev Simple function to calculate min between two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a < b) {
return a;
} else {
return b;
}
}
/**
* @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse.
* Note: this will not add the asset if it already exists.
*/
function addCollateralMarket(address asset) internal {
for (uint256 i = 0; i < collateralMarkets.length; i++) {
if (collateralMarkets[i] == asset) {
return;
}
}
collateralMarkets.push(asset);
}
/**
* @notice return the number of elements in `collateralMarkets`
* @dev you can then externally call `collateralMarkets(uint)` to pull each market address
* @return the length of `collateralMarkets`
*/
function getCollateralMarketsLength() public view returns (uint256) {
return collateralMarkets.length;
}
/**
* @dev Calculates a new supply/borrow index based on the prevailing interest rates applied over time
* This is defined as `we multiply the most recent supply/borrow index by (1 + blocks times rate)`
* @return Return value is expressed in 1e18 scale
*/
function calculateInterestIndex(
uint256 startingInterestIndex,
uint256 interestRateMantissa,
uint256 blockStart,
uint256 blockEnd
) internal pure returns (Error, uint256) {
// Get the block delta
(Error err0, uint256 blockDelta) = sub(blockEnd, blockStart);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
// Scale the interest rate times number of blocks
// Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.`
(Error err1, Exp memory blocksTimesRate) = mulScalar(
Exp({mantissa: interestRateMantissa}),
blockDelta
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
// Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0)
(Error err2, Exp memory onePlusBlocksTimesRate) = addExp(
blocksTimesRate,
Exp({mantissa: mantissaOne})
);
if (err2 != Error.NO_ERROR) {
return (err2, 0);
}
// Then scale that accumulated interest by the old interest index to get the new interest index
(Error err3, Exp memory newInterestIndexExp) = mulScalar(
onePlusBlocksTimesRate,
startingInterestIndex
);
if (err3 != Error.NO_ERROR) {
return (err3, 0);
}
// Finally, truncate the interest index. This works only if interest index starts large enough
// that is can be accurately represented with a whole number.
return (Error.NO_ERROR, truncate(newInterestIndexExp));
}
/**
* @dev Calculates a new balance based on a previous balance and a pair of interest indices
* This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex
* value and divided by the user's checkpoint index value`
* @return Return value is expressed in 1e18 scale
*/
function calculateBalance(
uint256 startingBalance,
uint256 interestIndexStart,
uint256 interestIndexEnd
) internal pure returns (Error, uint256) {
if (startingBalance == 0) {
// We are accumulating interest on any previous balance; if there's no previous balance, then there is
// nothing to accumulate.
return (Error.NO_ERROR, 0);
}
(Error err0, uint256 balanceTimesIndex) = mul(
startingBalance,
interestIndexEnd
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return div(balanceTimesIndex, interestIndexStart);
}
/**
* @dev Gets the price for the amount specified of the given asset.
* @return Return value is expressed in a magnified scale per token decimals
*/
function getPriceForAssetAmount(address asset, uint256 assetAmount)
internal
view
returns (Error, Exp memory)
{
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
if (isZeroExp(assetPrice)) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth
}
/**
* @dev Gets the price for the amount specified of the given asset multiplied by the current
* collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth).
* We will group this as `(oraclePrice * collateralRatio) * assetAmountWei`
* @return Return value is expressed in a magnified scale per token decimals
*/
function getPriceForAssetAmountMulCollatRatio(
address asset,
uint256 assetAmount
) internal view returns (Error, Exp memory) {
Error err;
Exp memory assetPrice;
Exp memory scaledPrice;
(err, assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
if (isZeroExp(assetPrice)) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
// Now, multiply the assetValue by the collateral ratio
(err, scaledPrice) = mulExp(collateralRatio, assetPrice);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
// Get the price for the given asset amount
return mulScalar(scaledPrice, assetAmount);
}
/**
* @dev Calculates the origination fee added to a given borrowAmount
* This is simply `(1 + originationFee) * borrowAmount`
* @return Return value is expressed in 1e18 scale
*/
function calculateBorrowAmountWithFee(uint256 borrowAmount)
internal
view
returns (Error, uint256)
{
// When origination fee is zero, the amount with fee is simply equal to the amount
if (isZeroExp(originationFee)) {
return (Error.NO_ERROR, borrowAmount);
}
(Error err0, Exp memory originationFeeFactor) = addExp(
originationFee,
Exp({mantissa: mantissaOne})
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
(Error err1, Exp memory borrowAmountWithFee) = mulScalar(
originationFeeFactor,
borrowAmount
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
return (Error.NO_ERROR, truncate(borrowAmountWithFee));
}
/**
* @dev fetches the price of asset from the PriceOracle and converts it to Exp
* @param asset asset whose price should be fetched
* @return Return value is expressed in a magnified scale per token decimals
*/
function fetchAssetPrice(address asset)
internal
view
returns (Error, Exp memory)
{
if (priceOracle == address(0)) {
return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0}));
}
if (priceOracle.paused()) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
(uint256 priceMantissa, uint8 assetDecimals) = priceOracle
.getAssetPrice(asset);
(Error err, uint256 magnification) = sub(18, uint256(assetDecimals));
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
(err, priceMantissa) = mul(priceMantissa, 10**magnification);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: priceMantissa}));
}
/**
* @notice Reads scaled price of specified asset from the price oracle
* @dev Reads scaled price of specified asset from the price oracle.
* The plural name is to match a previous storage mapping that this function replaced.
* @param asset Asset whose price should be retrieved
* @return 0 on an error or missing price, the price scaled by 1e18 otherwise
*/
function assetPrices(address asset) public view returns (uint256) {
(Error err, Exp memory result) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return 0;
}
return result.mantissa;
}
/**
* @dev Gets the amount of the specified asset given the specified Eth value
* ethValue / oraclePrice = assetAmountWei
* If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0)
* @return Return value is expressed in a magnified scale per token decimals
*/
function getAssetAmountForValue(address asset, Exp ethValue)
internal
view
returns (Error, uint256)
{
Error err;
Exp memory assetPrice;
Exp memory assetAmount;
(err, assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, assetAmount) = divExp(ethValue, assetPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(assetAmount));
}
/**
* @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin
* @param newOracle New oracle address
* @param requestedState value to assign to `paused`
* @param originationFeeMantissa rational collateral ratio, scaled by 1e18.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _adminFunctions(
address newPendingAdmin,
address newOracle,
bool requestedState,
uint256 originationFeeMantissa,
uint256 newCloseFactorMantissa
) public returns (uint256) {
// Check caller = admin
require(msg.sender == admin, "SET_PENDING_ADMIN_OWNER_CHECK");
// newPendingAdmin can be 0x00, hence not checked
require(newOracle != address(0), "Cannot set weth address to 0x00");
require(
originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18,
"Invalid Origination Fee or Close Factor Mantissa"
);
// Store pendingAdmin = newPendingAdmin
pendingAdmin = newPendingAdmin;
// Verify contract at newOracle address supports assetPrices call.
// This will revert if it doesn't.
// ChainLink priceOracleTemp = ChainLink(newOracle);
// priceOracleTemp.getAssetPrice(address(0));
// Initialize the Chainlink contract in priceOracle
priceOracle = ChainLink(newOracle);
paused = requestedState;
// Save current value so we can emit it in log.
Exp memory oldOriginationFee = originationFee;
originationFee = Exp({mantissa: originationFeeMantissa});
emit NewOriginationFee(
oldOriginationFee.mantissa,
originationFeeMantissa
);
closeFactorMantissa = newCloseFactorMantissa;
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint256) {
// Check caller = pendingAdmin
// msg.sender can't be zero
require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK");
// Save current value for inclusion in log
address oldAdmin = admin;
// Store admin = pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = 0;
emit NewAdmin(oldAdmin, msg.sender);
return uint256(Error.NO_ERROR);
}
/**
* @notice returns the liquidity for given account.
* a positive result indicates ability to borrow, whereas
* a negative result indicates a shortfall which may be liquidated
* @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0
* note: this includes interest trued up on all balances
* @param account the account to examine
* @return signed integer in terms of eth-wei (negative indicates a shortfall)
*/
function getAccountLiquidity(address account) public view returns (int256) {
(
Error err,
Exp memory accountLiquidity,
Exp memory accountShortfall
) = calculateAccountLiquidity(account);
revertIfError(err);
if (isZeroExp(accountLiquidity)) {
return -1 * int256(truncate(accountShortfall));
} else {
return int256(truncate(accountLiquidity));
}
}
/**
* @notice return supply balance with any accumulated interest for `asset` belonging to `account`
* @dev returns supply balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose supply balance belonging to `account` should be checked
* @return uint supply balance on success, throws on failed assertion otherwise
*/
function getSupplyBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[account][asset];
// Calculate the newSupplyIndex, needed to calculate user's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
newSupplyIndex
);
revertIfError(err);
return userSupplyCurrent;
}
/**
* @notice return borrow balance with any accumulated interest for `asset` belonging to `account`
* @dev returns borrow balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose borrow balance belonging to `account` should be checked
* @return uint borrow balance on success, throws on failed assertion otherwise
*/
function getBorrowBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[account][asset];
// Calculate the newBorrowIndex, needed to calculate user's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
newBorrowIndex
);
revertIfError(err);
return userBorrowCurrent;
}
/**
* @notice Supports a given market (asset) for use
* @dev Admin function to add support for a market
* @param asset Asset to support; MUST already have a non-zero price set
* @param interestRateModel InterestRateModel to use for the asset
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _supportMarket(address asset, InterestRateModel interestRateModel)
public
returns (uint256)
{
// Check caller = admin
require(msg.sender == admin, "SUPPORT_MARKET_OWNER_CHECK");
require(interestRateModel != address(0), "Rate Model cannot be 0x00");
// Hard cap on the maximum number of markets allowed
require(
collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED
"Exceeding the max number of markets allowed"
);
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED);
}
if (isZeroExp(assetPrice)) {
return
fail(
Error.ASSET_NOT_PRICED,
FailureInfo.SUPPORT_MARKET_PRICE_CHECK
);
}
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
// Append asset to collateralAssets if not set
addCollateralMarket(asset);
// Set market isSupported to true
markets[asset].isSupported = true;
// Default supply and borrow index to 1e18
if (markets[asset].supplyIndex == 0) {
markets[asset].supplyIndex = initialInterestIndex;
}
if (markets[asset].borrowIndex == 0) {
markets[asset].borrowIndex = initialInterestIndex;
}
emit SupportedMarket(asset, interestRateModel);
return uint256(Error.NO_ERROR);
}
/**
* @notice Suspends a given *supported* market (asset) from use.
* Assets in this state do count for collateral, but users may only withdraw, payBorrow,
* and liquidate the asset. The liquidate function no longer checks collateralization.
* @dev Admin function to suspend a market
* @param asset Asset to suspend
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _suspendMarket(address asset) public returns (uint256) {
// Check caller = admin
require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK");
// If the market is not configured at all, we don't want to add any configuration for it.
// If we find !markets[asset].isSupported then either the market is not configured at all, or it
// has already been marked as unsupported. We can just return without doing anything.
// Caller is responsible for knowing the difference between not-configured and already unsupported.
if (!markets[asset].isSupported) {
return uint256(Error.NO_ERROR);
}
// If we get here, we know market is configured and is supported, so set isSupported to false
markets[asset].isSupported = false;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the risk parameters: collateral ratio and liquidation discount
* @dev Owner function to set the risk parameters
* @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1
* @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setRiskParameters(
uint256 collateralRatioMantissa,
uint256 liquidationDiscountMantissa
) public returns (uint256) {
// Check caller = admin
require(msg.sender == admin, "SET_RISK_PARAMETERS_OWNER_CHECK");
// Input validations
require(
collateralRatioMantissa >= minimumCollateralRatioMantissa &&
liquidationDiscountMantissa <=
maximumLiquidationDiscountMantissa,
"Liquidation discount is more than max discount or collateral ratio is less than min ratio"
);
Exp memory newCollateralRatio = Exp({
mantissa: collateralRatioMantissa
});
Exp memory newLiquidationDiscount = Exp({
mantissa: liquidationDiscountMantissa
});
Exp memory minimumCollateralRatio = Exp({
mantissa: minimumCollateralRatioMantissa
});
Exp memory maximumLiquidationDiscount = Exp({
mantissa: maximumLiquidationDiscountMantissa
});
Error err;
Exp memory newLiquidationDiscountPlusOne;
// Make sure new collateral ratio value is not below minimum value
if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) {
return
fail(
Error.INVALID_COLLATERAL_RATIO,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the
// existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential.
if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) {
return
fail(
Error.INVALID_LIQUIDATION_DISCOUNT,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount`
// C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount`
(err, newLiquidationDiscountPlusOne) = addExp(
newLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size
if (
lessThanOrEqualExp(
newCollateralRatio,
newLiquidationDiscountPlusOne
)
) {
return
fail(
Error.INVALID_COMBINED_RISK_PARAMETERS,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Save current values so we can emit them in log.
Exp memory oldCollateralRatio = collateralRatio;
Exp memory oldLiquidationDiscount = liquidationDiscount;
// Store new values
collateralRatio = newCollateralRatio;
liquidationDiscount = newLiquidationDiscount;
emit NewRiskParameters(
oldCollateralRatio.mantissa,
collateralRatioMantissa,
oldLiquidationDiscount.mantissa,
liquidationDiscountMantissa
);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the interest rate model for a given market
* @dev Admin function to set interest rate model
* @param asset Asset to support
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMarketInterestRateModel(
address asset,
InterestRateModel interestRateModel
) public returns (uint256) {
// Check caller = admin
require(
msg.sender == admin,
"SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK"
);
require(interestRateModel != address(0), "Rate Model cannot be 0x00");
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
emit SetMarketInterestRateModel(asset, interestRateModel);
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply
* @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply
* @param asset asset whose equity should be withdrawn
* @param amount amount of equity to withdraw; must not exceed equity available
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _withdrawEquity(address asset, uint256 amount)
public
returns (uint256)
{
// Check caller = admin
require(msg.sender == admin, "EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK");
// Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply.
// Get supply and borrows with interest accrued till the latest block
(
uint256 supplyWithInterest,
uint256 borrowWithInterest
) = getMarketBalances(asset);
(Error err0, uint256 equity) = addThenSub(
getCash(asset),
borrowWithInterest,
supplyWithInterest
);
if (err0 != Error.NO_ERROR) {
return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY);
}
if (amount > equity) {
return
fail(
Error.EQUITY_INSUFFICIENT_BALANCE,
FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset out of the protocol to the admin
Error err2 = doTransferOut(asset, admin, amount);
if (err2 != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return
fail(
err2,
FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED
);
}
} else {
withdrawEther(admin, amount); // send Ether to user
}
(, markets[asset].supplyRateMantissa) = markets[asset]
.interestRateModel
.getSupplyRate(
asset,
getCash(asset) - amount,
markets[asset].totalSupply
);
(, markets[asset].borrowRateMantissa) = markets[asset]
.interestRateModel
.getBorrowRate(
asset,
getCash(asset) - amount,
markets[asset].totalBorrows
);
//event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner)
emit EquityWithdrawn(asset, equity, amount, admin);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Set WETH token contract address
* @param wethContractAddress Enter the WETH token address
*/
function setWethAddress(address wethContractAddress)
public
returns (uint256)
{
// Check caller = admin
require(msg.sender == admin, "SET_WETH_ADDRESS_ADMIN_CHECK_FAILED");
require(
wethContractAddress != address(0),
"Cannot set weth address to 0x00"
);
wethAddress = wethContractAddress;
WETHContract = AlkemiWETH(wethAddress);
return uint256(Error.NO_ERROR);
}
/**
* @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user
* @return errors if any
* @param etherAmount Amount of ether to be converted to WETH
* @param user User account address
*/
function supplyEther(address user, uint256 etherAmount)
internal
returns (uint256)
{
user; // To silence the warning of unused local variable
if (wethAddress != address(0)) {
WETHContract.deposit.value(etherAmount)();
return uint256(Error.NO_ERROR);
} else {
return uint256(Error.WETH_ADDRESS_NOT_SET_ERROR);
}
}
/**
* @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason
* @param etherAmount Amount of ether to be sent back to user
* @param user User account address
*/
function revertEtherToUser(address user, uint256 etherAmount) internal {
if (etherAmount > 0) {
user.transfer(etherAmount);
}
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol
* @dev add amount of supported asset to msg.sender's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supply(address asset, uint256 amount)
public
payable
nonReentrant
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED);
}
refreshAlkSupplyIndex(asset, msg.sender, false);
Market storage market = markets[asset];
Balance storage balance = supplyBalances[msg.sender][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// Fail if market not supported
if (!market.isSupported) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED
);
}
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
// Fail gracefully if asset is not approved or has insufficient balance
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
amount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex (we already had newSupplyIndex)
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(msg.sender, msg.value);
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
emit SupplyReceived(
msg.sender,
asset,
amount,
localResults.startingBalance,
balance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice withdraw `amount` of `ether` from sender's account to sender's address
* @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender
* @param etherAmount Amount of ether to be converted to WETH
* @param user User account address
*/
function withdrawEther(address user, uint256 etherAmount)
internal
returns (uint256)
{
WETHContract.withdraw(user, etherAmount);
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraw `amount` of `asset` from sender's account to sender's address
* @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender
* @param asset The market asset to withdraw
* @param requestedAmount The amount to withdraw (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function withdraw(address asset, uint256 requestedAmount)
public
nonReentrant
returns (uint256)
{
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.WITHDRAW_CONTRACT_PAUSED
);
}
refreshAlkSupplyIndex(asset, msg.sender, false);
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[msg.sender][asset];
WithdrawLocalVars memory localResults; // Holds all our calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// We calculate the user's accountLiquidity and accountShortfall.
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent
if (requestedAmount == uint256(-1)) {
(err, localResults.withdrawCapacity) = getAssetAmountForValue(
asset,
localResults.accountLiquidity
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED);
}
localResults.withdrawAmount = min(
localResults.withdrawCapacity,
localResults.userSupplyCurrent
);
} else {
localResults.withdrawAmount = requestedAmount;
}
// From here on we should NOT use requestedAmount.
// Fail gracefully if protocol has insufficient cash
// If protocol has insufficient cash, the sub operation will underflow.
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = sub(
localResults.currentCash,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE
);
}
// We check that the amount is less than or equal to supplyCurrent
// If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW
(err, localResults.userSupplyUpdated) = sub(
localResults.userSupplyCurrent,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.INSUFFICIENT_BALANCE,
FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT
);
}
// We want to know the user's withdrawCapacity, denominated in the asset
// Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth)
// Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth
(err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount(
asset,
localResults.withdrawAmount
); // amount * oraclePrice = ethValueOfWithdrawal
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED);
}
// We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below)
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfWithdrawal
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply.
// Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
supplyBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event
supplyBalance.principal = localResults.userSupplyUpdated;
supplyBalance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, localResults.withdrawAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user
}
emit SupplyWithdrawn(
msg.sender,
asset,
localResults.withdrawAmount,
localResults.startingBalance,
supplyBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Gets the user's account liquidity and account shortfall balances. This includes
* any accumulated interest thus far but does NOT actually update anything in
* storage, it simply calculates the account liquidity and shortfall with liquidity being
* returned as the first Exp, ie (Error, accountLiquidity, accountShortfall).
* @return Return values are expressed in 1e18 scale
*/
function calculateAccountLiquidity(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
Error err;
Exp memory sumSupplyValuesMantissa;
Exp memory sumBorrowValuesMantissa;
(
err,
sumSupplyValuesMantissa,
sumBorrowValuesMantissa
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
Exp memory result;
Exp memory sumSupplyValuesFinal = Exp({
mantissa: sumSupplyValuesMantissa.mantissa
});
Exp memory sumBorrowValuesFinal; // need to apply collateral ratio
(err, sumBorrowValuesFinal) = mulExp(
collateralRatio,
Exp({mantissa: sumBorrowValuesMantissa.mantissa})
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall.
// else the user meets the collateral ratio and has account liquidity.
if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) {
// accountShortfall = borrows - supplies
(err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal);
assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, Exp({mantissa: 0}), result);
} else {
// accountLiquidity = supplies - borrows
(err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal);
assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, result, Exp({mantissa: 0}));
}
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValuesInternal(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
/** By definition, all collateralMarkets are those that contribute to the user's
* liquidity and shortfall so we need only loop through those markets.
* To handle avoiding intermediate negative results, we will sum all the user's
* supply balances and borrow balances (with collateral ratio) separately and then
* subtract the sums at the end.
*/
AccountValueLocalVars memory localResults; // Re-used for all intermediate results
localResults.sumSupplies = Exp({mantissa: 0});
localResults.sumBorrows = Exp({mantissa: 0});
Error err; // Re-used for all intermediate errors
localResults.collateralMarketsLength = collateralMarkets.length;
for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) {
localResults.assetAddress = collateralMarkets[i];
Market storage currentMarket = markets[localResults.assetAddress];
Balance storage supplyBalance = supplyBalances[userAddress][
localResults.assetAddress
];
Balance storage borrowBalance = borrowBalances[userAddress][
localResults.assetAddress
];
if (supplyBalance.principal > 0) {
// We calculate the newSupplyIndex and user’s supplyCurrent (includes interest)
(err, localResults.newSupplyIndex) = calculateInterestIndex(
currentMarket.supplyIndex,
currentMarket.supplyRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's supply balance with interest so let's multiply by the asset price to get the total value
(err, localResults.supplyTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userSupplyCurrent
); // supplyCurrent * oraclePrice = supplyValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of supplies
(err, localResults.sumSupplies) = addExp(
localResults.supplyTotalValue,
localResults.sumSupplies
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
if (borrowBalance.principal > 0) {
// We perform a similar actions to get the user's borrow balance
(err, localResults.newBorrowIndex) = calculateInterestIndex(
currentMarket.borrowIndex,
currentMarket.borrowRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's borrow balance with interest so let's multiply by the asset price to get the total value
(err, localResults.borrowTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userBorrowCurrent
); // borrowCurrent * oraclePrice = borrowValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of borrows
(err, localResults.sumBorrows) = addExp(
localResults.borrowTotalValue,
localResults.sumBorrows
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
}
return (
Error.NO_ERROR,
localResults.sumSupplies,
localResults.sumBorrows
);
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details),
* sum ETH value of supplies scaled by 10e18,
* sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValues(address userAddress)
public
view
returns (
uint256,
uint256,
uint256
)
{
(
Error err,
Exp memory supplyValue,
Exp memory borrowValue
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (uint256(err), 0, 0);
}
return (0, supplyValue.mantissa, borrowValue.mantissa);
}
/**
* @notice Users repay borrowed assets from their own address to the protocol.
* @param asset The market asset to repay
* @param amount The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(address asset, uint256 amount)
public
payable
nonReentrant
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.REPAY_BORROW_CONTRACT_PAUSED
);
}
refreshAlkBorrowIndex(asset, msg.sender, false);
PayBorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
uint256 reimburseAmount;
// If the user specifies -1 amount to repay (“max”), repayAmount =>
// the lesser of the senders ERC-20 balance and borrowCurrent
if (asset != wethAddress) {
if (amount == uint256(-1)) {
localResults.repayAmount = min(
getBalanceOf(asset, msg.sender),
localResults.userBorrowCurrent
);
} else {
localResults.repayAmount = amount;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (amount > localResults.userBorrowCurrent) {
localResults.repayAmount = localResults.userBorrowCurrent;
(err, reimburseAmount) = sub(
amount,
localResults.userBorrowCurrent
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults.repayAmount = amount;
}
}
// Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated`
// Note: this checks that repayAmount is less than borrowCurrent
(err, localResults.userBorrowUpdated) = sub(
localResults.userBorrowCurrent,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail gracefully if asset is not approved or has insufficient balance
// Note: this checks that repayAmount is less than or equal to their ERC-20 balance
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE
);
}
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(
localResults.currentCash,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(
msg.sender,
localResults.repayAmount
);
//Repay excess funds
if (reimburseAmount > 0) {
revertEtherToUser(msg.sender, reimburseAmount);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
asset,
msg.sender,
localResults.repayAmount,
market.supplyIndex
);
emit BorrowRepaid(
msg.sender,
asset,
localResults.repayAmount,
localResults.startingBalance,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice users repay all or some of an underwater borrow and receive collateral
* @param targetAccount The account whose borrow should be liquidated
* @param assetBorrow The market asset to repay
* @param assetCollateral The borrower's market asset to receive in exchange
* @param requestedAmountClose The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(
address targetAccount,
address assetBorrow,
address assetCollateral,
uint256 requestedAmountClose
) public payable returns (uint256) {
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.LIQUIDATE_CONTRACT_PAUSED
);
}
refreshAlkSupplyIndex(assetCollateral, targetAccount, false);
refreshAlkSupplyIndex(assetCollateral, msg.sender, false);
refreshAlkBorrowIndex(assetBorrow, targetAccount, false);
LiquidateLocalVars memory localResults;
// Copy these addresses into the struct for use with `emitLiquidationEvent`
// We'll use localResults.liquidator inside this function for clarity vs using msg.sender.
localResults.targetAccount = targetAccount;
localResults.assetBorrow = assetBorrow;
localResults.liquidator = msg.sender;
localResults.assetCollateral = assetCollateral;
Market storage borrowMarket = markets[assetBorrow];
Market storage collateralMarket = markets[assetCollateral];
Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[
targetAccount
][assetBorrow];
Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[
targetAccount
][assetCollateral];
// Liquidator might already hold some of the collateral asset
Balance storage supplyBalance_LiquidatorCollateralAsset
= supplyBalances[localResults.liquidator][assetCollateral];
uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls
Error err; // re-used for all intermediate errors
(err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED);
}
(err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow);
// If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice
assert(err == Error.NO_ERROR);
// We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset
(
err,
localResults.newBorrowIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.borrowIndex,
borrowMarket.borrowRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
err,
localResults.currentBorrowBalance_TargetUnderwaterAsset
) = calculateBalance(
borrowBalance_TargeUnderwaterAsset.principal,
borrowBalance_TargeUnderwaterAsset.interestIndex,
localResults.newBorrowIndex_UnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED
);
}
// We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset
(
err,
localResults.newSupplyIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.supplyIndex,
collateralMarket.supplyRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
(
err,
localResults.currentSupplyBalance_TargetCollateralAsset
) = calculateBalance(
supplyBalance_TargetCollateralAsset.principal,
supplyBalance_TargetCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Liquidator may or may not already have some collateral asset.
// If they do, we need to accumulate interest on it before adding the seized collateral to it.
// We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset
(
err,
localResults.currentSupplyBalance_LiquidatorCollateralAsset
) = calculateBalance(
supplyBalance_LiquidatorCollateralAsset.principal,
supplyBalance_LiquidatorCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated
// interest and then by adding the liquidator's accumulated interest.
// Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the target user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
collateralMarket.totalSupply,
localResults.currentSupplyBalance_TargetCollateralAsset,
supplyBalance_TargetCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the calling user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
localResults.newTotalSupply_ProtocolCollateralAsset,
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
supplyBalance_LiquidatorCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user
// This is equal to the lesser of
// 1. borrowCurrent; (already calculated)
// 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount:
// discountedRepayToEvenAmount=
// shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
// 3. discountedBorrowDenominatedCollateral
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
// Here we calculate item 3. discountedBorrowDenominatedCollateral =
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
(
err,
localResults.discountedBorrowDenominatedCollateral
) = calculateDiscountedBorrowDenominatedCollateral(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.currentSupplyBalance_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED
);
}
if (borrowMarket.isSupported) {
// Market is supported, so we calculate item 2 from above.
(
err,
localResults.discountedRepayToEvenAmount
) = calculateDiscountedRepayToEvenAmount(
targetAccount,
localResults.underwaterAssetPrice,
assetBorrow
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED
);
}
// We need to do a two-step min to select from all 3 values
// min1&3 = min(item 1, item 3)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
// min1&3&2 = min(min1&3, 2)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset,
localResults.discountedRepayToEvenAmount
);
} else {
// Market is not supported, so we don't need to calculate item 2.
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
}
// If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset
if (assetBorrow != wethAddress) {
if (requestedAmountClose == uint256(-1)) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (
requestedAmountClose >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
(err, localResults.reimburseAmount) = sub(
requestedAmountClose,
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
}
// From here on, no more use of `requestedAmountClose`
// Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset
if (
localResults.closeBorrowAmount_TargetUnderwaterAsset >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
return
fail(
Error.INVALID_CLOSE_AMOUNT_REQUESTED,
FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH
);
}
// seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount)
(
err,
localResults.seizeSupplyAmount_TargetCollateralAsset
) = calculateAmountSeize(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED
);
}
// We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol
// Fail gracefully if asset is not approved or has insufficient balance
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
err = checkTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We are going to repay the target user's borrow using the calling user's funds
// We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance,
// adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset.
// Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset`
(err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
// We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow
assert(err == Error.NO_ERROR);
// We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(
err,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
) = addThenSub(
borrowMarket.totalBorrows,
localResults.updatedBorrowBalance_TargetUnderwaterAsset,
borrowBalance_TargeUnderwaterAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET
);
}
// We need to calculate what the updated cash will be after we transfer in from liquidator
localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow);
(err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(
localResults.currentCash_ProtocolUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET
);
}
// The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow
// (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.)
// We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it.
(
err,
localResults.newSupplyIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.supplyIndex,
borrowMarket.supplyRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
rateCalculationResultCode,
localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getSupplyRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
(
rateCalculationResultCode,
localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getBorrowRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
// Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above.
// Now we need to calculate the borrow index.
// We don't need to calculate new rates for the collateral asset because we have not changed utilization:
// - accumulating interest on the target user's collateral does not change cash or borrows
// - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows.
(
err,
localResults.newBorrowIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.borrowIndex,
collateralMarket.borrowRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
// We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index
(err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub(
localResults.currentSupplyBalance_TargetCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance
// maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset
// which in turn limits seizeSupplyAmount_TargetCollateralAsset.
assert(err == Error.NO_ERROR);
// We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index
(
err,
localResults.updatedSupplyBalance_LiquidatorCollateralAsset
) = add(
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// We can't overflow here because if this would overflow, then we would have already overflowed above and failed
// with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
assert(err == Error.NO_ERROR);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save borrow market updates
borrowMarket.blockNumber = block.number;
borrowMarket.totalBorrows = localResults
.newTotalBorrows_ProtocolUnderwaterAsset;
// borrowMarket.totalSupply does not need to be updated
borrowMarket.supplyRateMantissa = localResults
.newSupplyRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset;
borrowMarket.borrowRateMantissa = localResults
.newBorrowRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset;
// Save collateral market updates
// We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply.
collateralMarket.blockNumber = block.number;
collateralMarket.totalSupply = localResults
.newTotalSupply_ProtocolCollateralAsset;
collateralMarket.supplyIndex = localResults
.newSupplyIndex_CollateralAsset;
collateralMarket.borrowIndex = localResults
.newBorrowIndex_CollateralAsset;
// Save user updates
localResults
.startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset
.principal; // save for use in event
borrowBalance_TargeUnderwaterAsset.principal = localResults
.updatedBorrowBalance_TargetUnderwaterAsset;
borrowBalance_TargeUnderwaterAsset.interestIndex = localResults
.newBorrowIndex_UnderwaterAsset;
localResults
.startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset
.principal; // save for use in event
supplyBalance_TargetCollateralAsset.principal = localResults
.updatedSupplyBalance_TargetCollateralAsset;
supplyBalance_TargetCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
localResults
.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset
.principal; // save for use in event
supplyBalance_LiquidatorCollateralAsset.principal = localResults
.updatedSupplyBalance_LiquidatorCollateralAsset;
supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == requestedAmountClose) {
uint256 supplyError = supplyEther(
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
//Repay excess funds
if (localResults.reimburseAmount > 0) {
revertEtherToUser(
localResults.liquidator,
localResults.reimburseAmount
);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.newSupplyIndex_UnderwaterAsset
);
emit BorrowLiquidated(
localResults.targetAccount,
localResults.assetBorrow,
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.liquidator,
localResults.assetCollateral,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
* If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed.
* Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO.
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedRepayToEvenAmount(
address targetAccount,
Exp memory underwaterAssetPrice,
address assetBorrow
) internal view returns (Error, uint256) {
Error err;
Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity
Exp memory accountShortfall_TargetUser;
Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount
Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1
Exp memory discountedPrice_UnderwaterAsset;
Exp memory rawResult;
// we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio
(
err,
_accountLiquidity,
accountShortfall_TargetUser
) = calculateAccountLiquidity(targetAccount);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, collateralRatioMinusLiquidationDiscount) = subExp(
collateralRatio,
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedCollateralRatioMinusOne) = subExp(
collateralRatioMinusLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedPrice_UnderwaterAsset) = mulExp(
underwaterAssetPrice,
discountedCollateralRatioMinusOne
);
// calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio
// discountedCollateralRatioMinusOne < collateralRatio
// so if underwaterAssetPrice * collateralRatio did not overflow then
// underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either
assert(err == Error.NO_ERROR);
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow);
Exp memory maxClose;
(err, maxClose) = mulScalar(
Exp({mantissa: closeFactorMantissa}),
borrowBalance
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset);
// It's theoretically possible an asset could have such a low price that it truncates to zero when discounted.
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedBorrowDenominatedCollateral(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 supplyCurrent_TargetCollateralAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end
// [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ]
Error err;
Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount)
Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral
Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow
Exp memory rawResult;
(err, onePlusLiquidationDiscount) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, supplyCurrentTimesOracleCollateral) = mulScalar(
collateralPrice,
supplyCurrent_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp(
onePlusLiquidationDiscount,
underwaterAssetPrice
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(
supplyCurrentTimesOracleCollateral,
onePlusLiquidationDiscountTimesOracleBorrow
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral
* @return Return values are expressed in 1e18 scale
*/
function calculateAmountSeize(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 closeBorrowAmount_TargetUnderwaterAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices:
// underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice
// re-used for all intermediate errors
Error err;
// (1+liquidationDiscount)
Exp memory liquidationMultiplier;
// assetPrice-of-underwaterAsset * (1+liquidationDiscount)
Exp memory priceUnderwaterAssetTimesLiquidationMultiplier;
// priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset
// or, expanded:
// underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset
Exp memory finalNumerator;
// finalNumerator / priceCollateral
Exp memory rawResult;
(err, liquidationMultiplier) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
// liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow.
assert(err == Error.NO_ERROR);
(err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(
underwaterAssetPrice,
liquidationMultiplier
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, finalNumerator) = mulScalar(
priceUnderwaterAssetTimesLiquidationMultiplier,
closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(finalNumerator, collateralPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param asset The market asset to borrow
* @param amount The amount to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(address asset, uint256 amount)
public
nonReentrant
returns (uint256)
{
if (paused) {
return
fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED);
}
refreshAlkBorrowIndex(asset, msg.sender, false);
BorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// Fail if market not supported
if (!market.isSupported) {
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.BORROW_MARKET_NOT_SUPPORTED
);
}
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// Calculate origination fee.
(err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee(
amount
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED
);
}
uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount;
// Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated`
(err, localResults.userBorrowUpdated) = add(
localResults.userBorrowCurrent,
localResults.borrowAmountWithFee
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// Check customer liquidity
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT
);
}
// Would the customer have a shortfall after this borrow (including origination fee)?
// We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity.
// This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity`
(
err,
localResults.ethValueOfBorrowAmountWithFee
) = getPriceForAssetAmountMulCollatRatio(
asset,
localResults.borrowAmountWithFee
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED);
}
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfBorrowAmountWithFee
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// Fail gracefully if protocol has insufficient cash
localResults.currentCash = getCash(asset);
// We need to calculate what the updated cash will be after we transfer out to the user
(err, localResults.updatedCash) = sub(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
// Note: we ignore error here and call this token insufficient cash
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
originationFeeBalance[msg.sender][asset] += orgFeeBalance;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, amount); // send Ether to user
}
emit BorrowTaken(
msg.sender,
asset,
amount,
localResults.startingBalance,
localResults.borrowAmountWithFee,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol
* @dev add amount of supported asset to admin's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supplyOriginationFeeAsAdmin(
address asset,
address user,
uint256 amount,
uint256 newSupplyIndex
) private {
refreshAlkSupplyIndex(asset, admin, false);
uint256 originationFeeRepaid = 0;
if (originationFeeBalance[user][asset] != 0) {
if (amount < originationFeeBalance[user][asset]) {
originationFeeRepaid = amount;
} else {
originationFeeRepaid = originationFeeBalance[user][asset];
}
Balance storage balance = supplyBalances[admin][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
originationFeeBalance[user][asset] -= originationFeeRepaid;
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
newSupplyIndex
);
revertIfError(err);
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
originationFeeRepaid
);
revertIfError(err);
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
markets[asset].totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
revertIfError(err);
// Save market updates
markets[asset].totalSupply = localResults.newTotalSupply;
// Save user updates
localResults.startingBalance = balance.principal;
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = newSupplyIndex;
emit SupplyOrgFeeAsAdmin(
admin,
asset,
originationFeeRepaid,
localResults.startingBalance,
localResults.userSupplyUpdated
);
}
}
/**
* @notice Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants
* @param _rewardControl The address of the underlying reward control contract
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function setRewardControlAddress(address _rewardControl)
external
returns (uint256)
{
// Check caller = admin
require(
msg.sender == admin,
"SET_REWARD_CONTROL_ADDRESS_ADMIN_CHECK_FAILED"
);
require(
address(rewardControl) != _rewardControl,
"The same Reward Control address"
);
require(
_rewardControl != address(0),
"RewardControl address cannot be empty"
);
rewardControl = RewardControlInterface(_rewardControl);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market
* @param market The address of the market to accrue rewards
* @param supplier The address of the supplier to accrue rewards
* @param isVerified Verified / Public protocol
*/
function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
) internal {
if (address(rewardControl) == address(0)) {
return;
}
rewardControl.refreshAlkSupplyIndex(market, supplier, isVerified);
}
/**
* @notice Trigger the underlying Reward Control contract to accrue ALK borrow rewards for the borrower on the specified market
* @param market The address of the market to accrue rewards
* @param borrower The address of the borrower to accrue rewards
* @param isVerified Verified / Public protocol
*/
function refreshAlkBorrowIndex(
address market,
address borrower,
bool isVerified
) internal {
if (address(rewardControl) == address(0)) {
return;
}
rewardControl.refreshAlkBorrowIndex(market, borrower, isVerified);
}
/**
* @notice Get supply and borrows for a market
* @param asset The market asset to find balances of
* @return updated supply and borrows
*/
function getMarketBalances(address asset)
public
view
returns (uint256, uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 marketSupplyCurrent;
uint256 newBorrowIndex;
uint256 marketBorrowCurrent;
Market storage market = markets[asset];
// Calculate the newSupplyIndex, needed to calculate market's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, marketSupplyCurrent) = calculateBalance(
market.totalSupply,
market.supplyIndex,
newSupplyIndex
);
revertIfError(err);
// Calculate the newBorrowIndex, needed to calculate market's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, marketBorrowCurrent) = calculateBalance(
market.totalBorrows,
market.borrowIndex,
newBorrowIndex
);
revertIfError(err);
return (marketSupplyCurrent, marketBorrowCurrent);
}
/**
* @dev Function to revert in case of an internal exception
*/
function revertIfError(Error err) internal pure {
require(
err == Error.NO_ERROR,
"Function revert due to internal exception"
);
}
}
// File: contracts/RewardControlStorage.sol
pragma solidity 0.4.24;
contract RewardControlStorage {
struct MarketState {
// @notice The market's last updated alkSupplyIndex or alkBorrowIndex
uint224 index;
// @notice The block number the index was last updated at
uint32 block;
}
// @notice A list of all markets in the reward program mapped to respective verified/public protocols
// @notice true => address[] represents Verified Protocol markets
// @notice false => address[] represents Public Protocol markets
mapping(bool => address[]) public allMarkets;
// @notice The index for checking whether a market is already in the reward program
// @notice The first mapping represents verified / public market and the second gives the existence of the market
mapping(bool => mapping(address => bool)) public allMarketsIndex;
// @notice The rate at which the Reward Control distributes ALK per block
uint256 public alkRate;
// @notice The portion of alkRate that each market currently receives
// @notice The first mapping represents verified / public market and the second gives the alkSpeeds
mapping(bool => mapping(address => uint256)) public alkSpeeds;
// @notice The ALK market supply state for each market
// @notice The first mapping represents verified / public market and the second gives the supplyState
mapping(bool => mapping(address => MarketState)) public alkSupplyState;
// @notice The ALK market borrow state for each market
// @notice The first mapping represents verified / public market and the second gives the borrowState
mapping(bool => mapping(address => MarketState)) public alkBorrowState;
// @notice The snapshot of ALK index for each market for each supplier as of the last time they accrued ALK
// @notice verified/public => market => supplier => supplierIndex
mapping(bool => mapping(address => mapping(address => uint256)))
public alkSupplierIndex;
// @notice The snapshot of ALK index for each market for each borrower as of the last time they accrued ALK
// @notice verified/public => market => borrower => borrowerIndex
mapping(bool => mapping(address => mapping(address => uint256)))
public alkBorrowerIndex;
// @notice The ALK accrued but not yet transferred to each participant
mapping(address => uint256) public alkAccrued;
// @notice To make sure initializer is called only once
bool public initializationDone;
// @notice The address of the current owner of this contract
address public owner;
// @notice The proposed address of the new owner of this contract
address public newOwner;
// @notice The underlying AlkemiEarnVerified contract
AlkemiEarnVerified public alkemiEarnVerified;
// @notice The underlying AlkemiEarnPublic contract
AlkemiEarnPublic public alkemiEarnPublic;
// @notice The ALK token address
address public alkAddress;
// Hard cap on the maximum number of markets
uint8 public MAXIMUM_NUMBER_OF_MARKETS;
}
// File: contracts/ExponentialNoError.sol
// Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a
pragma solidity 0.4.24;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint256 constant expScale = 1e18;
uint256 constant doubleScale = 1e36;
uint256 constant halfExpScale = expScale / 2;
uint256 constant mantissaOne = expScale;
struct Exp {
uint256 mantissa;
}
struct Double {
uint256 mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint256 scalar)
internal
pure
returns (uint256)
{
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
function safe224(uint256 n, string memory errorMessage)
internal
pure
returns (uint224)
{
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint256 a, uint256 b) internal pure returns (uint256) {
return add_(a, b, "addition overflow");
}
function add_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint256 a, uint256 b) internal pure returns (uint256) {
return sub_(a, b, "subtraction underflow");
}
function sub_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Exp memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Double memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint256 a, uint256 b) internal pure returns (uint256) {
return mul_(a, b, "multiplication overflow");
}
function mul_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Exp memory b) internal pure returns (uint256) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return
Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Double memory b) internal pure returns (uint256) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint256 a, uint256 b) internal pure returns (uint256) {
return div_(a, b, "divide by zero");
}
function div_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint256 a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// File: contracts/RewardControl.sol
pragma solidity 0.4.24;
contract RewardControl is
RewardControlStorage,
RewardControlInterface,
ExponentialNoError
{
/**
* Events
*/
/// @notice Emitted when a new ALK speed is calculated for a market
event AlkSpeedUpdated(
address indexed market,
uint256 newSpeed,
bool isVerified
);
/// @notice Emitted when ALK is distributed to a supplier
event DistributedSupplierAlk(
address indexed market,
address indexed supplier,
uint256 supplierDelta,
uint256 supplierAccruedAlk,
uint256 supplyIndexMantissa,
bool isVerified
);
/// @notice Emitted when ALK is distributed to a borrower
event DistributedBorrowerAlk(
address indexed market,
address indexed borrower,
uint256 borrowerDelta,
uint256 borrowerAccruedAlk,
uint256 borrowIndexMantissa,
bool isVerified
);
/// @notice Emitted when ALK is transferred to a participant
event TransferredAlk(
address indexed participant,
uint256 participantAccrued,
address market,
bool isVerified
);
/// @notice Emitted when the owner of the contract is updated
event OwnerUpdate(address indexed owner, address indexed newOwner);
/// @notice Emitted when a market is added
event MarketAdded(
address indexed market,
uint256 numberOfMarkets,
bool isVerified
);
/// @notice Emitted when a market is removed
event MarketRemoved(
address indexed market,
uint256 numberOfMarkets,
bool isVerified
);
/**
* Constants
*/
/**
* Constructor
*/
/**
* @notice `RewardControl` is the contract to calculate and distribute reward tokens
* @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies
* @notice Hence this contract has an 'initializer' in place of a 'constructor'
* @notice Make sure to add new global variables only in a derived contract of RewardControlStorage, inherited by this contract
* @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade
*/
function initializer(
address _owner,
address _alkemiEarnVerified,
address _alkemiEarnPublic,
address _alkAddress
) public {
require(
_owner != address(0) &&
_alkemiEarnVerified != address(0) &&
_alkemiEarnPublic != address(0) &&
_alkAddress != address(0),
"Inputs cannot be 0x00"
);
if (initializationDone == false) {
initializationDone = true;
owner = _owner;
alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified);
alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic);
alkAddress = _alkAddress;
// Total Liquidity rewards for 4 years = 70,000,000
// Liquidity per year = 70,000,000/4 = 17,500,000
// Divided by blocksPerYear (assuming 13.3 seconds avg. block time) = 17,500,000/2,371,128 = 7.380453522542860000
// 7380453522542860000 (Tokens scaled by token decimals of 18) divided by 2 (half for lending and half for borrowing)
alkRate = 3690226761271430000;
MAXIMUM_NUMBER_OF_MARKETS = 16;
}
}
/**
* Modifiers
*/
/**
* @notice Make sure that the sender is only the owner of the contract
*/
modifier onlyOwner() {
require(msg.sender == owner, "non-owner");
_;
}
/**
* Public functions
*/
/**
* @notice Refresh ALK supply index for the specified market and supplier
* @param market The market whose supply index to update
* @param supplier The address of the supplier to distribute ALK to
* @param isVerified Specifies if the market is from verified or public protocol
*/
function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
) external {
if (!allMarketsIndex[isVerified][market]) {
return;
}
refreshAlkSpeeds();
updateAlkSupplyIndex(market, isVerified);
distributeSupplierAlk(market, supplier, isVerified);
}
/**
* @notice Refresh ALK borrow index for the specified market and borrower
* @param market The market whose borrow index to update
* @param borrower The address of the borrower to distribute ALK to
* @param isVerified Specifies if the market is from verified or public protocol
*/
function refreshAlkBorrowIndex(
address market,
address borrower,
bool isVerified
) external {
if (!allMarketsIndex[isVerified][market]) {
return;
}
refreshAlkSpeeds();
updateAlkBorrowIndex(market, isVerified);
distributeBorrowerAlk(market, borrower, isVerified);
}
/**
* @notice Claim all the ALK accrued by holder in all markets
* @param holder The address to claim ALK for
*/
function claimAlk(address holder) external {
claimAlk(holder, allMarkets[true], true);
claimAlk(holder, allMarkets[false], false);
}
/**
* @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only
* @param holder The address to claim ALK for
* @param market The address of the market to refresh the indexes for
* @param isVerified Specifies if the market is from verified or public protocol
*/
function claimAlk(
address holder,
address market,
bool isVerified
) external {
require(allMarketsIndex[isVerified][market], "Market does not exist");
address[] memory markets = new address[](1);
markets[0] = market;
claimAlk(holder, markets, isVerified);
}
/**
* Private functions
*/
/**
* @notice Recalculate and update ALK speeds for all markets
*/
function refreshMarketLiquidity()
internal
view
returns (Exp[] memory, Exp memory)
{
Exp memory totalLiquidity = Exp({mantissa: 0});
Exp[] memory marketTotalLiquidity = new Exp[](
add_(allMarkets[true].length, allMarkets[false].length)
);
address currentMarket;
uint256 verifiedMarketsLength = allMarkets[true].length;
for (uint256 i = 0; i < allMarkets[true].length; i++) {
currentMarket = allMarkets[true][i];
uint256 currentMarketTotalSupply = mul_(
getMarketTotalSupply(currentMarket, true),
alkemiEarnVerified.assetPrices(currentMarket)
);
uint256 currentMarketTotalBorrows = mul_(
getMarketTotalBorrows(currentMarket, true),
alkemiEarnVerified.assetPrices(currentMarket)
);
Exp memory currentMarketTotalLiquidity = Exp({
mantissa: add_(
currentMarketTotalSupply,
currentMarketTotalBorrows
)
});
marketTotalLiquidity[i] = currentMarketTotalLiquidity;
totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity);
}
for (uint256 j = 0; j < allMarkets[false].length; j++) {
currentMarket = allMarkets[false][j];
currentMarketTotalSupply = mul_(
getMarketTotalSupply(currentMarket, false),
alkemiEarnVerified.assetPrices(currentMarket)
);
currentMarketTotalBorrows = mul_(
getMarketTotalBorrows(currentMarket, false),
alkemiEarnVerified.assetPrices(currentMarket)
);
currentMarketTotalLiquidity = Exp({
mantissa: add_(
currentMarketTotalSupply,
currentMarketTotalBorrows
)
});
marketTotalLiquidity[
verifiedMarketsLength + j
] = currentMarketTotalLiquidity;
totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity);
}
return (marketTotalLiquidity, totalLiquidity);
}
/**
* @notice Recalculate and update ALK speeds for all markets
*/
function refreshAlkSpeeds() public {
address currentMarket;
(
Exp[] memory marketTotalLiquidity,
Exp memory totalLiquidity
) = refreshMarketLiquidity();
uint256 newSpeed;
uint256 verifiedMarketsLength = allMarkets[true].length;
for (uint256 i = 0; i < allMarkets[true].length; i++) {
currentMarket = allMarkets[true][i];
newSpeed = totalLiquidity.mantissa > 0
? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity))
: 0;
alkSpeeds[true][currentMarket] = newSpeed;
emit AlkSpeedUpdated(currentMarket, newSpeed, true);
}
for (uint256 j = 0; j < allMarkets[false].length; j++) {
currentMarket = allMarkets[false][j];
newSpeed = totalLiquidity.mantissa > 0
? mul_(
alkRate,
div_(
marketTotalLiquidity[verifiedMarketsLength + j],
totalLiquidity
)
)
: 0;
alkSpeeds[false][currentMarket] = newSpeed;
emit AlkSpeedUpdated(currentMarket, newSpeed, false);
}
}
/**
* @notice Accrue ALK to the market by updating the supply index
* @param market The market whose supply index to update
* @param isVerified Verified / Public protocol
*/
function updateAlkSupplyIndex(address market, bool isVerified) public {
MarketState storage supplyState = alkSupplyState[isVerified][market];
uint256 marketSpeed = alkSpeeds[isVerified][market];
uint256 blockNumber = getBlockNumber();
uint256 deltaBlocks = sub_(blockNumber, uint256(supplyState.block));
if (deltaBlocks > 0 && marketSpeed > 0) {
uint256 marketTotalSupply = getMarketTotalSupply(
market,
isVerified
);
uint256 supplyAlkAccrued = mul_(deltaBlocks, marketSpeed);
Double memory ratio = marketTotalSupply > 0
? fraction(supplyAlkAccrued, marketTotalSupply)
: Double({mantissa: 0});
Double memory index = add_(
Double({mantissa: supplyState.index}),
ratio
);
alkSupplyState[isVerified][market] = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(
blockNumber,
"block number exceeds 32 bits"
);
}
}
/**
* @notice Accrue ALK to the market by updating the borrow index
* @param market The market whose borrow index to update
* @param isVerified Verified / Public protocol
*/
function updateAlkBorrowIndex(address market, bool isVerified) public {
MarketState storage borrowState = alkBorrowState[isVerified][market];
uint256 marketSpeed = alkSpeeds[isVerified][market];
uint256 blockNumber = getBlockNumber();
uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block));
if (deltaBlocks > 0 && marketSpeed > 0) {
uint256 marketTotalBorrows = getMarketTotalBorrows(
market,
isVerified
);
uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed);
Double memory ratio = marketTotalBorrows > 0
? fraction(borrowAlkAccrued, marketTotalBorrows)
: Double({mantissa: 0});
Double memory index = add_(
Double({mantissa: borrowState.index}),
ratio
);
alkBorrowState[isVerified][market] = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(
blockNumber,
"block number exceeds 32 bits"
);
}
}
/**
* @notice Calculate ALK accrued by a supplier and add it on top of alkAccrued[supplier]
* @param market The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function distributeSupplierAlk(
address market,
address supplier,
bool isVerified
) public {
MarketState storage supplyState = alkSupplyState[isVerified][market];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({
mantissa: alkSupplierIndex[isVerified][market][supplier]
});
alkSupplierIndex[isVerified][market][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa > 0) {
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint256 supplierBalance = getSupplyBalance(
market,
supplier,
isVerified
);
uint256 supplierDelta = mul_(supplierBalance, deltaIndex);
alkAccrued[supplier] = add_(alkAccrued[supplier], supplierDelta);
emit DistributedSupplierAlk(
market,
supplier,
supplierDelta,
alkAccrued[supplier],
supplyIndex.mantissa,
isVerified
);
}
}
/**
* @notice Calculate ALK accrued by a borrower and add it on top of alkAccrued[borrower]
* @param market The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function distributeBorrowerAlk(
address market,
address borrower,
bool isVerified
) public {
MarketState storage borrowState = alkBorrowState[isVerified][market];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({
mantissa: alkBorrowerIndex[isVerified][market][borrower]
});
alkBorrowerIndex[isVerified][market][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint256 borrowerBalance = getBorrowBalance(
market,
borrower,
isVerified
);
uint256 borrowerDelta = mul_(borrowerBalance, deltaIndex);
alkAccrued[borrower] = add_(alkAccrued[borrower], borrowerDelta);
emit DistributedBorrowerAlk(
market,
borrower,
borrowerDelta,
alkAccrued[borrower],
borrowIndex.mantissa,
isVerified
);
}
}
/**
* @notice Claim all the ALK accrued by holder in the specified markets
* @param holder The address to claim ALK for
* @param markets The list of markets to claim ALK in
* @param isVerified Verified / Public protocol
*/
function claimAlk(
address holder,
address[] memory markets,
bool isVerified
) internal {
for (uint256 i = 0; i < markets.length; i++) {
address market = markets[i];
updateAlkSupplyIndex(market, isVerified);
distributeSupplierAlk(market, holder, isVerified);
updateAlkBorrowIndex(market, isVerified);
distributeBorrowerAlk(market, holder, isVerified);
alkAccrued[holder] = transferAlk(
holder,
alkAccrued[holder],
market,
isVerified
);
}
}
/**
* @notice Transfer ALK to the participant
* @dev Note: If there is not enough ALK, we do not perform the transfer all.
* @param participant The address of the participant to transfer ALK to
* @param participantAccrued The amount of ALK to (possibly) transfer
* @param market Market for which ALK is transferred
* @param isVerified Verified / Public Protocol
* @return The amount of ALK which was NOT transferred to the participant
*/
function transferAlk(
address participant,
uint256 participantAccrued,
address market,
bool isVerified
) internal returns (uint256) {
if (participantAccrued > 0) {
EIP20Interface alk = EIP20Interface(getAlkAddress());
uint256 alkRemaining = alk.balanceOf(address(this));
if (participantAccrued <= alkRemaining) {
alk.transfer(participant, participantAccrued);
emit TransferredAlk(
participant,
participantAccrued,
market,
isVerified
);
return 0;
}
}
return participantAccrued;
}
/**
* Getters
*/
/**
* @notice Get the current block number
* @return The current block number
*/
function getBlockNumber() public view returns (uint256) {
return block.number;
}
/**
* @notice Get the current accrued ALK for a participant
* @param participant The address of the participant
* @return The amount of accrued ALK for the participant
*/
function getAlkAccrued(address participant) public view returns (uint256) {
return alkAccrued[participant];
}
/**
* @notice Get the address of the ALK token
* @return The address of ALK token
*/
function getAlkAddress() public view returns (address) {
return alkAddress;
}
/**
* @notice Get the address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract
* @return The address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract
*/
function getAlkemiEarnAddress() public view returns (address, address) {
return (address(alkemiEarnVerified), address(alkemiEarnPublic));
}
/**
* @notice Get market statistics from the AlkemiEarnVerified contract
* @param market The address of the market
* @param isVerified Verified / Public protocol
* @return Market statistics for the given market
*/
function getMarketStats(address market, bool isVerified)
public
view
returns (
bool isSupported,
uint256 blockNumber,
address interestRateModel,
uint256 totalSupply,
uint256 supplyRateMantissa,
uint256 supplyIndex,
uint256 totalBorrows,
uint256 borrowRateMantissa,
uint256 borrowIndex
)
{
if (isVerified) {
return (alkemiEarnVerified.markets(market));
} else {
return (alkemiEarnPublic.markets(market));
}
}
/**
* @notice Get market total supply from the AlkemiEarnVerified / AlkemiEarnPublic contract
* @param market The address of the market
* @param isVerified Verified / Public protocol
* @return Market total supply for the given market
*/
function getMarketTotalSupply(address market, bool isVerified)
public
view
returns (uint256)
{
uint256 totalSupply;
(, , , totalSupply, , , , , ) = getMarketStats(market, isVerified);
return totalSupply;
}
/**
* @notice Get market total borrows from the AlkemiEarnVerified contract
* @param market The address of the market
* @param isVerified Verified / Public protocol
* @return Market total borrows for the given market
*/
function getMarketTotalBorrows(address market, bool isVerified)
public
view
returns (uint256)
{
uint256 totalBorrows;
(, , , , , , totalBorrows, , ) = getMarketStats(market, isVerified);
return totalBorrows;
}
/**
* @notice Get supply balance of the specified market and supplier
* @param market The address of the market
* @param supplier The address of the supplier
* @param isVerified Verified / Public protocol
* @return Supply balance of the specified market and supplier
*/
function getSupplyBalance(
address market,
address supplier,
bool isVerified
) public view returns (uint256) {
if (isVerified) {
return alkemiEarnVerified.getSupplyBalance(supplier, market);
} else {
return alkemiEarnPublic.getSupplyBalance(supplier, market);
}
}
/**
* @notice Get borrow balance of the specified market and borrower
* @param market The address of the market
* @param borrower The address of the borrower
* @param isVerified Verified / Public protocol
* @return Borrow balance of the specified market and borrower
*/
function getBorrowBalance(
address market,
address borrower,
bool isVerified
) public view returns (uint256) {
if (isVerified) {
return alkemiEarnVerified.getBorrowBalance(borrower, market);
} else {
return alkemiEarnPublic.getBorrowBalance(borrower, market);
}
}
/**
* Admin functions
*/
/**
* @notice Transfer the ownership of this contract to the new owner. The ownership will not be transferred until the new owner accept it.
* @param _newOwner The address of the new owner
*/
function transferOwnership(address _newOwner) external onlyOwner {
require(_newOwner != owner, "TransferOwnership: the same owner.");
newOwner = _newOwner;
}
/**
* @notice Accept the ownership of this contract by the new owner
*/
function acceptOwnership() external {
require(
msg.sender == newOwner,
"AcceptOwnership: only new owner do this."
);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
/**
* @notice Add new market to the reward program
* @param market The address of the new market to be added to the reward program
* @param isVerified Verified / Public protocol
*/
function addMarket(address market, bool isVerified) external onlyOwner {
require(!allMarketsIndex[isVerified][market], "Market already exists");
require(
allMarkets[isVerified].length < uint256(MAXIMUM_NUMBER_OF_MARKETS),
"Exceeding the max number of markets allowed"
);
allMarketsIndex[isVerified][market] = true;
allMarkets[isVerified].push(market);
emit MarketAdded(
market,
add_(allMarkets[isVerified].length, allMarkets[!isVerified].length),
isVerified
);
}
/**
* @notice Remove a market from the reward program based on array index
* @param id The index of the `allMarkets` array to be removed
* @param isVerified Verified / Public protocol
*/
function removeMarket(uint256 id, bool isVerified) external onlyOwner {
if (id >= allMarkets[isVerified].length) {
return;
}
allMarketsIndex[isVerified][allMarkets[isVerified][id]] = false;
address removedMarket = allMarkets[isVerified][id];
for (uint256 i = id; i < allMarkets[isVerified].length - 1; i++) {
allMarkets[isVerified][i] = allMarkets[isVerified][i + 1];
}
allMarkets[isVerified].length--;
// reset the ALK speeds for the removed market and refresh ALK speeds
alkSpeeds[isVerified][removedMarket] = 0;
refreshAlkSpeeds();
emit MarketRemoved(
removedMarket,
add_(allMarkets[isVerified].length, allMarkets[!isVerified].length),
isVerified
);
}
/**
* @notice Set ALK token address
* @param _alkAddress The ALK token address
*/
function setAlkAddress(address _alkAddress) external onlyOwner {
require(alkAddress != _alkAddress, "The same ALK address");
require(_alkAddress != address(0), "ALK address cannot be empty");
alkAddress = _alkAddress;
}
/**
* @notice Set AlkemiEarnVerified contract address
* @param _alkemiEarnVerified The AlkemiEarnVerified contract address
*/
function setAlkemiEarnVerifiedAddress(address _alkemiEarnVerified)
external
onlyOwner
{
require(
address(alkemiEarnVerified) != _alkemiEarnVerified,
"The same AlkemiEarnVerified address"
);
require(
_alkemiEarnVerified != address(0),
"AlkemiEarnVerified address cannot be empty"
);
alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified);
}
/**
* @notice Set AlkemiEarnPublic contract address
* @param _alkemiEarnPublic The AlkemiEarnVerified contract address
*/
function setAlkemiEarnPublicAddress(address _alkemiEarnPublic)
external
onlyOwner
{
require(
address(alkemiEarnPublic) != _alkemiEarnPublic,
"The same AlkemiEarnPublic address"
);
require(
_alkemiEarnPublic != address(0),
"AlkemiEarnPublic address cannot be empty"
);
alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic);
}
/**
* @notice Set ALK rate
* @param _alkRate The ALK rate
*/
function setAlkRate(uint256 _alkRate) external onlyOwner {
alkRate = _alkRate;
}
/**
* @notice Get latest ALK rewards
* @param user the supplier/borrower
*/
function getAlkRewards(address user) external view returns (uint256) {
// Refresh ALK speeds
uint256 alkRewards = alkAccrued[user];
(
Exp[] memory marketTotalLiquidity,
Exp memory totalLiquidity
) = refreshMarketLiquidity();
uint256 verifiedMarketsLength = allMarkets[true].length;
for (uint256 i = 0; i < allMarkets[true].length; i++) {
alkRewards = add_(
alkRewards,
add_(
getSupplyAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
i,
i,
true
),
getBorrowAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
i,
i,
true
)
)
);
}
for (uint256 j = 0; j < allMarkets[false].length; j++) {
uint256 index = verifiedMarketsLength + j;
alkRewards = add_(
alkRewards,
add_(
getSupplyAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
index,
j,
false
),
getBorrowAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
index,
j,
false
)
)
);
}
return alkRewards;
}
/**
* @notice Get latest Supply ALK rewards
* @param totalLiquidity Total Liquidity of all markets
* @param marketTotalLiquidity Array of individual market liquidity
* @param user the supplier
* @param i index of the market in marketTotalLiquidity array
* @param j index of the market in the verified/public allMarkets array
* @param isVerified Verified / Public protocol
*/
function getSupplyAlkRewards(
Exp memory totalLiquidity,
Exp[] memory marketTotalLiquidity,
address user,
uint256 i,
uint256 j,
bool isVerified
) internal view returns (uint256) {
uint256 newSpeed = totalLiquidity.mantissa > 0
? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity))
: 0;
MarketState memory supplyState = alkSupplyState[isVerified][
allMarkets[isVerified][j]
];
if (
sub_(getBlockNumber(), uint256(supplyState.block)) > 0 &&
newSpeed > 0
) {
Double memory index = add_(
Double({mantissa: supplyState.index}),
(
getMarketTotalSupply(
allMarkets[isVerified][j],
isVerified
) > 0
? fraction(
mul_(
sub_(
getBlockNumber(),
uint256(supplyState.block)
),
newSpeed
),
getMarketTotalSupply(
allMarkets[isVerified][j],
isVerified
)
)
: Double({mantissa: 0})
)
);
supplyState = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
} else if (sub_(getBlockNumber(), uint256(supplyState.block)) > 0) {
supplyState.block = safe32(
getBlockNumber(),
"block number exceeds 32 bits"
);
}
if (
isVerified &&
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0
) {
return
mul_(
alkemiEarnVerified.getSupplyBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: supplyState.index}),
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
}
if (
!isVerified &&
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0
) {
return
mul_(
alkemiEarnPublic.getSupplyBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: supplyState.index}),
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
} else {
return 0;
}
}
/**
* @notice Get latest Borrow ALK rewards
* @param totalLiquidity Total Liquidity of all markets
* @param marketTotalLiquidity Array of individual market liquidity
* @param user the borrower
* @param i index of the market in marketTotalLiquidity array
* @param j index of the market in the verified/public allMarkets array
* @param isVerified Verified / Public protocol
*/
function getBorrowAlkRewards(
Exp memory totalLiquidity,
Exp[] memory marketTotalLiquidity,
address user,
uint256 i,
uint256 j,
bool isVerified
) internal view returns (uint256) {
uint256 newSpeed = totalLiquidity.mantissa > 0
? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity))
: 0;
MarketState memory borrowState = alkBorrowState[isVerified][
allMarkets[isVerified][j]
];
if (
sub_(getBlockNumber(), uint256(borrowState.block)) > 0 &&
newSpeed > 0
) {
Double memory index = add_(
Double({mantissa: borrowState.index}),
(
getMarketTotalBorrows(
allMarkets[isVerified][j],
isVerified
) > 0
? fraction(
mul_(
sub_(
getBlockNumber(),
uint256(borrowState.block)
),
newSpeed
),
getMarketTotalBorrows(
allMarkets[isVerified][j],
isVerified
)
)
: Double({mantissa: 0})
)
);
borrowState = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
} else if (sub_(getBlockNumber(), uint256(borrowState.block)) > 0) {
borrowState.block = safe32(
getBlockNumber(),
"block number exceeds 32 bits"
);
}
if (
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0 &&
isVerified
) {
return
mul_(
alkemiEarnVerified.getBorrowBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: borrowState.index}),
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
}
if (
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0 &&
!isVerified
) {
return
mul_(
alkemiEarnPublic.getBorrowBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: borrowState.index}),
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
} else {
return 0;
}
}
}
|
* By definition, all collateralMarkets are those that contribute to the user's liquidity and shortfall so we need only loop through those markets. To handle avoiding intermediate negative results, we will sum all the user's supply balances and borrow balances (with collateral ratio) separately and then subtract the sums at the end./
|
localResults.sumSupplies = Exp({mantissa: 0});
| 81,046 |
[
1,
858,
2379,
16,
777,
4508,
2045,
287,
3882,
2413,
854,
5348,
716,
356,
887,
358,
326,
729,
1807,
4501,
372,
24237,
471,
3025,
25602,
1427,
732,
1608,
1338,
2798,
3059,
5348,
2267,
2413,
18,
2974,
1640,
4543,
310,
12110,
6092,
1686,
16,
732,
903,
2142,
777,
326,
729,
1807,
14467,
324,
26488,
471,
29759,
324,
26488,
261,
1918,
4508,
2045,
287,
7169,
13,
18190,
471,
1508,
10418,
326,
26608,
622,
326,
679,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
1191,
3447,
18,
1364,
3088,
5259,
273,
7784,
12590,
81,
970,
21269,
30,
374,
22938,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract ERC20AtlasManager is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public constant HYN_ADDRESS = IERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
mapping(bytes32 => bool) public usedEvents_;
event Locked(
address indexed token,
address indexed sender,
uint256 amount,
address recipient
);
event Unlocked(
address token,
uint256 amount,
address recipient,
bytes32 receiptId
);
address public wallet;
modifier onlyWallet {
require(msg.sender == wallet, "AtlasManager/not-authorized");
_;
}
/**
* @dev constructor
* @param _wallet is the multisig wallet
*/
constructor(address _wallet) public {
wallet = _wallet;
}
/**
* @dev lock tokens to be minted on heco chain
* @param hynTokenAddr is the atlas token contract address
* @param amount amount of tokens to lock
* @param recipient recipient address on the heco chain
*/
function lockToken(
address hynTokenAddr,
uint256 amount,
address recipient
) public {
require(
recipient != address(0),
"AtlasManager/recipient is a zero address"
);
require(amount > 0, "AtlasManager/zero token locked");
IERC20 hynToken = IERC20(hynTokenAddr);
uint256 _balanceBefore = hynToken.balanceOf(msg.sender);
hynToken.safeTransferFrom(msg.sender, address(this), amount);
uint256 _balanceAfter = hynToken.balanceOf(msg.sender);
uint256 _actualAmount = _balanceBefore.sub(_balanceAfter);
emit Locked(address(hynToken), msg.sender, _actualAmount, recipient);
}
/**
* @dev lock tokens for a user address to be minted on heco chain
* @param hynTokenAddr is the atlas token contract address
* @param userAddr is token holder address
* @param amount amount of tokens to lock
* @param recipient recipient address on the heco chain
*/
function lockTokenFor(
address hynTokenAddr,
address userAddr,
uint256 amount,
address recipient
) public onlyWallet {
require(
recipient != address(0),
"AtlasManager/recipient is a zero address"
);
require(amount > 0, "AtlasManager/zero token locked");
IERC20 hynToken = IERC20(hynTokenAddr);
uint256 _balanceBefore = hynToken.balanceOf(userAddr);
hynToken.safeTransferFrom(userAddr, address(this), amount);
uint256 _balanceAfter = hynToken.balanceOf(userAddr);
uint256 _actualAmount = _balanceBefore.sub(_balanceAfter);
emit Locked(address(hynToken), userAddr, _actualAmount, recipient);
}
/**
* @dev unlock tokens after burning them on heco chain
* @param hynTokenAddr is the atlas token contract address
* @param amount amount of unlock tokens
* @param recipient recipient of the unlock tokens
* @param receiptId transaction hash of the burn event on heco chain
*/
function unlockToken(
address hynTokenAddr,
uint256 amount,
address recipient,
bytes32 receiptId
) public onlyWallet {
require(
!usedEvents_[receiptId],
"AtlasManager/The burn event cannot be reused"
);
IERC20 hynToken = IERC20(hynTokenAddr);
usedEvents_[receiptId] = true;
hynToken.safeTransfer(recipient, amount);
emit Unlocked(hynTokenAddr, amount, recipient, receiptId);
}
/**
* @dev lock HYNs to be minted on heco chain
* @param amount amount of tokens to lock
* @param recipient recipient address on the harmony chain
*/
function lockHyn(
uint256 amount,
address recipient
) public payable {
require(
recipient != address(0),
"AtlasManager/recipient is a zero address"
);
require(msg.value == amount, "HynManager/zero token locked");
emit Locked(address(HYN_ADDRESS), msg.sender, amount, recipient);
}
/**
* @dev unlock HYNs after burning them on heco chain
* @param amount amount of unlock tokens
* @param recipient recipient of the unlock tokens
* @param receiptId transaction hash of the burn event on harmony chain
*/
function unlockHyn(
uint256 amount,
address payable recipient,
bytes32 receiptId
) public onlyWallet {
require(
!usedEvents_[receiptId],
"AtlasManager/The burn event cannot be reused"
);
usedEvents_[receiptId] = true;
recipient.transfer(amount);
emit Unlocked(address(HYN_ADDRESS), amount, recipient, receiptId);
}
}
|
* @dev unlock HYNs after burning them on heco chain @param amount amount of unlock tokens @param recipient recipient of the unlock tokens @param receiptId transaction hash of the burn event on harmony chain/
|
function unlockHyn(
uint256 amount,
address payable recipient,
bytes32 receiptId
) public onlyWallet {
require(
!usedEvents_[receiptId],
"AtlasManager/The burn event cannot be reused"
);
usedEvents_[receiptId] = true;
recipient.transfer(amount);
emit Unlocked(address(HYN_ADDRESS), amount, recipient, receiptId);
}
| 13,109,938 |
[
1,
26226,
29684,
10386,
1839,
18305,
310,
2182,
603,
366,
557,
83,
2687,
225,
3844,
3844,
434,
7186,
2430,
225,
8027,
8027,
434,
326,
7186,
2430,
225,
16030,
548,
2492,
1651,
434,
326,
18305,
871,
603,
17895,
2586,
93,
2687,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7186,
44,
878,
12,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1758,
8843,
429,
8027,
16,
203,
3639,
1731,
1578,
16030,
548,
203,
565,
262,
1071,
1338,
16936,
288,
203,
3639,
2583,
12,
203,
5411,
401,
3668,
3783,
67,
63,
8606,
8138,
548,
6487,
203,
5411,
315,
861,
9521,
1318,
19,
1986,
18305,
871,
2780,
506,
23312,
6,
203,
3639,
11272,
203,
3639,
1399,
3783,
67,
63,
8606,
8138,
548,
65,
273,
638,
31,
203,
3639,
8027,
18,
13866,
12,
8949,
1769,
203,
3639,
3626,
3967,
329,
12,
2867,
12,
44,
17317,
67,
15140,
3631,
3844,
16,
8027,
16,
16030,
548,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xe5d0c26C2E427b32B6daA2CFCf41E9A189ee6d93/sources/tests.sol
|
Wrapped(tokens[tokens.length - 1]).withdraw(minerFee); block.coinbase.transfer(minerFee);
|
function capitalClosingSwap(bytes calldata _data, uint id, uint bribe) external {
(address[] memory pools,uint8[] memory dexType, uint8[] memory dexMeta, , address[] memory tokens) = decodeCapital1(_data);
uint cost= _positions[id][tokens[tokens.length - 1]];
uint112 amountIn = uint112(_positions[id][tokens[0]]);
require(cost>0,"CA");
require (amountIn>0,"CB");
(uint[] memory valid,) = getAmountsOut(amountIn, pools,dexType,dexMeta);
require(cost < valid[valid.length - 1],"cc");
isTrader();
if(dexType[0]<2)
IERC20(tokens[0]).transfer(pools[0], amountIn);
_swap(pools, valid, dexType, dexMeta, address(this));
uint profit = (valid[valid.length -1] - cost );
uint minerFee = (profit - 1) * bribe / 100000;
emit flashbots(profit,minerFee, profit - minerFee);
}
| 9,684,550 |
[
1,
17665,
12,
7860,
63,
7860,
18,
2469,
300,
404,
65,
2934,
1918,
9446,
12,
1154,
264,
14667,
1769,
3639,
1203,
18,
12645,
1969,
18,
13866,
12,
1154,
264,
14667,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
12872,
15745,
12521,
12,
3890,
745,
892,
389,
892,
16,
2254,
612,
16,
2254,
324,
1902,
13,
3903,
288,
203,
3639,
261,
2867,
8526,
3778,
16000,
16,
11890,
28,
8526,
3778,
302,
338,
559,
16,
2254,
28,
8526,
3778,
302,
338,
2781,
16,
269,
1758,
8526,
3778,
2430,
13,
273,
2495,
4664,
7053,
21,
24899,
892,
1769,
203,
3639,
2254,
6991,
33,
389,
12388,
63,
350,
6362,
7860,
63,
7860,
18,
2469,
300,
404,
13563,
31,
203,
3639,
2254,
17666,
3844,
382,
273,
2254,
17666,
24899,
12388,
63,
350,
6362,
7860,
63,
20,
13563,
1769,
203,
3639,
2583,
12,
12398,
34,
20,
10837,
3587,
8863,
203,
3639,
2583,
261,
8949,
382,
34,
20,
10837,
8876,
8863,
203,
3639,
261,
11890,
8526,
3778,
923,
16,
13,
273,
24418,
87,
1182,
12,
8949,
382,
16,
16000,
16,
561,
559,
16,
561,
2781,
1769,
203,
203,
3639,
2583,
12,
12398,
411,
923,
63,
877,
18,
2469,
300,
404,
6487,
6,
952,
8863,
203,
203,
3639,
353,
1609,
765,
5621,
203,
203,
3639,
309,
12,
561,
559,
63,
20,
65,
32,
22,
13,
203,
5411,
467,
654,
39,
3462,
12,
7860,
63,
20,
65,
2934,
13866,
12,
27663,
63,
20,
6487,
3844,
382,
1769,
203,
203,
3639,
389,
22270,
12,
27663,
16,
923,
16,
302,
338,
559,
16,
302,
338,
2781,
16,
1758,
12,
2211,
10019,
203,
3639,
2254,
450,
7216,
273,
261,
877,
63,
877,
18,
2469,
300,
21,
65,
300,
6991,
11272,
203,
3639,
2254,
1131,
264,
14667,
273,
261,
685,
7216,
300,
404,
2
] |
pragma solidity 0.4.25;
/*
__ __ ___ ______
/\ \ __/\ \ /\_ \ /\__ _\
\ \ \/\ \ \ \ __\//\ \ ___ ___ ___ ___ __ \/_/\ \/ ___
\ \ \ \ \ \ \ /'__`\\ \ \ /'___\ / __`\ /' __` __`\ /'__`\ \ \ \ / __`\
\ \ \_/ \_\ \/\ __/ \_\ \_/\ \__//\ \L\ \/\ \/\ \/\ \/\ __/ \ \ \/\ \L\ \__ __ __
\ `\___x___/\ \____\/\____\ \____\ \____/\ \_\ \_\ \_\ \____\ \ \_\ \____/\_\/\_\/\_\
'\/__//__/ \/____/\/____/\/____/\/___/ \/_/\/_/\/_/\/____/ \/_/\/___/\/_/\/_/\/_/
__/\\\\\\\\\\\\\\\__/\\\\\\\\\\\\\\\__/\\\________/\\\_____/\\\\\\\\\____
_\/\\\///////////__\///////\\\/////__\/\\\_____/\\\//____/\\\\\\\\\\\\\__
_\/\\\___________________\/\\\_______\/\\\__/\\\//______/\\\/////////\\\_
_\/\\\\\\\\\\\___________\/\\\_______\/\\\\\\//\\\_____\/\\\_______\/\\\_
_\/\\\///////____________\/\\\_______\/\\\//_\//\\\____\/\\\\\\\\\\\\\\\_
_\/\\\___________________\/\\\_______\/\\\____\//\\\___\/\\\/////////\\\_
_\/\\\___________________\/\\\_______\/\\\_____\//\\\__\/\\\_______\/\\\_
_\/\\\___________________\/\\\_______\/\\\______\//\\\_\/\\\_______\/\\\_
_\///____________________\///________\///________\///__\///________\///__
// ----------------------------------------------------------------------------
// 'FTKA' token contract, having Crowdsale and Reward functionality
//
// Contract Owner : 0xef9EcD8a0A2E4b31d80B33E243761f4D93c990a8
// Symbol : FTKA
// Name : FTKA
// Total supply : 1,000,000,000 (1 Billion)
// Tokens for ICO : 800,000,000 (800 Million)
// Tokens to Owner: 200,000,000 (200 Million)
// Decimals : 8
//
// Copyright © 2018 onwards FTKA. (https://ftka.io)
// Contract designed by EtherAuthority (https://EtherAuthority.io)
// ----------------------------------------------------------------------------
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract owned {
address public owner;
constructor () public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
// Public variables of the token
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals = 8; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
uint256 public reservedForICO;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor (
uint256 initialSupply,
uint256 allocatedForICO,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply.mul(1e8); // Update total supply with the decimal amount
reservedForICO = allocatedForICO.mul(1e8); // Tokens reserved For ICO
balanceOf[this] = reservedForICO; // 800 Million Tokens will remain in the contract
balanceOf[msg.sender]=totalSupply.sub(reservedForICO); // Rest of tokens will be sent to owner
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* 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 for overflows
require(balanceOf[_to].add(_value) > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from].add(balanceOf[_to]);
// Subtract from the sender
balanceOf[_from] = balanceOf[_from].sub(_value);
// Add the same to the recipient
balanceOf[_to] = balanceOf[_to].add(_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].add(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);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in 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) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in 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) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender
totalSupply = totalSupply.sub(_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance
totalSupply = totalSupply.sub(_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/****************************************************/
/* MAIN FTKA TOKEN CONTRACT STARTS HERE */
/****************************************************/
contract FTKA is owned, TokenERC20 {
//**************************************************//
//------------- Code for the FTKA Token -------------//
//**************************************************//
// Public variables of the token
string internal tokenName = "FTKA";
string internal tokenSymbol = "FTKA";
uint256 internal initialSupply = 1000000000; // 1 Billion
uint256 private allocatedForICO = 800000000; // 800 Million
// Records for the fronzen accounts
mapping (address => bool) public frozenAccount;
// This generates a public event on the blockchain that will notify clients
event FrozenFunds(address target, bool frozen);
// Initializes contract with initial supply of tokens sent to the creator as well as contract
constructor () TokenERC20(initialSupply, allocatedForICO, tokenName, tokenSymbol) public { }
/**
* Transfer tokens - Internal transfer, only can be called by this contract
*
* This checks if the sender or recipient is not fronzen
*
* This keeps the track of total token holders and adds new holders as well.
*
* Send `_value` tokens to `_to` from your account
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount of tokens to send
*/
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient
emit Transfer(_from, _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) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
//**************************************************//
//------------- Code for the Crowdsale -------------//
//**************************************************//
//public variables for the Crowdsale
uint256 public icoStartDate = 1542326400 ; // 16 November 2018 00:00:00 - GMT
uint256 public icoEndDate = 1554076799 ; // 31 March 2019 23:59:59 - GMT
uint256 public exchangeRate = 5000; // 1 ETH = 5000 Tokens
uint256 public tokensSold = 0; // How many tokens sold in crowdsale
bool internal withdrawTokensOnlyOnce = true; // Admin can withdraw unsold tokens after ICO only once
//public variables of reward distribution
mapping(address => uint256) public investorContribution; //Track record whether token holder exist or not
address[] public icoContributors; //Array of addresses of ICO contributors
uint256 public tokenHolderIndex = 0; //To split the iterations of For Loop
uint256 public totalContributors = 0; //Total number of ICO contributors
/**
* @dev Fallback function, it accepts Ether from owner address as well as non-owner address
* @dev If ether came from owner address, then it will consider as reward payment to ICO contributors
* @dev If ether came from non-owner address, then it will consider as ICO investment contribution
*/
function () payable public {
if(msg.sender == owner && msg.value > 0){
processRewards(); //This function will process reward distribution
}
else{
processICO(); //This function will process ICO and sends tokens to contributor
}
}
/**
* @dev Function which processes ICO contributions
* @dev It calcualtes token amount from exchangeRate and also adds Bonuses if applicable
* @dev Ether will be forwarded to owner immidiately.
*/
function processICO() internal {
require(icoEndDate > now);
require(icoStartDate < now);
uint ethervalueWEI=msg.value;
uint256 token = ethervalueWEI.div(1e10).mul(exchangeRate);// token amount = weiamount * price
uint256 totalTokens = token.add(purchaseBonus(token)); // token + bonus
tokensSold = tokensSold.add(totalTokens);
_transfer(this, msg.sender, totalTokens); // makes the token transfer
forwardEherToOwner(); // send ether to owner
//if contributor does not exist in tokenHolderExist mapping, then add into it as well as add in tokenHolders array
if(investorContribution[msg.sender] == 0){
icoContributors.push(msg.sender);
totalContributors++;
}
investorContribution[msg.sender] = investorContribution[msg.sender].add(totalTokens);
}
/**
* @dev Function which processes ICO contributions
* @dev It calcualtes token amount from exchangeRate and also adds Bonuses if applicable
* @dev Ether will be forwarded to owner immidiately.
*/
function processRewards() internal {
for(uint256 i = 0; i < 150; i++){
if(tokenHolderIndex < totalContributors){
uint256 userContribution = investorContribution[icoContributors[tokenHolderIndex]];
if(userContribution > 0){
uint256 rewardPercentage = userContribution.mul(1000).div(tokensSold);
uint256 reward = msg.value.mul(rewardPercentage).div(1000);
icoContributors[tokenHolderIndex].transfer(reward);
tokenHolderIndex++;
}
}else{
//this code will run only when all the dividend/reward has been paid
tokenHolderIndex = 0;
break;
}
}
}
/**
* Automatocally forwards ether from smart contract to owner address.
*/
function forwardEherToOwner() internal {
owner.transfer(msg.value);
}
/**
* @dev Calculates purchase bonus according to the schedule.
* @dev SafeMath at some place is not used intentionally as overflow is impossible, and that saves gas cost
*
* @param _tokenAmount calculating tokens from amount of tokens
*
* @return bonus amount in wei
*
*/
function purchaseBonus(uint256 _tokenAmount) public view returns(uint256){
uint256 week1 = icoStartDate + 604800; //25% token bonus
uint256 week2 = week1 + 604800; //20% token bonus
uint256 week3 = week2 + 604800; //15% token bonus
uint256 week4 = week3 + 604800; //10% token bonus
uint256 week5 = week4 + 604800; //5% token bonus
if(now > icoStartDate && now < week1){
return _tokenAmount.mul(25).div(100); //25% bonus
}
else if(now > week1 && now < week2){
return _tokenAmount.mul(20).div(100); //20% bonus
}
else if(now > week2 && now < week3){
return _tokenAmount.mul(15).div(100); //15% bonus
}
else if(now > week3 && now < week4){
return _tokenAmount.mul(10).div(100); //10% bonus
}
else if(now > week4 && now < week5){
return _tokenAmount.mul(5).div(100); //5% bonus
}
else{
return 0;
}
}
/**
* Function to check wheter ICO is running or not.
*
* @return bool for whether ICO is running or not
*/
function isICORunning() public view returns(bool){
if(icoEndDate > now && icoStartDate < now){
return true;
}else{
return false;
}
}
/**
* Just in case, owner wants to transfer Tokens from contract to owner address
*/
function manualWithdrawToken(uint256 _amount) onlyOwner public {
uint256 tokenAmount = _amount.mul(1 ether);
_transfer(this, msg.sender, tokenAmount);
}
/**
* Just in case, owner wants to transfer Ether from contract to owner address
*/
function manualWithdrawEther()onlyOwner public{
address(owner).transfer(address(this).balance);
}
}
|
* @dev Function which processes ICO contributions @dev It calcualtes token amount from exchangeRate and also adds Bonuses if applicable @dev Ether will be forwarded to owner immidiately./if contributor does not exist in tokenHolderExist mapping, then add into it as well as add in tokenHolders array
|
function processICO() internal {
require(icoEndDate > now);
require(icoStartDate < now);
uint ethervalueWEI=msg.value;
tokensSold = tokensSold.add(totalTokens);
if(investorContribution[msg.sender] == 0){
icoContributors.push(msg.sender);
totalContributors++;
}
investorContribution[msg.sender] = investorContribution[msg.sender].add(totalTokens);
}
| 5,387,643 |
[
1,
2083,
1492,
8488,
467,
3865,
13608,
6170,
225,
2597,
7029,
1462,
1078,
1147,
3844,
628,
7829,
4727,
471,
2546,
4831,
605,
265,
6117,
309,
12008,
225,
512,
1136,
903,
506,
19683,
358,
3410,
709,
13138,
77,
5173,
18,
19,
430,
31123,
1552,
486,
1005,
316,
1147,
6064,
4786,
2874,
16,
1508,
527,
1368,
518,
487,
5492,
487,
527,
316,
1147,
27003,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
540,
445,
1207,
2871,
51,
1435,
2713,
288,
203,
5411,
2583,
12,
10764,
24640,
405,
2037,
1769,
203,
377,
202,
202,
6528,
12,
10764,
22635,
411,
2037,
1769,
203,
377,
202,
202,
11890,
225,
2437,
1132,
6950,
45,
33,
3576,
18,
1132,
31,
203,
377,
202,
202,
7860,
55,
1673,
273,
2430,
55,
1673,
18,
1289,
12,
4963,
5157,
1769,
203,
5411,
309,
12,
5768,
395,
280,
442,
4027,
63,
3576,
18,
15330,
65,
422,
374,
15329,
203,
7734,
277,
2894,
442,
665,
13595,
18,
6206,
12,
3576,
18,
15330,
1769,
203,
7734,
2078,
442,
665,
13595,
9904,
31,
203,
5411,
289,
203,
5411,
2198,
395,
280,
442,
4027,
63,
3576,
18,
15330,
65,
273,
2198,
395,
280,
442,
4027,
63,
3576,
18,
15330,
8009,
1289,
12,
4963,
5157,
1769,
203,
2398,
203,
540,
289,
203,
1850,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
* Safe Math Smart Contract. Copyright © 2016–2017 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.4.20;
/**
* Provides methods to safely add, subtract and multiply uint256 numbers.
*/
contract SafeMath {
uint256 constant private MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Add two uint256 values, throw in case of overflow.
*
* @param x first value to add
* @param y second value to add
* @return x + y
*/
function safeAdd (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
assert (x <= MAX_UINT256 - y);
return x + y;
}
/**
* Subtract one uint256 value from another, throw in case of underflow.
*
* @param x value to subtract from
* @param y value to subtract
* @return x - y
*/
function safeSub (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
assert (x >= y);
return x - y;
}
/**
* Multiply two uint256 values, throw in case of overflow.
*
* @param x first value to multiply
* @param y second value to multiply
* @return x * y
*/
function safeMul (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
if (y == 0) return 0; // Prevent division by zero at the next line
assert (x <= MAX_UINT256 / y);
return x * y;
}
}
/*
* EIP-20 Standard Token Smart Contract Interface.
* Copyright © 2016–2018 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* ERC-20 standard token interface, as defined
* <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md">here</a>.
*/
contract Token {
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply () public view returns (uint256 supply);
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) public view returns (uint256 balance);
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success);
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success);
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
public returns (bool success);
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance (address _owner, address _spender)
public view returns (uint256 remaining);
/**
* Logged when tokens were transferred from one owner to another.
*
* @param _from address of the owner, tokens were transferred from
* @param _to address of the owner, tokens were transferred to
* @param _value number of tokens transferred
*/
event Transfer (address indexed _from, address indexed _to, uint256 _value);
/**
* Logged when owner approved his tokens to be transferred by some spender.
*
* @param _owner owner who approved his tokens to be transferred
* @param _spender spender who were allowed to transfer the tokens belonging
* to the owner
* @param _value number of tokens belonging to the owner, approved to be
* transferred by the spender
*/
event Approval (
address indexed _owner, address indexed _spender, uint256 _value);
}/*
* Address Set Smart Contract Interface.
* Copyright © 2017–2018 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* Address Set smart contract interface.
*/
contract AddressSet {
/**
* Check whether address set contains given address.
*
* @param _address address to check
* @return true if address set contains given address, false otherwise
*/
function contains (address _address) public view returns (bool);
}
/*
* Abstract Token Smart Contract. Copyright © 2017 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* Abstract Token Smart Contract that could be used as a base contract for
* ERC-20 token contracts.
*/
contract AbstractToken is Token, SafeMath {
/**
* Create new Abstract Token contract.
*/
function AbstractToken () public {
// Do nothing
}
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) public view returns (uint256 balance) {
return accounts [_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success) {
uint256 fromBalance = accounts [msg.sender];
if (fromBalance < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (fromBalance, _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer (msg.sender, _to, _value);
return true;
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success) {
uint256 spenderAllowance = allowances [_from][msg.sender];
if (spenderAllowance < _value) return false;
uint256 fromBalance = accounts [_from];
if (fromBalance < _value) return false;
allowances [_from][msg.sender] =
safeSub (spenderAllowance, _value);
if (_value > 0 && _from != _to) {
accounts [_from] = safeSub (fromBalance, _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer (_from, _to, _value);
return true;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
public returns (bool success) {
allowances [msg.sender][_spender] = _value;
Approval (msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance (address _owner, address _spender)
public view returns (uint256 remaining) {
return allowances [_owner][_spender];
}
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) internal accounts;
/**
* Mapping from addresses of token holders to the mapping of addresses of
* spenders to the allowances set by these token holders to these spenders.
*/
mapping (address => mapping (address => uint256)) internal allowances;
}
/*
* Abstract Virtual Token Smart Contract.
* Copyright © 2017–2018 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* Abstract Token Smart Contract that could be used as a base contract for
* ERC-20 token contracts supporting virtual balance.
*/
contract AbstractVirtualToken is AbstractToken {
/**
* Maximum number of real (i.e. non-virtual) tokens in circulation (2^255-1).
*/
uint256 constant MAXIMUM_TOKENS_COUNT =
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Mask used to extract real balance of an account (2^255-1).
*/
uint256 constant BALANCE_MASK =
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Mask used to extract "materialized" flag of an account (2^255).
*/
uint256 constant MATERIALIZED_FLAG_MASK =
0x8000000000000000000000000000000000000000000000000000000000000000;
/**
* Create new Abstract Virtual Token contract.
*/
function AbstractVirtualToken () public AbstractToken () {
// Do nothing
}
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply () public view returns (uint256 supply) {
return tokensCount;
}
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) public view returns (uint256 balance) {
return safeAdd (
accounts [_owner] & BALANCE_MASK, getVirtualBalance (_owner));
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success) {
if (_value > balanceOf (msg.sender)) return false;
else {
materializeBalanceIfNeeded (msg.sender, _value);
return AbstractToken.transfer (_to, _value);
}
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success) {
if (_value > allowance (_from, msg.sender)) return false;
if (_value > balanceOf (_from)) return false;
else {
materializeBalanceIfNeeded (_from, _value);
return AbstractToken.transferFrom (_from, _to, _value);
}
}
/**
* Get virtual balance of the owner of given address.
*
* @param _owner address to get virtual balance for the owner of
* @return virtual balance of the owner of given address
*/
function virtualBalanceOf (address _owner)
internal view returns (uint256 _virtualBalance);
/**
* Calculate virtual balance of the owner of given address taking into account
* materialized flag and total number of real tokens already in circulation.
*/
function getVirtualBalance (address _owner)
private view returns (uint256 _virtualBalance) {
if (accounts [_owner] & MATERIALIZED_FLAG_MASK != 0) return 0;
else {
_virtualBalance = virtualBalanceOf (_owner);
uint256 maxVirtualBalance = safeSub (MAXIMUM_TOKENS_COUNT, tokensCount);
if (_virtualBalance > maxVirtualBalance)
_virtualBalance = maxVirtualBalance;
}
}
/**
* Materialize virtual balance of the owner of given address if this will help
* to transfer given number of tokens from it.
*
* @param _owner address to materialize virtual balance of
* @param _value number of tokens to be transferred
*/
function materializeBalanceIfNeeded (address _owner, uint256 _value) private {
uint256 storedBalance = accounts [_owner];
if (storedBalance & MATERIALIZED_FLAG_MASK == 0) {
// Virtual balance is not materialized yet
if (_value > storedBalance) {
// Real balance is not enough
uint256 virtualBalance = getVirtualBalance (_owner);
require (safeSub (_value, storedBalance) <= virtualBalance);
accounts [_owner] = MATERIALIZED_FLAG_MASK |
safeAdd (storedBalance, virtualBalance);
tokensCount = safeAdd (tokensCount, virtualBalance);
}
}
}
/**
* Number of real (i.e. non-virtual) tokens in circulation.
*/
uint256 internal tokensCount;
}
/*
* Module Promo Token Smart Contract. Copyright © 2018 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
/**
* Module Promo Tokem Smart Contract.
*/
contract ModulePromoToken is AbstractVirtualToken {
/**
* Number of virtual tokens to assign to the owners of addresses from given
* address set.
*/
uint256 private constant VIRTUAL_COUNT = 5;
/**
* Number of tokens to give to the contract deployer for future distribution.
*/
uint256 private constant INITIAL_TOKENS = 10e6;
/**
* Create ModulePromoToken smart contract with given address set.
*
* @param _addressSet address set to use
*/
function ModulePromoToken (AddressSet _addressSet)
public AbstractVirtualToken () {
owner = msg.sender;
accounts[owner] = INITIAL_TOKENS;
addressSet = _addressSet;
}
/**
* Get name of this token.
*
* @return name of this token
*/
function name () public pure returns (string) {
return "Promodl";
}
/**
* Get symbol of this token.
*
* @return symbol of this token
*/
function symbol () public pure returns (string) {
return "PMOD";
}
/**
* Get number of decimals for this token.
*
* @return number of decimals for this token
*/
function decimals () public pure returns (uint8) {
return 0;
}
/**
* Notify owners about their virtual balances.
*
* @param _owners addresses of the owners to be notified
*/
function massNotify (address [] _owners) public {
require (msg.sender == owner);
uint256 count = _owners.length;
for (uint256 i = 0; i < count; i++)
Transfer (address (0), _owners [i], VIRTUAL_COUNT);
}
/**
* Kill this smart contract.
*/
function kill () public {
require (msg.sender == owner);
selfdestruct (owner);
}
/**
* Change owner of the smart contract.
*
* @param _owner address of a new owner of the smart contract
*/
function changeOwner (address _owner) public {
require (msg.sender == owner);
owner = _owner;
}
/**
* Get virtual balance of the owner of given address.
*
* @param _owner address to get virtual balance for the owner of
* @return virtual balance of the owner of given address
*/
function virtualBalanceOf (address _owner)
internal view returns (uint256 _virtualBalance) {
return addressSet.contains (_owner) ? VIRTUAL_COUNT : 0;
}
/**
* Address of the owner of this smart contract.
*/
address internal owner;
/**
* Address set of addresses that are eligible for initial balance.
*/
AddressSet internal addressSet;
}
|
* Address of the owner of this smart contract./
|
address internal owner;
| 230,903 |
[
1,
1887,
434,
326,
3410,
434,
333,
13706,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
1758,
2713,
3410,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x83473a0A1a9a08506e2952D96730AaC0f39b8c9A/sources/contracts/implementation/EclipseERC721.sol
|
* @dev Get royalty info see {IERC2981}/
|
function royaltyInfo(
uint256,
uint256 salePrice_
) external view virtual override returns (address, uint256) {
return (
_royaltyReceiver,
((
_royaltyShares != 0
? _royaltyShares
: IEclipsePaymentSplitter(_royaltyReceiver)
.getTotalRoyaltyShares()
) * salePrice_) / DOMINATOR
);
}
| 4,868,807 |
[
1,
967,
721,
93,
15006,
1123,
2621,
288,
45,
654,
39,
5540,
11861,
4004,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
721,
93,
15006,
966,
12,
203,
3639,
2254,
5034,
16,
203,
3639,
2254,
5034,
272,
5349,
5147,
67,
203,
565,
262,
3903,
1476,
5024,
3849,
1135,
261,
2867,
16,
2254,
5034,
13,
288,
203,
3639,
327,
261,
203,
5411,
389,
3800,
15006,
12952,
16,
203,
5411,
14015,
203,
7734,
389,
3800,
15006,
24051,
480,
374,
203,
10792,
692,
389,
3800,
15006,
24051,
203,
10792,
294,
10897,
71,
10472,
6032,
26738,
24899,
3800,
15006,
12952,
13,
203,
13491,
263,
588,
5269,
54,
13372,
15006,
24051,
1435,
203,
5411,
262,
380,
272,
5349,
5147,
67,
13,
342,
4703,
706,
3575,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.11;
/**
* @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;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
//function Ownable() public {
constructor () public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/// @title A facet of KittyCore that manages special access privileges.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract AccessControl {
// This facet controls access control for CryptoKitties. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the KittyCore constructor.
//
// - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts.
//
// - The COO: The COO can release gen0 kitties to auction, and mint promo cats.
//
// It should be noted that these roles are distinct without overlap in their access abilities, the
// abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
// address to any role, the CEO address itself doesn't have the ability to act in those roles. This
// restriction is intentional so that we aren't tempted to use the CEO address frequently out of
// convenience. The less we use an address, the less likely it is that we somehow compromise the
// account.
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract PetBase is AccessControl {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously
/// includes any time a cat is created through the giveBirth method, but it is also called
/// when a new gen0 cat is created.
event Birth(address owner, uint256 monsterId, uint256 genes);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy
/// of this structure, so great care was taken to ensure that it fits neatly into
/// exactly two 256-bit words. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Pet {
// The Kitty's genetic code is packed into these 256-bits, the format is
// sooper-sekret! A cat's genes never change.
uint256 genes;
// The timestamp from the block when this cat came into existence.
uint64 birthTime;
// The "generation number" of this cat. Cats minted by the CK contract
// for sale are called "gen0" and have a generation number of 0. The
// generation number of all other cats is the larger of the two generation
// numbers of their parents, plus one.
// (i.e. max(matron.generation, sire.generation) + 1)
uint16 generation;
uint16 grade;
uint16 level;
uint16 params;
uint16 skills;
}
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the Pet struct for all pets (cats & dogs) in existence. The ID
/// of each pet is actually an index into this array. Note that ID 0 is a negapet,
/// the unPet, the mythical beast that is the parent of all gen0 pets. A bizarre
/// creature that is both matron and sire... to itself! Has an invalid genetic code.
/// In other words, pet ID 0 is invalid... ;-)
Pet[] pets; //Monster[] monsters;
/// @dev A mapping from pet IDs to the address that owns them. All pets have
/// some valid owner address, even gen0 pets are created with a non-zero owner.
mapping (uint256 => address) public petIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev A mapping from KittyIDs to an address that has been approved to call
/// transferFrom(). Each Kitty can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public petIndexToApproved;
/// @dev The address of the ClockAuction contract that handles sales of Kitties. This
/// same contract handles both peer-to-peer sales as well as the gen0 sales which are
/// initiated every 15 minutes.
SaleClockAuction public saleAuction;
/// @dev Assigns ownership of a specific Kitty to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of kittens is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
petIndexToOwner[_tokenId] = _to;
// When creating new kittens _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete petIndexToApproved[_tokenId];
}
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new kitty and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _generation The generation number of this cat, must be computed by caller.
/// @param _genes The kitty's genetic code.
/// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0)
function _createPet(
uint256 _generation,
uint256 _genes,
address _owner,
uint256 _grade,
uint256 _level,
uint256 _params,
uint256 _skills
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createKitty() is already
// an expensive call (for storage), and it doesn't hurt to be especially careful
// to ensure our data structures are always valid.
require(_generation == uint256(uint16(_generation)));
// New pet starts with the same cooldown as parent gen/2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
Pet memory _pet = Pet({
genes: _genes,
birthTime: uint64(now),
generation: uint16(_generation),
grade: uint16(_grade),
level: uint16(_level),
params: uint16(_params),
skills: uint16(_skills)
});
uint256 newPetId = pets.push(_pet) - 1;
// It's probably never going to happen, 4 billion cats is A LOT, but
// let's just be 100% sure we never let this happen.
require(newPetId == uint256(uint32(newPetId)));
// emit the birth event
emit Birth(
_owner,
newPetId,
_pet.genes
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newPetId);
return newPetId;
}
}
/// @title The external contract that is responsible for generating metadata for the kitties,
/// it has one function that will return the data as bytes.
contract ERC721Metadata {
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the KittyCore contract documentation to understand how the various contract facets are arranged.
contract PetOwnership is PetBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CatsVsDogs";
string public constant symbol = "CD";
// The contract that will return kitty metadata
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Kitty.
/// @param _claimant the address we are validating against.
/// @param _tokenId kitten id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return petIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Kitty.
/// @param _claimant the address we are confirming kitten is approved for.
/// @param _tokenId kitten id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return petIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Kitties on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
petIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of Kitties owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Kitty to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CryptoKitties specifically) or your Kitty may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Kitty to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any kitties (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of kitties
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
// You can only send your own cat.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Kitty via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Kitty owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Kitty to be transfered.
/// @param _to The address that should take ownership of the Kitty. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Kitty to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any kitties (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of Kitties currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return pets.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given Kitty.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = petIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all Kitty IDs assigned to an address.
/// @param _owner The owner whose Kitties we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Kitty array looking for cats belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCats = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all cats have IDs starting at 1 and increasing
// sequentially up to the totalCat count.
uint256 catId;
for (catId = 1; catId <= totalCats; catId++) {
if (petIndexToOwner[catId] == _owner) {
result[resultIndex] = catId;
resultIndex++;
}
}
return result;
}
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private pure {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private pure returns (string) {
//var outputString = new string(_stringLength);
string memory outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Kitty whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
emit AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
emit AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
emit AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/**
* @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 allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public returns (bool) {
paused = true;
emit Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
//function ClockAuction(address _nftAddress, uint256 _cut) public {
constructor (address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
uint256 balance = address(this).balance;
nftAddress.transfer(balance);
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
/// @title Clock auction modified for sale of kitties
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Tracks last 5 sale price of gen0 kitty sales
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
// Delegate constructor
//function SaleClockAuction(address _nftAddr, uint256 _cut) public
constructor (address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
external
payable
{
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
}
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
/// @title Handles creating auctions for sale and siring of kitties.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract PetAuction is PetOwnership {
// @notice The auction contract variables are defined in KittyBase to allow
// us to refer to them in KittyOwnership to prevent accidental transfers.
// `saleAuction` refers to the auction for gen0 and p2p sale of kitties.
// `siringAuction` refers to the auction for siring rights of kitties.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Put a kitty up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _petId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If kitty is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _petId));
_approve(_petId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the kitty.
saleAuction.createAuction(
_petId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Transfers the balance of the sale auction contract
/// to the KittyCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
}
}
/// @title all functions related to creating kittens
contract PetMinting is PetAuction {
// Limits the number of cats the contract owner can ever create.
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 45000;
// Constants for gen0 auctions.
uint256 public constant GEN0_STARTING_PRICE = 100 szabo; //1 finney;
uint256 public constant GEN0_AUCTION_DURATION = 14 days;
// Counts the number of cats the contract owner has created.
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
/// @dev we can create promo kittens, up to a limit. Only callable by COO
/// @param _genes the encoded genes of the kitten to be created, any value is accepted
/// @param _owner the future owner of the created kittens. Default to contract COO
function createPromoPet(uint256 _genes, address _owner, uint256 _grade, uint256 _level, uint256 _params, uint256 _skills) external onlyCOO {
address petOwner = _owner;
if (petOwner == address(0)) {
petOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createPet(0, _genes, petOwner, _grade, _level, _params, _skills);
}
/// @dev Creates a new gen0 kitty with the given genes and
/// creates an auction for it.
function createGen0Auction(uint256 _genes, uint256 _grade, uint256 _level, uint256 _params, uint256 _skills) external onlyCOO {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 petId = _createPet(0, _genes, address(this), _grade, _level, _params, _skills);
_approve(petId, saleAuction);
saleAuction.createAuction(
petId,
GEN0_STARTING_PRICE,
0,
GEN0_AUCTION_DURATION,
address(this)
);
gen0CreatedCount++;
}
}
/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost.
contract PetCore is PetMinting {
// This is the main CryptoKitties contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
// that handle auctions and our super-top-secret genetic combination algorithm. The auctions are
// seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
// them in their own contracts, we can upgrade them without disrupting the main contract that tracks
// kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of
// the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
// Don't worry, I'm sure someone will reverse engineer it soon enough!
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of CK. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - KittyBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - KittyAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - KittyOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - KittyBreeding: This file contains the methods necessary to breed cats together, including
// keeping track of siring offers, and relies on an external genetic combination contract.
//
// - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring
// services. The actual auction functionality is handled in two sibling contracts (one
// for sales and one for siring), while auction creation and bidding is mostly mediated
// through this facet of the core contract.
//
// - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats.
// We can make up to 5000 "promo" cats that can be given away (especially important when
// the community is new), and all others can only be created and then immediately put up
// for auction via an algorithmically determined starting price. Regardless of how they
// are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the
// community to breed, breed, breed!
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main CryptoKitties smart contract instance.
//function PetCore() public {
constructor() public {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
// start with the mythical catdog 0 - so we don't have generation-0 parent issues
_createPet(0, uint256(-1), address(0), uint256(-1), uint256(-1), uint256(-1), uint256(-1));
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction)
);
}
/// @notice Returns all the relevant information about a specific kitty.
/// @param _id The ID of the kitty of interest.
function getPet(uint256 _id)
external
view
returns (
uint256 birthTime,
uint256 generation,
uint256 genes,
uint256 grade,
uint256 level,
uint256 params,
uint256 skills
) {
Pet storage pet = pets[_id];
// if this variable is 0 then it's not gestating
birthTime = uint256(pet.birthTime);
generation = uint256(pet.generation);
genes = pet.genes;
grade = pet.grade;
level = pet.level;
params = pet.params;
skills = pet.skills;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the CFO to capture the balance available to the contract.
function withdrawBalance() external onlyCFO {
uint256 balance = address(this).balance;
cfoAddress.transfer(balance);
}
// @dev Allows the CFO to capture the balance available to the contract.
function withdrawBalanceCut(uint256 amount) external onlyCFO {
uint256 balance = address(this).balance;
require (balance > amount);
cfoAddress.transfer(amount);
}
}
|
@notice Returns the address currently assigned ownership of a given Kitty. @dev Required for ERC-721 compliance.
|
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = petIndexToOwner[_tokenId];
require(owner != address(0));
}
| 14,044,082 |
[
1,
1356,
326,
1758,
4551,
6958,
23178,
434,
279,
864,
1475,
305,
4098,
18,
225,
10647,
364,
4232,
39,
17,
27,
5340,
29443,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
3410,
951,
12,
11890,
5034,
389,
2316,
548,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
2867,
3410,
13,
203,
565,
288,
203,
3639,
3410,
273,
293,
278,
1016,
774,
5541,
63,
67,
2316,
548,
15533,
203,
203,
3639,
2583,
12,
8443,
480,
1758,
12,
20,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BSD-2
pragma solidity ^0.6.0;
/**
* @title Staking (Liquidity Mining/Farming) Contract for Buidl
*/
contract BUIDLHodl {
uint256 private constant MODES = 3;
address private _proxy;
address private _buidlTokenAddress;
address private _usdcTokenAddress;
address private _uniswapV2RouterAddress;
address private _buidlEthPoolTokenAddress;
address private _buidlUSDCPoolTokenAddress;
uint256[] private _blocksRanges;
uint256[][] private _tokenRewards;
uint256 private _accumulatingEndBlock;
mapping(address => mapping(uint256 => StakingInfo)) private _totalLocked;
struct StakingInfo {
bool eth;
uint256 amountLocked;
uint256 reward;
uint256 unlockBlock;
bool withdrawn;
}
event Staked(
address indexed sender,
uint256 indexed mode,
bool eth,
uint256 amountIn,
uint256 tokenPool,
uint256 reward,
uint256 endBlock
);
/**
* @dev Constructor for the contract
* @param proxy Address of the Proxy contract
* @param usdcTokenAddress Address of the USDC stablecoin contract
* @param uniswapV2RouterAddress Address of the UniswapV2Router Contract
* @param buidlEthPoolTokenAddress Address of the Uniswap buidl-eth pool
* @param buidlUSDCPoolTokenAddress Address of the Uniswap buidl-usdc pool
* @param accumulatingEndBlock Maximum time in which the staking is available
* @param blockRanges Array of timed windows for the various staking tiers
* @param tokenRewardsMultipliers Multipliers for the above tiers (Numerator)
* @param tokensRewardsDividers Dividers for the above tier, gives you the percentage (Denominator)
*/
constructor(
address proxy,
address usdcTokenAddress,
address uniswapV2RouterAddress,
address buidlEthPoolTokenAddress,
address buidlUSDCPoolTokenAddress,
uint256 accumulatingEndBlock,
uint256[] memory blocksRanges,
uint256[] memory tokenRewardsMultipliers,
uint256[] memory tokenRewardsDividers
) public {
assert(
blocksRanges.length == MODES &&
blocksRanges.length == tokenRewardsMultipliers.length &&
tokenRewardsMultipliers.length == tokenRewardsDividers.length
);
_buidlTokenAddress = IMVDProxy(_proxy = proxy).getToken();
_usdcTokenAddress = usdcTokenAddress;
_uniswapV2RouterAddress = uniswapV2RouterAddress;
_buidlEthPoolTokenAddress = buidlEthPoolTokenAddress;
_buidlUSDCPoolTokenAddress = buidlUSDCPoolTokenAddress;
_accumulatingEndBlock = accumulatingEndBlock;
_blocksRanges = blocksRanges;
for (uint256 i = 0; i < tokenRewardsMultipliers.length; i++) {
_tokenRewards.push([tokenRewardsMultipliers[i], tokenRewardsDividers[i]]);
}
}
/**
* @dev GETTER for the proxy
* @return proxy Address for the proxy contract
*/
function proxy() public view returns (address proxy) {
return _proxy;
}
/**
* @dev SETTER for the proxy
* @param newProxy Address for the new proxy contract to set
*/
function setProxy(address newProxy) public {
require(
IMVDFunctionalitiesManager(IMVDProxy(_proxy).getMVDFunctionalitiesManagerAddress())
.isAuthorizedFunctionality(msg.sender),
"Unauthorized Action!"
);
_proxy = newProxy;
}
/**
* @dev Stake the liquidity
* @param buidlIn Amount if buidl to stake
* @param usdcIn Amount of usdc to stake
* @param mode Staking mode (time tier)
*/
function lock(
uint256 buidlIn,
uint256 usdcIn,
uint256 mode
) public payable {
require(block.number < _accumulatingEndBlock, "Accumulating Time has finished!");
require(mode < MODES, "Unknown mode!");
uint256 reward = _calculateReward(buidlIn, mode);
_installStorageIfNecessary(msg.sender);
StakingInfo[] storage array = _totalLocked[msg.sender][mode];
array.push(
StakingInfo(msg.value > 0, buidlIn, reward, block.number + _blocksRanges[mode], false)
);
_totalLocked[msg.sender][mode] = array;
if (msg.value == 0) {
IERC20(_usdcTokenAddress).transferFrom(msg.sender, address(this), usdcIn);
}
emit Staked(
msg.sender,
mode,
msg.value > 0,
msg.value > 0 ? msg.value : buidlIn,
0,
reward,
block.number + _blocksRanges[mode]
);
}
// For each user insert their info in the relevant tier
function _installStorageIfNecessary(address sender) private {
if (_totalLocked[sender].length > 0) {
return;
}
for (uint256 i = 0; i < MODES; i++) {
_totalLocked[sender].push(new StakingInfo[]);
}
}
/**
* @dev Compute the staking reward according to the mode
* @param amount Locked amount
* @param mode Temporal Tier
* @return reward Total reward
*/
function _calculateReward(uint256 amount, uint256 mode) private view returns (uint256 reward) {
return _tokenRewards[mode][0];
}
/**
* @dev Withdraw staked liquidity. Can only be done after the time tier is passed.
* @param sender Address of the requester. Liquidity withdrawn will be sent to this address
*/
function withdraw(address sender) public {
require(block.number >= _accumulatingEndBlock, "Accumulating Time is still running!");
StakingInfo[][] storage stakingInfos = _totalLocked[sender];
uint256 ethPoolTokens = 0;
uint256 usdcPoolTokens = 0;
uint256 buidlTokens = 0;
for (uint256 i = 0; i < _blocksRanges.length; i++) {
for (uint256 z = 0; z < stakingInfos[i].length; z++) {
StakingInfo storage stakingInfo = stakingInfos[i][z];
if (stakingInfo.withdrawn) {
continue;
}
if (stakingInfo.unlockBlock > block.number) {
break;
}
stakingInfo.withdrawn = true;
ethPoolTokens += stakingInfo.eth ? stakingInfo.amountLocked : 0;
usdcPoolTokens += stakingInfo.eth ? 0 : stakingInfo.amountLocked;
buidlTokens += stakingInfo.reward;
}
}
if (ethPoolTokens > 0) {
IERC20(_buidlEthPoolTokenAddress).transfer(sender, ethPoolTokens);
}
if (usdcPoolTokens > 0) {
IERC20(_buidlUSDCPoolTokenAddress).transfer(sender, usdcPoolTokens);
}
if (buidlTokens > 0) {
IERC20(_buidlTokenAddress).transfer(sender, buidlTokens);
}
}
}
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function burn(uint256 amount) external;
}
interface IUniswapV2Router {
function WETH() external pure returns (address);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
interface IMVDProxy {
function getToken() external view returns (address);
function getStateHolderAddress() external view returns (address);
function getMVDWalletAddress() external view returns (address);
function getMVDFunctionalitiesManagerAddress() external view returns (address);
function submit(string calldata codeName, bytes calldata data)
external
payable
returns (bytes memory returnData);
function transfer(
address receiver,
uint256 value,
address token
) external;
}
interface IMVDFunctionalitiesManager {
function isAuthorizedFunctionality(address functionality) external view returns (bool);
}
interface IStateHolder {
function setUint256(string calldata name, uint256 value) external returns (uint256);
function getUint256(string calldata name) external view returns (uint256);
function getAddress(string calldata name) external view returns (address);
function setAddress(string calldata varName, address val) external returns (address);
function clear(string calldata varName)
external
returns (string memory oldDataType, bytes memory oldVal);
}
|
* @dev Stake the liquidity @param buidlIn Amount if buidl to stake @param usdcIn Amount of usdc to stake @param mode Staking mode (time tier)/
|
function lock(
uint256 buidlIn,
uint256 usdcIn,
uint256 mode
) public payable {
require(block.number < _accumulatingEndBlock, "Accumulating Time has finished!");
require(mode < MODES, "Unknown mode!");
uint256 reward = _calculateReward(buidlIn, mode);
_installStorageIfNecessary(msg.sender);
StakingInfo[] storage array = _totalLocked[msg.sender][mode];
array.push(
StakingInfo(msg.value > 0, buidlIn, reward, block.number + _blocksRanges[mode], false)
);
_totalLocked[msg.sender][mode] = array;
if (msg.value == 0) {
IERC20(_usdcTokenAddress).transferFrom(msg.sender, address(this), usdcIn);
}
emit Staked(
msg.sender,
mode,
msg.value > 0,
msg.value > 0 ? msg.value : buidlIn,
0,
reward,
block.number + _blocksRanges[mode]
);
}
| 5,547,779 |
[
1,
510,
911,
326,
4501,
372,
24237,
225,
324,
1911,
80,
382,
16811,
309,
324,
1911,
80,
358,
384,
911,
225,
584,
7201,
382,
16811,
434,
584,
7201,
358,
384,
911,
225,
1965,
934,
6159,
1965,
261,
957,
17742,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2176,
12,
203,
3639,
2254,
5034,
324,
1911,
80,
382,
16,
203,
3639,
2254,
5034,
584,
7201,
382,
16,
203,
3639,
2254,
5034,
1965,
203,
565,
262,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
2629,
18,
2696,
411,
389,
8981,
5283,
1776,
1638,
1768,
16,
315,
8973,
5283,
1776,
2647,
711,
6708,
4442,
1769,
203,
3639,
2583,
12,
3188,
411,
11741,
55,
16,
315,
4874,
1965,
4442,
1769,
203,
3639,
2254,
5034,
19890,
273,
389,
11162,
17631,
1060,
12,
70,
1911,
80,
382,
16,
1965,
1769,
203,
3639,
389,
5425,
3245,
26034,
12,
3576,
18,
15330,
1769,
203,
3639,
934,
6159,
966,
8526,
2502,
526,
273,
389,
4963,
8966,
63,
3576,
18,
15330,
6362,
3188,
15533,
203,
3639,
526,
18,
6206,
12,
203,
5411,
934,
6159,
966,
12,
3576,
18,
1132,
405,
374,
16,
324,
1911,
80,
382,
16,
19890,
16,
1203,
18,
2696,
397,
389,
7996,
9932,
63,
3188,
6487,
629,
13,
203,
3639,
11272,
203,
3639,
389,
4963,
8966,
63,
3576,
18,
15330,
6362,
3188,
65,
273,
526,
31,
203,
3639,
309,
261,
3576,
18,
1132,
422,
374,
13,
288,
203,
5411,
467,
654,
39,
3462,
24899,
407,
7201,
1345,
1887,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
584,
7201,
382,
1769,
203,
3639,
289,
203,
3639,
3626,
934,
9477,
12,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
1965,
16,
203,
5411,
1234,
18,
1132,
405,
374,
16,
203,
5411,
1234,
18,
1132,
405,
374,
692,
1234,
18,
1132,
294,
324,
1911,
80,
2
] |
pragma solidity ^0.4.11;
/**
* @title Owned contract with safe ownership pass.
*
* Note: all the non constant functions return false instead of throwing in case if state change
* didn't happen yet.
*/
contract Owned {
/**
* Contract owner address
*/
address public contractOwner;
/**
* Contract owner address
*/
address public pendingContractOwner;
function Owned() {
contractOwner = msg.sender;
}
/**
* @dev Owner check modifier
*/
modifier onlyContractOwner() {
if (contractOwner == msg.sender) {
_;
}
}
/**
* @dev Destroy contract and scrub a data
* @notice Only owner can call it
*/
function destroy() onlyContractOwner {
suicide(msg.sender);
}
/**
* Prepares ownership pass.
*
* Can only be called by current owner.
*
* @param _to address of the next owner. 0x0 is not allowed.
*
* @return success.
*/
function changeContractOwnership(address _to) onlyContractOwner() returns(bool) {
if (_to == 0x0) {
return false;
}
pendingContractOwner = _to;
return true;
}
/**
* Finalize ownership pass.
*
* Can only be called by pending owner.
*
* @return success.
*/
function claimContractOwnership() returns(bool) {
if (pendingContractOwner != msg.sender) {
return false;
}
contractOwner = pendingContractOwner;
delete pendingContractOwner;
return true;
}
}
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
/**
* @title Generic owned destroyable contract
*/
contract Object is Owned {
/**
* Common result code. Means everything is fine.
*/
uint constant OK = 1;
uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8;
function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) {
for(uint i=0;i<tokens.length;i++) {
address token = tokens[i];
uint balance = ERC20Interface(token).balanceOf(this);
if(balance != 0)
ERC20Interface(token).transfer(_to,balance);
}
return OK;
}
function checkOnlyContractOwner() internal constant returns(uint) {
if (contractOwner == msg.sender) {
return OK;
}
return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER;
}
}
/**
* @title General MultiEventsHistory user.
*
*/
contract MultiEventsHistoryAdapter {
/**
* @dev It is address of MultiEventsHistory caller assuming we are inside of delegate call.
*/
function _self() constant internal returns (address) {
return msg.sender;
}
}
contract DelayedPaymentsEmitter is MultiEventsHistoryAdapter {
event Error(bytes32 message);
function emitError(bytes32 _message) {
Error(_message);
}
}
contract DelayedPayments is Object {
uint constant DELAYED_PAYMENTS_SCOPE = 52000;
uint constant DELAYED_PAYMENTS_INVALID_INVOCATION = DELAYED_PAYMENTS_SCOPE + 17;
/// @dev `Payment` is a public structure that describes the details of
/// each payment making it easy to track the movement of funds
/// transparently
struct Payment {
address spender; // Who is sending the funds
uint earliestPayTime; // The earliest a payment can be made (Unix Time)
bool canceled; // If True then the payment has been canceled
bool paid; // If True then the payment has been paid
address recipient; // Who is receiving the funds
uint amount; // The amount of wei sent in the payment
uint securityGuardDelay;// The seconds `securityGuard` can delay payment
}
Payment[] public authorizedPayments;
address public securityGuard;
uint public absoluteMinTimeLock;
uint public timeLock;
uint public maxSecurityGuardDelay;
// Should use interface of the emitter, but address of events history.
address public eventsHistory;
/// @dev The white list of approved addresses allowed to set up && receive
/// payments from this vault
mapping (address => bool) public allowedSpenders;
/// @dev The address assigned the role of `securityGuard` is the only
/// addresses that can call a function with this modifier
modifier onlySecurityGuard { if (msg.sender != securityGuard) throw; _; }
// @dev Events to make the payment movements easy to find on the blockchain
event PaymentAuthorized(uint indexed idPayment, address indexed recipient, uint amount);
event PaymentExecuted(uint indexed idPayment, address indexed recipient, uint amount);
event PaymentCanceled(uint indexed idPayment);
event EtherReceived(address indexed from, uint amount);
event SpenderAuthorization(address indexed spender, bool authorized);
/////////
// Constructor
/////////
/// @notice The Constructor creates the Vault on the blockchain
/// @param _absoluteMinTimeLock The minimum number of seconds `timelock` can
/// be set to, if set to 0 the `owner` can remove the `timeLock` completely
/// @param _timeLock Initial number of seconds that payments are delayed
/// after they are authorized (a security precaution)
/// @param _maxSecurityGuardDelay The maximum number of seconds in total
/// that `securityGuard` can delay a payment so that the owner can cancel
/// the payment if needed
function DelayedPayments(
uint _absoluteMinTimeLock,
uint _timeLock,
uint _maxSecurityGuardDelay)
{
absoluteMinTimeLock = _absoluteMinTimeLock;
timeLock = _timeLock;
securityGuard = msg.sender;
maxSecurityGuardDelay = _maxSecurityGuardDelay;
}
/**
* Emits Error event with specified error message.
*
* Should only be used if no state changes happened.
*
* @param _errorCode code of an error
* @param _message error message.
*/
function _error(uint _errorCode, bytes32 _message) internal returns(uint) {
DelayedPaymentsEmitter(eventsHistory).emitError(_message);
return _errorCode;
}
/**
* Sets EventsHstory contract address.
*
* Can be set only once, and only by contract owner.
*
* @param _eventsHistory MultiEventsHistory contract address.
*
* @return success.
*/
function setupEventsHistory(address _eventsHistory) returns(uint errorCode) {
errorCode = checkOnlyContractOwner();
if (errorCode != OK) {
return errorCode;
}
if (eventsHistory != 0x0 && eventsHistory != _eventsHistory) {
return DELAYED_PAYMENTS_INVALID_INVOCATION;
}
eventsHistory = _eventsHistory;
return OK;
}
/////////
// Helper functions
/////////
/// @notice States the total number of authorized payments in this contract
/// @return The number of payments ever authorized even if they were canceled
function numberOfAuthorizedPayments() constant returns (uint) {
return authorizedPayments.length;
}
//////
// Receive Ether
//////
/// @notice Called anytime ether is sent to the contract && creates an event
/// to more easily track the incoming transactions
function receiveEther() payable {
EtherReceived(msg.sender, msg.value);
}
/// @notice The fall back function is called whenever ether is sent to this
/// contract
function () payable {
receiveEther();
}
////////
// Spender Interface
////////
/// @notice only `allowedSpenders[]` Creates a new `Payment`
/// @param _recipient Destination of the payment
/// @param _amount Amount to be paid in wei
/// @param _paymentDelay Number of seconds the payment is to be delayed, if
/// this value is below `timeLock` then the `timeLock` determines the delay
/// @return The Payment ID number for the new authorized payment
function authorizePayment(
address _recipient,
uint _amount,
uint _paymentDelay
) returns(uint) {
// Fail if you arent on the `allowedSpenders` white list
if (!allowedSpenders[msg.sender]) throw;
uint idPayment = authorizedPayments.length; // Unique Payment ID
authorizedPayments.length++;
// The following lines fill out the payment struct
Payment p = authorizedPayments[idPayment];
p.spender = msg.sender;
// Overflow protection
if (_paymentDelay > 10**18) throw;
// Determines the earliest the recipient can receive payment (Unix time)
p.earliestPayTime = _paymentDelay >= timeLock ?
now + _paymentDelay :
now + timeLock;
p.recipient = _recipient;
p.amount = _amount;
PaymentAuthorized(idPayment, p.recipient, p.amount);
return idPayment;
}
/// @notice only `allowedSpenders[]` The recipient of a payment calls this
/// function to send themselves the ether after the `earliestPayTime` has
/// expired
/// @param _idPayment The payment ID to be executed
function collectAuthorizedPayment(uint _idPayment) {
// Check that the `_idPayment` has been added to the payments struct
if (_idPayment >= authorizedPayments.length) return;
Payment p = authorizedPayments[_idPayment];
// Checking for reasons not to execute the payment
if (msg.sender != p.recipient) return;
if (now < p.earliestPayTime) return;
if (p.canceled) return;
if (p.paid) return;
if (this.balance < p.amount) return;
p.paid = true; // Set the payment to being paid
if (!p.recipient.send(p.amount)) { // Make the payment
return;
}
PaymentExecuted(_idPayment, p.recipient, p.amount);
}
/////////
// SecurityGuard Interface
/////////
/// @notice `onlySecurityGuard` Delays a payment for a set number of seconds
/// @param _idPayment ID of the payment to be delayed
/// @param _delay The number of seconds to delay the payment
function delayPayment(uint _idPayment, uint _delay) onlySecurityGuard {
if (_idPayment >= authorizedPayments.length) throw;
// Overflow test
if (_delay > 10**18) throw;
Payment p = authorizedPayments[_idPayment];
if ((p.securityGuardDelay + _delay > maxSecurityGuardDelay) ||
(p.paid) ||
(p.canceled))
throw;
p.securityGuardDelay += _delay;
p.earliestPayTime += _delay;
}
////////
// Owner Interface
///////
/// @notice `onlyOwner` Cancel a payment all together
/// @param _idPayment ID of the payment to be canceled.
function cancelPayment(uint _idPayment) onlyContractOwner {
if (_idPayment >= authorizedPayments.length) throw;
Payment p = authorizedPayments[_idPayment];
if (p.canceled) throw;
if (p.paid) throw;
p.canceled = true;
PaymentCanceled(_idPayment);
}
/// @notice `onlyOwner` Adds a spender to the `allowedSpenders[]` white list
/// @param _spender The address of the contract being authorized/unauthorized
/// @param _authorize `true` if authorizing and `false` if unauthorizing
function authorizeSpender(address _spender, bool _authorize) onlyContractOwner {
allowedSpenders[_spender] = _authorize;
SpenderAuthorization(_spender, _authorize);
}
/// @notice `onlyOwner` Sets the address of `securityGuard`
/// @param _newSecurityGuard Address of the new security guard
function setSecurityGuard(address _newSecurityGuard) onlyContractOwner {
securityGuard = _newSecurityGuard;
}
/// @notice `onlyOwner` Changes `timeLock`; the new `timeLock` cannot be
/// lower than `absoluteMinTimeLock`
/// @param _newTimeLock Sets the new minimum default `timeLock` in seconds;
/// pending payments maintain their `earliestPayTime`
function setTimelock(uint _newTimeLock) onlyContractOwner {
if (_newTimeLock < absoluteMinTimeLock) throw;
timeLock = _newTimeLock;
}
/// @notice `onlyOwner` Changes the maximum number of seconds
/// `securityGuard` can delay a payment
/// @param _maxSecurityGuardDelay The new maximum delay in seconds that
/// `securityGuard` can delay the payment's execution in total
function setMaxSecurityGuardDelay(uint _maxSecurityGuardDelay) onlyContractOwner {
maxSecurityGuardDelay = _maxSecurityGuardDelay;
}
}
contract Asset {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
contract BuyBackEmitter {
function emitError(uint errorCode);
function emitPricesUpdated(uint buyPrice, uint sellPrice);
function emitActiveChanged(bool isActive);
}
contract BuyBack is Object {
uint constant ERROR_EXCHANGE_INVALID_PARAMETER = 6000;
uint constant ERROR_EXCHANGE_INVALID_INVOCATION = 6001;
uint constant ERROR_EXCHANGE_INVALID_FEE_PERCENT = 6002;
uint constant ERROR_EXCHANGE_INVALID_PRICE = 6003;
uint constant ERROR_EXCHANGE_MAINTENANCE_MODE = 6004;
uint constant ERROR_EXCHANGE_TOO_HIGH_PRICE = 6005;
uint constant ERROR_EXCHANGE_TOO_LOW_PRICE = 6006;
uint constant ERROR_EXCHANGE_INSUFFICIENT_BALANCE = 6007;
uint constant ERROR_EXCHANGE_INSUFFICIENT_ETHER_SUPPLY = 6008;
uint constant ERROR_EXCHANGE_PAYMENT_FAILED = 6009;
uint constant ERROR_EXCHANGE_TRANSFER_FAILED = 6010;
uint constant ERROR_EXCHANGE_FEE_TRANSFER_FAILED = 6011;
uint constant ERROR_EXCHANGE_DELAYEDPAYMENTS_ACCESS = 6012;
// Assigned ERC20 token.
Asset public asset;
DelayedPayments public delayedPayments;
//Switch for turn on and off the exchange operations
bool public isActive;
// Price in wei at which exchange buys tokens.
uint public buyPrice = 1;
// Price in wei at which exchange sells tokens.
uint public sellPrice = 2570735391000000; // 80% from ETH/USD=311.1950
uint public minAmount;
uint public maxAmount;
// User sold tokens and received wei.
event Sell(address indexed who, uint token, uint eth);
// User bought tokens and payed wei.
event Buy(address indexed who, uint token, uint eth);
event WithdrawTokens(address indexed recipient, uint amount);
event WithdrawEth(address indexed recipient, uint amount);
event PricesUpdated(address indexed self, uint buyPrice, uint sellPrice);
event ActiveChanged(address indexed self, bool isActive);
event Error(uint errorCode);
/**
* @dev On received ethers
* @param sender Ether sender
* @param amount Ether value
*/
event ReceivedEther(address indexed sender, uint256 indexed amount);
// Should use interface of the emitter, but address of events history.
BuyBackEmitter public eventsHistory;
/**
* Emits Error event with specified error message.
*
* Should only be used if no state changes happened.
*
* @param error error from Errors library.
*/
function _error(uint error) internal returns (uint) {
getEventsHistory().emitError(error);
return error;
}
function _emitPricesUpdated(uint buyPrice, uint sellPrice) internal {
getEventsHistory().emitPricesUpdated(buyPrice, sellPrice);
}
function _emitActiveChanged(bool isActive) internal {
getEventsHistory().emitActiveChanged(isActive);
}
/**
* Sets EventsHstory contract address.
*
* Can be set only once, and only by contract owner.
*
* @param _eventsHistory MultiEventsHistory contract address.
*
* @return success.
*/
function setupEventsHistory(address _eventsHistory) onlyContractOwner returns (uint) {
if (address(eventsHistory) != 0x0) {
return _error(ERROR_EXCHANGE_INVALID_INVOCATION);
}
eventsHistory = BuyBackEmitter(_eventsHistory);
return OK;
}
/**
* Assigns ERC20 token for exchange.
*
* Can be set only once, and only by contract owner.
*
* @param _asset ERC20 token address.
*
* @return success.
*/
function init(Asset _asset, DelayedPayments _delayedPayments) onlyContractOwner returns (uint errorCode) {
if (address(asset) != 0x0 || address(delayedPayments) != 0x0) {
return _error(ERROR_EXCHANGE_INVALID_INVOCATION);
}
asset = _asset;
delayedPayments = _delayedPayments;
isActive = true;
return OK;
}
function setActive(bool _active) onlyContractOwner returns (uint) {
if (isActive != _active) {
_emitActiveChanged(_active);
}
isActive = _active;
return OK;
}
/**
* Set exchange operation prices.
* Sell price cannot be less than buy price.
*
* Can be set only by contract owner.
*
* @param _buyPrice price in wei at which exchange buys tokens.
* @param _sellPrice price in wei at which exchange sells tokens.
*
* @return success.
*/
function setPrices(uint _buyPrice, uint _sellPrice) onlyContractOwner returns (uint) {
if (_sellPrice < _buyPrice) {
return _error(ERROR_EXCHANGE_INVALID_PRICE);
}
buyPrice = _buyPrice;
sellPrice = _sellPrice;
_emitPricesUpdated(_buyPrice, _sellPrice);
return OK;
}
/**
* Returns assigned token address balance.
*
* @param _address address to get balance.
*
* @return token balance.
*/
function _balanceOf(address _address) constant internal returns (uint) {
return asset.balanceOf(_address);
}
/**
* Sell tokens for ether at specified price. Tokens are taken from caller
* though an allowance logic.
* Amount should be less than or equal to current allowance value.
* Price should be less than or equal to current exchange buyPrice.
*
* @param _amount amount of tokens to sell.
* @param _price price in wei at which sell will happen.
*
* @return success.
*/
function sell(uint _amount, uint _price) returns (uint) {
if (!isActive) {
return _error(ERROR_EXCHANGE_MAINTENANCE_MODE);
}
if (_price > buyPrice) {
return _error(ERROR_EXCHANGE_TOO_HIGH_PRICE);
}
if (_balanceOf(msg.sender) < _amount) {
return _error(ERROR_EXCHANGE_INSUFFICIENT_BALANCE);
}
uint total = _mul(_amount, _price);
if (this.balance < total) {
return _error(ERROR_EXCHANGE_INSUFFICIENT_ETHER_SUPPLY);
}
if (!asset.transferFrom(msg.sender, this, _amount)) {
return _error(ERROR_EXCHANGE_PAYMENT_FAILED);
}
if (!delayedPayments.send(total)) {
throw;
}
if (!delayedPayments.allowedSpenders(this)) {
throw;
}
delayedPayments.authorizePayment(msg.sender,total,1 hours);
Sell(msg.sender, _amount, total);
return OK;
}
/**
* Transfer specified amount of tokens from exchange to specified address.
*
* Can be called only by contract owner.
*
* @param _recipient address to transfer tokens to.
* @param _amount amount of tokens to transfer.
*
* @return success.
*/
function withdrawTokens(address _recipient, uint _amount) onlyContractOwner returns (uint) {
if (_balanceOf(this) < _amount) {
return _error(ERROR_EXCHANGE_INSUFFICIENT_BALANCE);
}
if (!asset.transfer(_recipient, _amount)) {
return _error(ERROR_EXCHANGE_TRANSFER_FAILED);
}
WithdrawTokens(_recipient, _amount);
return OK;
}
/**
* Transfer all tokens from exchange to specified address.
*
* Can be called only by contract owner.
*
* @param _recipient address to transfer tokens to.
*
* @return success.
*/
function withdrawAllTokens(address _recipient) onlyContractOwner returns (uint) {
return withdrawTokens(_recipient, _balanceOf(this));
}
/**
* Transfer specified amount of wei from exchange to specified address.
*
* Can be called only by contract owner.
*
* @param _recipient address to transfer wei to.
* @param _amount amount of wei to transfer.
*
* @return success.
*/
function withdrawEth(address _recipient, uint _amount) onlyContractOwner returns (uint) {
if (this.balance < _amount) {
return _error(ERROR_EXCHANGE_INSUFFICIENT_ETHER_SUPPLY);
}
if (!_recipient.send(_amount)) {
return _error(ERROR_EXCHANGE_TRANSFER_FAILED);
}
WithdrawEth(_recipient, _amount);
return OK;
}
/**
* Transfer all wei from exchange to specified address.
*
* Can be called only by contract owner.
*
* @param _recipient address to transfer wei to.
*
* @return success.
*/
function withdrawAllEth(address _recipient) onlyContractOwner() returns (uint) {
return withdrawEth(_recipient, this.balance);
}
/**
* Transfer all tokens and wei from exchange to specified address.
*
* Can be called only by contract owner.
*
* @param _recipient address to transfer tokens and wei to.
*
* @return success.
*/
function withdrawAll(address _recipient) onlyContractOwner returns (uint) {
uint withdrawAllTokensResult = withdrawAllTokens(_recipient);
if (withdrawAllTokensResult != OK) {
return withdrawAllTokensResult;
}
uint withdrawAllEthResult = withdrawAllEth(_recipient);
if (withdrawAllEthResult != OK) {
return withdrawAllEthResult;
}
return OK;
}
function emitError(uint errorCode) {
Error(errorCode);
}
function emitPricesUpdated(uint buyPrice, uint sellPrice) {
PricesUpdated(msg.sender, buyPrice, sellPrice);
}
function emitActiveChanged(bool isActive) {
ActiveChanged(msg.sender, isActive);
}
function getEventsHistory() constant returns (BuyBackEmitter) {
return address(eventsHistory) != 0x0 ? eventsHistory : BuyBackEmitter(this);
}
/**
* Overflow-safe multiplication.
*
* Throws in case of value overflow.
*
* @param _a first operand.
* @param _b second operand.
*
* @return multiplication result.
*/
function _mul(uint _a, uint _b) internal constant returns (uint) {
uint result = _a * _b;
if (_a != 0 && result / _a != _b) {
throw;
}
return result;
}
/**
* Accept all ether to maintain exchange supply.
*/
function() payable {
if (msg.value != 0) {
ReceivedEther(msg.sender, msg.value);
} else {
throw;
}
}
}
|
* Set exchange operation prices. Sell price cannot be less than buy price. Can be set only by contract owner. @param _buyPrice price in wei at which exchange buys tokens. @param _sellPrice price in wei at which exchange sells tokens. @return success./
|
function setPrices(uint _buyPrice, uint _sellPrice) onlyContractOwner returns (uint) {
if (_sellPrice < _buyPrice) {
return _error(ERROR_EXCHANGE_INVALID_PRICE);
}
buyPrice = _buyPrice;
sellPrice = _sellPrice;
_emitPricesUpdated(_buyPrice, _sellPrice);
return OK;
}
| 7,657,836 |
[
1,
694,
7829,
1674,
19827,
18,
348,
1165,
6205,
2780,
506,
5242,
2353,
30143,
6205,
18,
4480,
506,
444,
1338,
635,
6835,
3410,
18,
225,
389,
70,
9835,
5147,
6205,
316,
732,
77,
622,
1492,
7829,
25666,
1900,
2430,
18,
225,
389,
87,
1165,
5147,
6205,
316,
732,
77,
622,
1492,
7829,
357,
3251,
2430,
18,
327,
2216,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
31862,
12,
11890,
389,
70,
9835,
5147,
16,
2254,
389,
87,
1165,
5147,
13,
1338,
8924,
5541,
1135,
261,
11890,
13,
288,
203,
3639,
309,
261,
67,
87,
1165,
5147,
411,
389,
70,
9835,
5147,
13,
288,
203,
5411,
327,
389,
1636,
12,
3589,
67,
2294,
14473,
67,
9347,
67,
7698,
1441,
1769,
203,
3639,
289,
203,
203,
3639,
30143,
5147,
273,
389,
70,
9835,
5147,
31,
203,
3639,
357,
80,
5147,
273,
389,
87,
1165,
5147,
31,
203,
3639,
389,
18356,
31862,
7381,
24899,
70,
9835,
5147,
16,
389,
87,
1165,
5147,
1769,
203,
203,
3639,
327,
7791,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-22
*/
// SPDX-License-Identifier: MIT
// Author: 0xTycoon
// Repo: github.com/0xTycoon/punksceo
pragma solidity ^0.8.11;
//import "./safemath.sol"; // don't need since v0.8
//import "./ceo.sol";
/*
PUNKS CEO (and "Cigarette" token)
WEB: https://punksceo.eth.limo / https://punksceo.eth.link
IPFS: See content hash record for punksceo.eth
Token Address: cigtoken.eth
There is NO trade tax or any other fee in the standard ERC20 methods of this token.
The "CEO of CryptoPunks" game element is optional and implemented for your entertainment.
### THE RULES OF THE GAME
1. Anybody can buy the CEO title at any time using Cigarettes. (The CEO of all cryptopunks)
2. When buying the CEO title, you must nominate a punk, set the price and pre-pay the tax.
3. The CEO title can be bought from the existing CEO at any time.
4. To remain a CEO, a daily tax needs to be paid.
5. The tax is 0.1% of the price to buy the CEO title, to be charged per epoch.
6. The CEO can be removed if they fail to pay the tax. A reward of CIGs is paid to the whistleblower.
7. After Removing a CEO: A dutch auction is held, where the price will decrease 10% every half-an-epoch.
8. The price can be changed by the CEO at any time. (Once per block)
9. An epoch is 7200 blocks.
10. All the Cigarettes from the sale are burned.
11. All tax is burned
12. After buying the CEO title, the old CEO will get their unspent tax deposit refunded
### CEO perk
13. The CEO can increase or decrease the CIG farming block reward by 20% every 2nd epoch!
However, note that the issuance can never be more than 1000 CIG per block, also never under 0.0001 CIG.
14. THE CEO gets to hold a NFT in their wallet. There will only be ever 1 this NFT.
The purpose of this NFT is so that everyone can see that they are the CEO.
IMPORTANT: This NFT will be revoked once the CEO title changes.
Also, the NFT cannot be transferred by the owner, the only way to transfer is for someone else to buy the CEO title! (Think of this NFT as similar to a "title belt" in boxing.)
END
* states
* 0 = initial
* 1 = CEO reigning
* 2 = Dutch auction
Notes:
It was decided that whoever buys the CEO title does not have to hold a punk and can nominate any punk they wish.
This is because some may hold their punks in cold storage, plus checking ownership costs additional gas.
Besides, CEOs are usually appointed by the board.
Credits:
- LP Staking based on code from SushiSwap's MasterChef.sol
- ERC20 & SafeMath based on lib from OpenZeppelin
*/
contract Cig {
//using SafeMath for uint256; // no need since Solidity 0.8
// ERC20 stuff
string public constant name = "Cigarette Token";
string public constant symbol = "CIG";
uint8 public constant decimals = 18;
uint256 public totalSupply = 0;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// UserInfo keeps track of user LP deposits and withdrawals
struct UserInfo {
uint256 deposit; // How many LP tokens the user has deposited.
uint256 rewardDebt; // keeps track of how much reward was paid out
}
mapping(address => UserInfo) public userInfo; // keeps track of UserInfo for each staking address
address public admin; // admin is used for deployment, burned after
ILiquidityPoolERC20 public lpToken; // lpToken is the address of LP token contract that's being staked.
uint256 public lastRewardBlock; // Last block number that cigarettes distribution occurs.
uint256 public accCigPerShare; // Accumulated cigarettes per share, times 1e12. See below.
uint256 public cigPerBlock; // CIGs per-block rewarded and split with LPs
bytes32 public graffiti; // a 32 character graffiti set when buying a CEO
ICryptoPunk public punks; // a reference to the CryptoPunks contract
event Deposit(address indexed user, uint256 amount); // when depositing LP tokens to stake, or harvest
event Withdraw(address indexed user, uint256 amount); // when withdrawing LP tokens form staking
event EmergencyWithdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed
event RewardUp(uint256 reward, uint256 upAmount); // when cigPerBlock is increased
event RewardDown(uint256 reward, uint256 downAmount); // when cigPerBlock is decreased
event Claim(address indexed owner, uint indexed punkIndex, uint256 value); // when a punk is claimed
mapping(uint => bool) public claims; // keep track of claimed punks
modifier onlyAdmin {
require(
msg.sender == admin,
"Only admin can call this"
);
_;
}
uint256 constant MIN_PRICE = 1e12; // 0.000001 CIG
uint256 constant CLAIM_AMOUNT = 100000 ether; // claim amount for each punk
uint256 constant MIN_REWARD = 1e14; // minimum block reward of 0.0001 CIG (1e14 wei)
uint256 constant MAX_REWARD = 1000 ether; // maximum block reward of 1000 CIG
address public The_CEO; // address of CEO
uint public CEO_punk_index; // which punk id the CEO is using
uint256 public CEO_price = 50000 ether; // price to buy the CEO title
uint256 public CEO_state; // state has 3 states, described above.
uint256 public CEO_tax_balance; // deposit to be used to pay the CEO tax
uint256 public taxBurnBlock; // The last block when the tax was burned
uint256 public rewardsChangedBlock; // which block was the last reward increase / decrease
uint256 private immutable CEO_epoch_blocks; // secs per day divided by 12 (86400 / 12), assuming 12 sec blocks
uint256 private immutable CEO_auction_blocks; // 3600 blocks
event NewCEO(address indexed user, uint indexed punk_id, uint256 new_price, bytes32 graffiti); // when a CEO is bought
event TaxDeposit(address indexed user, uint256 amount); // when tax is deposited
event RevenueBurned(address indexed user, uint256 amount); // when tax is burned
event TaxBurned(address indexed user, uint256 amount); // when tax is burned
event CEODefaulted(address indexed called_by, uint256 reward); // when CEO defaulted on tax
event CEOPriceChange(uint256 price); // when CEO changed price
modifier onlyCEO {
require(
msg.sender == The_CEO,
"only CEO can call this"
);
_;
}
IRouterV2 private immutable V2ROUTER; // address of router used to get the price quote
ICEOERC721 private immutable The_NFT; // reference to the CEO NFT token
address private immutable MASTERCHEF_V2; // address pointing to SushiSwap's MasterChefv2 contract
/**
* @dev constructor
* @param _startBlock starting block when rewards start
* @param _cigPerBlock Number of CIG tokens rewarded per block
* @param _punks address of the cryptopunks contract
* @param _CEO_epoch_blocks how many blocks between each epochs
* @param _CEO_auction_blocks how many blocks between each auction discount
* @param _CEO_price starting price to become CEO (in CIG)
* @param _MASTERCHEF_V2 address of the MasterChefv2 contract
*/
constructor(
uint256 _startBlock,
uint256 _cigPerBlock,
address _punks,
uint _CEO_epoch_blocks,
uint _CEO_auction_blocks,
uint256 _CEO_price,
address _MASTERCHEF_V2,
bytes32 _graffiti,
address _NFT,
address _V2ROUTER
) {
lastRewardBlock = _startBlock;
cigPerBlock = _cigPerBlock;
admin = msg.sender; // the admin key will be burned after deployment
punks = ICryptoPunk(_punks);
CEO_epoch_blocks = _CEO_epoch_blocks;
CEO_auction_blocks = _CEO_auction_blocks;
CEO_price = _CEO_price;
MASTERCHEF_V2 = _MASTERCHEF_V2;
graffiti = _graffiti;
The_NFT = ICEOERC721(_NFT);
V2ROUTER = IRouterV2(_V2ROUTER);
// mint the tokens for the airdrop and place them in the CryptoPunks contract.
mint(_punks, CLAIM_AMOUNT * 10000);
}
/**
* @dev renounceOwnership burns the admin key, so this contract is unruggable
*/
function renounceOwnership() external onlyAdmin {
admin = address(0);
}
/**
* @dev setStartingBlock sets the starting block for LP staking rewards
* Admin only, used only for initial configuration.
* @param _startBlock the block to start rewards for
*/
function setStartingBlock(uint256 _startBlock) external onlyAdmin {
lastRewardBlock = _startBlock;
}
/**
* @dev setPool address to an LP pool. Only Admin. (used only in testing/deployment)
*/
function setPool(ILiquidityPoolERC20 _addr) external onlyAdmin {
require(address(lpToken) == address(0), "pool already set");
lpToken = _addr;
}
/**
* @dev setReward sets the reward. Admin only (used only in testing/deployment)
*/
function setReward(uint256 _value) public onlyAdmin {
cigPerBlock = _value;
}
/**
* @dev buyCEO allows anybody to be the CEO
* @param _max_spend the total CIG that can be spent
* @param _new_price the new price for the punk (in CIG)
* @param _tax_amount how much to pay in advance (in CIG)
* @param _punk_index the id of the punk 0-9999
* @param _graffiti a little message / ad from the buyer
*/
function buyCEO(
uint256 _max_spend,
uint256 _new_price,
uint256 _tax_amount,
uint256 _punk_index,
bytes32 _graffiti
) external {
if (CEO_state == 1 && (taxBurnBlock != block.number)) {
_burnTax(); // _burnTax can change CEO_state to 2
}
if (CEO_state == 2) {
// Auction state. The price goes down 10% every `CEO_auction_blocks` blocks
CEO_price = _calcDiscount();
}
require (CEO_price + _tax_amount <= _max_spend, "overpaid"); // prevent CEO over-payment
require (_new_price >= MIN_PRICE, "price 2 smol"); // price cannot be under 0.000001 CIG
require (_punk_index <= 9999, "invalid punk"); // validate the punk index
require (_tax_amount >= _new_price / 1000, "insufficient tax" ); // at least %0.1 fee paid for 1 epoch
transfer(address(this), CEO_price); // pay for the CEO title
burn(address(this), CEO_price); // burn the revenue
emit RevenueBurned(msg.sender, CEO_price);
_returnDeposit(The_CEO, CEO_tax_balance); // return deposited tax back to old CEO
transfer(address(this), _tax_amount); // deposit tax (reverts if not enough)
CEO_tax_balance = _tax_amount; // store the tax deposit amount
_transferNFT(The_CEO, msg.sender); // yank the NFT to the new CEO
CEO_price = _new_price; // set the new price
CEO_punk_index = _punk_index; // store the punk id
The_CEO = msg.sender; // store the CEO's address
taxBurnBlock = block.number; // store the block number
// (tax may not have been burned if the
// previous state was 0)
CEO_state = 1;
graffiti = _graffiti;
emit TaxDeposit(msg.sender, _tax_amount);
emit NewCEO(msg.sender, _punk_index, _new_price, _graffiti);
}
/**
* @dev _returnDeposit returns the tax deposit back to the CEO
* @param _to address The address which you want to transfer to
* remember to update CEO_tax_balance after calling this
*/
function _returnDeposit(
address _to,
uint256 _amount
)
internal
{
if (_amount == 0) {
return;
}
balanceOf[address(this)] = balanceOf[address(this)] - _amount;
balanceOf[_to] = balanceOf[_to] + _amount;
emit Transfer(address(this), _to, _amount);
//CEO_tax_balance = 0; // can be omitted since value gets overwritten by caller
}
/**
* @dev transfer the NFT to a new wallet
*/
function _transferNFT(address _oldCEO, address _newCEO) internal {
if (_oldCEO != _newCEO) {
The_NFT.transferFrom(_oldCEO, _newCEO, 0);
}
}
/**
* @dev depositTax pre-pays tax for the existing CEO.
* It may also burn any tax debt the CEO may have.
* @param _amount amount of tax to pre-pay
*/
function depositTax(uint256 _amount) external onlyCEO {
require (CEO_state == 1, "no CEO");
if (_amount > 0) {
transfer(address(this), _amount); // place the tax on deposit
CEO_tax_balance = CEO_tax_balance + _amount; // record the balance
emit TaxDeposit(msg.sender, _amount);
}
if (taxBurnBlock != block.number) {
_burnTax(); // settle any tax debt
taxBurnBlock = block.number;
}
}
/**
* @dev burnTax is called to burn tax.
* It removes the CEO if tax is unpaid.
* 1. deduct tax, update last update
* 2. if not enough tax, remove & begin auction
* 3. reward the caller by minting a reward from the amount indebted
* A Dutch auction begins where the price decreases 10% every hour.
*/
function burnTax() external {
if (taxBurnBlock == block.number) return;
if (CEO_state == 1) {
_burnTax();
taxBurnBlock = block.number;
}
}
/**
* @dev _burnTax burns any tax debt. Boots the CEO if defaulted, paying a reward to the caller
*/
function _burnTax() internal {
// calculate tax per block (tpb)
uint256 tpb = CEO_price / 1000 / CEO_epoch_blocks; // 0.1% per epoch
uint256 debt = (block.number - taxBurnBlock) * tpb;
if (CEO_tax_balance !=0 && CEO_tax_balance >= debt) { // Does CEO have enough deposit to pay debt?
CEO_tax_balance = CEO_tax_balance - debt; // deduct tax
burn(address(this), debt); // burn the tax
emit TaxBurned(msg.sender, debt);
} else {
// CEO defaulted
uint256 default_amount = debt - CEO_tax_balance; // calculate how much defaulted
burn(address(this), CEO_tax_balance); // burn the tax
emit TaxBurned(msg.sender, CEO_tax_balance);
CEO_state = 2; // initiate a Dutch auction.
CEO_tax_balance = 0;
_transferNFT(The_CEO, address(this)); // This contract holds the NFT temporarily
The_CEO = address(this); // This contract is the "interim CEO"
mint(msg.sender, default_amount); // reward the caller for reporting tax default
emit CEODefaulted(msg.sender, default_amount);
}
}
/**
* @dev setPrice changes the price for the CEO title.
* @param _price the price to be paid. The new price most be larger tan MIN_PRICE and not default on debt
*/
function setPrice(uint256 _price) external onlyCEO {
require(CEO_state == 1, "No CEO in charge");
require (_price >= MIN_PRICE, "price 2 smol");
require (CEO_tax_balance >= _price / 1000, "price would default"); // need at least 0.1% for tax
if (block.number != taxBurnBlock) {
_burnTax();
taxBurnBlock = block.number;
}
// The state is 1 if the CEO hasn't defaulted on tax
if (CEO_state == 1) {
CEO_price = _price; // set the new price
emit CEOPriceChange(_price);
}
}
/**
* @dev rewardUp allows the CEO to increase the block rewards by %1
* Can only be called by the CEO every 7 epochs
* @return _amount increased by
*/
function rewardUp() external onlyCEO returns (uint256) {
require(CEO_state == 1, "No CEO in charge");
require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks");
require (cigPerBlock <= MAX_REWARD, "reward already max");
rewardsChangedBlock = block.number;
uint256 _amount = cigPerBlock / 5; // %20
uint256 _new_reward = cigPerBlock + _amount;
if (_new_reward > MAX_REWARD) {
_amount = MAX_REWARD - cigPerBlock;
_new_reward = MAX_REWARD; // cap
}
cigPerBlock = _new_reward;
emit RewardUp(_new_reward, _amount);
return _amount;
}
/**
* @dev rewardDown decreases the block rewards by 1%
* Can only be called by the CEO every 7 epochs
*/
function rewardDown() external onlyCEO returns (uint256) {
require(CEO_state == 1, "No CEO in charge");
require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks");
require(cigPerBlock >= MIN_REWARD, "reward already low");
rewardsChangedBlock = block.number;
uint256 _amount = cigPerBlock / 5; // %20
uint256 _new_reward = cigPerBlock - _amount;
if (_new_reward < MIN_REWARD) {
_amount = cigPerBlock - MIN_REWARD;
_new_reward = MIN_REWARD;
}
cigPerBlock = _new_reward;
emit RewardDown(_new_reward, _amount);
return _amount;
}
/**
* @dev _calcDiscount calculates the discount for the CEO title based on how many blocks passed
*/
function _calcDiscount() internal view returns (uint256) {
unchecked {
uint256 d = (CEO_price / 10) // 10% discount
// multiply by the number of discounts accrued
* (block.number - taxBurnBlock) / CEO_auction_blocks;
if (d > CEO_price) {
// overflow assumed, reset to MIN_PRICE
return MIN_PRICE;
}
uint256 price = CEO_price - d;
if (price < MIN_PRICE) {
price = MIN_PRICE;
}
return price;
}
}
/**
* @dev getStats helps to fetch some stats for the GUI in a single web3 call
* @param _user the address to return the report for
* @return uint256[22] the stats
* @return address of the current CEO
* @return bytes32 Current graffiti
*/
function getStats(address _user) external view returns(uint256[] memory, address, bytes32, uint112[] memory) {
uint[] memory ret = new uint[](22);
uint112[] memory reserves = new uint112[](2);
uint256 tpb = (CEO_price / 1000) / (CEO_epoch_blocks); // 0.1% per epoch
uint256 debt = (block.number - taxBurnBlock) * tpb;
uint256 price = CEO_price;
UserInfo memory info = userInfo[_user];
if (CEO_state == 2) {
price = _calcDiscount();
}
ret[0] = CEO_state;
ret[1] = CEO_tax_balance;
ret[2] = taxBurnBlock; // the block number last tax burn
ret[3] = rewardsChangedBlock; // the block of the last staking rewards change
ret[4] = price; // price of the CEO title
ret[5] = CEO_punk_index; // punk ID of CEO
ret[6] = cigPerBlock; // staking reward per block
ret[7] = totalSupply; // total supply of CIG
if (address(lpToken) != address(0)) {
ret[8] = lpToken.balanceOf(address(this)); // Total LP staking
ret[16] = lpToken.balanceOf(_user); // not staked by user
ret[17] = pendingCig(_user); // pending harvest
(reserves[0], reserves[1], ) = lpToken.getReserves(); // uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast
ret[18] = V2ROUTER.getAmountOut(1 ether, uint(reserves[0]), uint(reserves[1])); // CIG price in ETH
if (isContract(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2))) { // are we on mainnet?
ILiquidityPoolERC20 ethusd = ILiquidityPoolERC20(address(0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f)); // sushi DAI-WETH pool
uint112 r0;
uint112 r1;
(r0, r1, ) = ethusd.getReserves();
// get the price of ETH in USD
ret[19] = V2ROUTER.getAmountOut(1 ether, uint(r0), uint(r1)); // ETH price in USD
}
}
ret[9] = block.number; // current block number
ret[10] = tpb; // "tax per block" (tpb)
ret[11] = debt; // tax debt accrued
ret[12] = lastRewardBlock; // the block of the last staking rewards payout update
ret[13] = info.deposit; // amount of LP tokens staked by user
ret[14] = info.rewardDebt; // amount of rewards paid out
ret[15] = balanceOf[_user]; // amount of CIG held by user
ret[20] = balanceOf[address(0)]; // amount of CIG burned
ret[21] = balanceOf[address(punks)]; // amount of CIG to be claimed
return (ret, The_CEO, graffiti, reserves);
}
/*
* ************************ Token distribution and farming stuff ****************
*/
/**
* Claim claims the initial CIG airdrop using a punk
* @param _punkIndex the index of the punk, number between 0-9999
*/
function claim(uint256 _punkIndex) external returns(bool) {
require (_punkIndex <= 9999, "invalid punk");
require(claims[_punkIndex] == false, "punk already claimed");
require(msg.sender == punks.punkIndexToAddress(_punkIndex), "punk 404");
claims[_punkIndex] = true;
balanceOf[address(punks)] = balanceOf[address(punks)] - CLAIM_AMOUNT; // deduct from the punks contract
balanceOf[msg.sender] = balanceOf[msg.sender] + CLAIM_AMOUNT; // deposit to the caller
emit Transfer(address(punks), msg.sender, CLAIM_AMOUNT);
emit Claim(msg.sender, _punkIndex, CLAIM_AMOUNT);
return true;
}
/**
* @dev update updates the accCigPerShare value and mints new CIG rewards to be distributed to LP stakers
* Credits go to MasterChef.sol
* Modified the original by removing poolInfo as there is only a single pool
* Removed totalAllocPoint and pool.allocPoint
* pool.lastRewardBlock moved to lastRewardBlock
* There is no need for getMultiplier (rewards are adjusted by the CEO)
*
*/
function update() public {
if (block.number <= lastRewardBlock) {
return;
}
uint256 lpSupply = lpToken.balanceOf(address(this));
if (lpSupply == 0) {
lastRewardBlock = block.number;
return;
}
// mint some new cigarette rewards to be distributed
uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock;
mint(address(this), cigReward);
accCigPerShare = accCigPerShare + (
cigReward * 1e12 / lpSupply
);
lastRewardBlock = block.number;
}
/**
* @dev pendingCig displays the amount of cig to be claimed
* @param _user the address to report
*/
function pendingCig(address _user) view public returns (uint256) {
uint256 _acps = accCigPerShare;
// accumulated cig per share
UserInfo storage user = userInfo[_user];
uint256 lpSupply = lpToken.balanceOf(address(this));
if (block.number > lastRewardBlock && lpSupply != 0) {
uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock;
_acps = _acps + (
cigReward * 1e12 / lpSupply
);
}
return (user.deposit * _acps / 1e12) - user.rewardDebt;
}
/**
* @dev deposit deposits LP tokens to be staked. It also harvests rewards.
* @param _amount the amount of LP tokens to deposit. Assumes this contract has been approved for the _amount.
*/
function deposit(uint256 _amount) public {
UserInfo storage user = userInfo[msg.sender];
update();
if (user.deposit > 0) {
uint256 pending =
(user.deposit * (accCigPerShare) / 1e12) - user.rewardDebt;
safeSendPayout(msg.sender, pending);
}
if (_amount > 0) {
lpToken.transferFrom(
address(msg.sender),
address(this),
_amount
);
user.deposit = user.deposit + _amount;
emit Deposit(msg.sender, _amount);
}
user.rewardDebt = user.deposit * accCigPerShare / 1e12;
}
/**
* @dev withdraw takes out the LP tokens and pending rewards
* @param _amount the amount to withdraw
*/
function withdraw(uint256 _amount) external {
UserInfo storage user = userInfo[msg.sender];
require(user.deposit >= _amount, "withdraw: not good");
update();
uint256 pending = (user.deposit * accCigPerShare / 1e12) - user.rewardDebt;
safeSendPayout(msg.sender, pending);
user.deposit = user.deposit - _amount;
user.rewardDebt = user.deposit * accCigPerShare / 1e12;
lpToken.transfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _amount);
}
/**
* @dev emergencyWithdraw does a withdraw without caring about rewards. EMERGENCY ONLY.
*/
function emergencyWithdraw() external {
UserInfo storage user = userInfo[msg.sender];
uint256 amount = user.deposit;
user.deposit = 0;
user.rewardDebt = 0;
lpToken.transfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, amount);
}
/**
* @dev safeSendPayout, just in case if rounding error causes pool to not have enough CIGs.
* @param _to recipient address
* @param _amount the value to send
*/
function safeSendPayout(address _to, uint256 _amount) internal {
uint256 cigBal = balanceOf[address(this)];
if (_amount > cigBal) {
_amount = cigBal;
}
balanceOf[address(this)] = balanceOf[address(this)] - _amount;
balanceOf[_to] = balanceOf[_to] + _amount;
emit Transfer(address(this), _to, _amount);
}
/*
* ************************ ERC20 Token stuff ********************************
*/
/**
* @dev burn some tokens
* @param _from The address to burn from
* @param _amount The amount to burn
*/
function burn(address _from, uint256 _amount) internal {
balanceOf[_from] = balanceOf[_from] - _amount;
totalSupply = totalSupply - _amount;
emit Transfer(_from, address(0), _amount);
}
/**
* @dev mint new tokens
* @param _to The address to mint to.
* @param _amount The amount to be minted.
*/
function mint(address _to, uint256 _amount) internal {
require(_to != address(0), "ERC20: mint to the zero address");
totalSupply = totalSupply + _amount;
balanceOf[_to] = balanceOf[_to] + _amount;
emit Transfer(address(0), _to, _amount);
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
// require(_value <= balanceOf[msg.sender], "value exceeds balance"); // SafeMath already checks this
balanceOf[msg.sender] = balanceOf[msg.sender] - _value;
balanceOf[_to] = balanceOf[_to] + _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
//require(_value <= balanceOf[_from], "value exceeds balance"); // SafeMath already checks this
require(_value <= allowance[_from][msg.sender], "not approved");
balanceOf[_from] = balanceOf[_from] - _value;
balanceOf[_to] = balanceOf[_to] + _value;
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve tokens of mount _value to be spent by _spender
* @param _spender address The spender
* @param _value the stipend to spend
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/********************************************************************
* @dev onSushiReward IRewarder methods to be called by the SushSwap MasterChefV2 contract
*/
function onSushiReward (
uint256 /* pid */,
address _user,
address _to,
uint256 /* sushiAmount*/,
uint256 _newLpAmount) external onlyMCV2 {
UserInfo storage user = userInfo[_user];
update();
if (user.deposit > 0) {
uint256 pending = (user.deposit * accCigPerShare / 1e12) - user.rewardDebt;
safeSendPayout(_to, pending);
}
user.deposit = _newLpAmount;
user.rewardDebt = user.deposit * accCigPerShare / 1e12;
}
/**
* pendingTokens returns the number of pending CIG rewards, implementing IRewarder
* @param user it is the only parameter we look at
*/
function pendingTokens(uint256 pid, address user, uint256 sushiAmount) external view returns (IERC20[] memory, uint256[] memory) {
IERC20[] memory _rewardTokens = new IERC20[](1);
_rewardTokens[0] = IERC20(address(this));
uint256[] memory _rewardAmounts = new uint256[](1);
_rewardAmounts[0] = pendingCig(user);
return (_rewardTokens, _rewardAmounts);
}
// onlyMCV2 ensures only the MasterChefV2 contract can call this
modifier onlyMCV2 {
require(
msg.sender == MASTERCHEF_V2,
"Only MCV2"
);
_;
}
/**
* @dev Returns true if `account` is a contract.
*
* credits https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
/**
* @dev sushi router 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F
*/
interface IRouterV2 {
function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external pure returns(uint256 amountOut);
}
interface ICryptoPunk {
//function balanceOf(address account) external view returns (uint256);
function punkIndexToAddress(uint256 punkIndex) external returns (address);
//function punksOfferedForSale(uint256 punkIndex) external returns (bool, uint256, address, uint256, address);
//function buyPunk(uint punkIndex) external payable;
//function transferPunk(address to, uint punkIndex) external;
}
interface ICEOERC721 {
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
}
// IRewarder allows the contract to be called by SushSwap MasterChefV2
// example impl https://etherscan.io/address/0x7519c93fc5073e15d89131fd38118d73a72370f8/advanced#code
interface IRewarder {
function onSushiReward(uint256 pid, address user, address recipient, uint256 sushiAmount, uint256 newLpAmount) external;
function pendingTokens(uint256 pid, address user, uint256 sushiAmount) external view returns (IERC20[] memory, uint256[] memory);
}
/*
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 is IRewarder {
/**
* @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
* 0xTycoon was here
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev from UniswapV2Pair.sol
*/
interface ILiquidityPoolERC20 is IERC20 {
function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast);
}
|
the admin key will be burned after deployment
|
admin = msg.sender;
| 2,101,461 |
[
1,
5787,
3981,
498,
903,
506,
18305,
329,
1839,
6314,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
3981,
2868,
273,
1234,
18,
15330,
31,
5375,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x0996A41Eb04e33BBd0048350e6c5e4103a4aec8d/sources/contracts/Company.sol
|
Call the employee's address with the specified amount in WEI (Transer / Withdraw).
|
function withdrawToken() public onlyCollaborators {
uint256 amount = calculateAllowedWithdrawal();
_EthPrice = PriceConverter.getEthPrice();
_CompanyBalance = _CompanyBalance - amount;
require(success, "Withdraw Failed");
}
| 862,573 |
[
1,
1477,
326,
24539,
1340,
1807,
1758,
598,
326,
1269,
3844,
316,
13880,
45,
261,
17730,
550,
342,
3423,
9446,
2934,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
598,
9446,
1345,
1435,
1071,
1338,
22894,
31391,
225,
288,
203,
1377,
2254,
5034,
3844,
273,
4604,
5042,
1190,
9446,
287,
5621,
203,
3639,
389,
41,
451,
5147,
273,
20137,
5072,
18,
588,
41,
451,
5147,
5621,
203,
3639,
389,
12627,
13937,
273,
389,
12627,
13937,
300,
3844,
31,
7010,
203,
3639,
2583,
12,
4768,
16,
315,
1190,
9446,
11175,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.12;
import { Context } from "@openzeppelin/contracts/GSN/Context.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC777 } from "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import { IERC777Recipient } from "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import { IERC777Sender } from "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC1820Registry } from "@openzeppelin/contracts/introspection/IERC1820Registry.sol";
import { RuntimeConstants } from "./RuntimeConstants.sol";
// ERC777 is inlined because we need to change `_callTokensToSend` to protect against Uniswap replay attacks
/**
* @dev Implementation of the {IERC777} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract ERC777 is RuntimeConstants, Context, IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant private TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
// KEYDONIX: Protect against Uniswap Exchange reentrancy bug: https://blog.openzeppelin.com/exploiting-uniswap-from-reentrancy-to-actual-profit/
bool uniswapExchangeReentrancyGuard = false;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(string memory name, string memory symbol, address[] memory defaultOperators) public {
_name = name;
_symbol = symbol;
_defaultOperatorsArray = defaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20Detailed-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes calldata data) external {
_send(_msgSender(), _msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes calldata data) external {
_burn(_msgSender(), _msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(address operator, address tokenHolder) public view returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) external {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) external {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {Transfer} events.
*/
function operatorSend(address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData) external {
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(_msgSender(), sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(_msgSender(), account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) external returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {Transfer} and {Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
// KEYDONIX: Block re-entrancy specifically for uniswap, which is vulnerable to ERC-777 tokens
if (msg.sender == uniswapExchange) {
require(!uniswapExchangeReentrancyGuard, "Attempted to execute a Uniswap exchange while in the middle of a Uniswap exchange");
uniswapExchangeReentrancyGuard = true;
}
_callTokensToSend(spender, holder, recipient, amount, "", "");
if (msg.sender == uniswapExchange) {
uniswapExchangeReentrancyGuard = false;
}
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData) internal {
require(account != address(0), "ERC777: mint to the zero address");
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
// KEYDONIX: changed visibility from private to internal, we reference this function in derived contract
/**
* @dev Send tokens
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck) internal {
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
// KEYDONIX: changed visibility from private to internal, we reference this function in derived contract
/**
* @dev Burn tokens
* @param operator address operator requesting the operation
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData) internal {
require(from != address(0), "ERC777: burn from the zero address");
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData) private {
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
function _approve(address holder, address spender, uint256 value) private {
// TODO: restore this require statement if this function becomes internal, or is called at a new callsite. It is
// currently unnecessary.
//require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData) private {
address implementer = _erc1820.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck) private {
address implementer = _erc1820.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
}
contract MakerFunctions {
// KEYDONIX: Renamed from `rmul` for clarity
// KEYDONIX: Changed ONE to 10**27 for clarity
function safeMul27(uint x, uint y) internal pure returns (uint z) {
z = safeMul(x, y) / 10 ** 27;
}
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)
}
}
}
}
}
// KEYDONIX: Renamed from `mul` due to shadowing warning from Solidity
function safeMul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
}
contract ReverseRegistrar {
function setName(string memory name) public returns (bytes32 node);
}
contract DaiHrd is ERC777, MakerFunctions {
event Deposit(address indexed from, uint256 depositedAttodai, uint256 mintedAttodaiHrd);
event Withdrawal(address indexed from, address indexed to, uint256 withdrawnAttodai, uint256 burnedAttodaiHrd);
event DepositVatDai(address indexed account, uint256 depositedAttorontodai, uint256 mintedAttodaiHrd);
event WithdrawalVatDai(address indexed from, address indexed to, uint256 withdrawnAttorontodai, uint256 burnedAttodaiHrd);
// uses this super constructor syntax instead of the preferred alternative syntax because my editor doesn't like the class syntax
constructor(ReverseRegistrar reverseRegistrar) ERC777("DAI-HRD", "DAI-HRD", new address[](0)) public {
dai.approve(address(daiJoin), uint(-1));
vat.hope(address(pot));
vat.hope(address(daiJoin));
if (reverseRegistrar != ReverseRegistrar(0)) {
reverseRegistrar.setName("dai-hrd.eth");
}
}
function deposit(uint256 attodai) external returns(uint256 attodaiHrd) {
dai.transferFrom(msg.sender, address(this), attodai);
daiJoin.join(address(this), dai.balanceOf(address(this)));
uint256 depositedAttopot = depositVatDaiForAccount(msg.sender);
emit Deposit(msg.sender, attodai, depositedAttopot);
return depositedAttopot;
}
// If the user has vat dai directly (after performing vault actions, for instance), they don't need to create the DAI ERC20 just so we can burn it, we'll accept vat dai
function depositVatDai(uint256 attorontovatDai) external returns(uint256 attodaiHrd) {
vat.move(msg.sender, address(this), attorontovatDai);
uint256 depositedAttopot = depositVatDaiForAccount(msg.sender);
emit DepositVatDai(msg.sender, attorontovatDai, depositedAttopot);
return depositedAttopot;
}
function withdrawTo(address recipient, uint256 attodaiHrd) external returns(uint256 attodai) {
// Don't need rontodaiPerPot, so we don't call updateAndFetchChi
if (pot.rho() != now) pot.drip();
return withdraw(recipient, attodaiHrd);
}
function withdrawToDenominatedInDai(address recipient, uint256 attodai) external returns(uint256 attodaiHrd) {
uint256 rontodaiPerPot = updateAndFetchChi();
attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot);
uint256 attodaiWithdrawn = withdraw(recipient, attodaiHrd);
require(attodaiWithdrawn >= attodai, "DaiHrd/withdrawToDenominatedInDai: Not withdrawing enough DAI to cover request");
return attodaiHrd;
}
function withdrawVatDai(address recipient, uint256 attodaiHrd) external returns(uint256 attorontodai) {
require(recipient != address(0) && recipient != address(this), "DaiHrd/withdrawVatDai: Invalid recipient");
// Don't need rontodaiPerPot, so we don't call updateAndFetchChi
if (pot.rho() != now) pot.drip();
_burn(address(0), msg.sender, attodaiHrd, new bytes(0), new bytes(0));
pot.exit(attodaiHrd);
attorontodai = vat.dai(address(this));
vat.move(address(this), recipient, attorontodai);
emit WithdrawalVatDai(msg.sender, recipient, attorontodai, attodaiHrd);
return attorontodai;
}
// Dai specific functions. These functions all behave similar to standard ERC777 functions with input or output denominated in Dai instead of DaiHrd
function balanceOfDenominatedInDai(address tokenHolder) external view returns(uint256 attodai) {
uint256 rontodaiPerPot = calculatedChi();
uint256 attodaiHrd = balanceOf(tokenHolder);
return convertAttodaiHrdToAttodai(attodaiHrd, rontodaiPerPot);
}
function totalSupplyDenominatedInDai() external view returns(uint256 attodai) {
uint256 rontodaiPerPot = calculatedChi();
return convertAttodaiHrdToAttodai(totalSupply(), rontodaiPerPot);
}
function sendDenominatedInDai(address recipient, uint256 attodai, bytes calldata data) external {
uint256 rontodaiPerPot = calculatedChi();
uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot);
_send(_msgSender(), _msgSender(), recipient, attodaiHrd, data, "", true);
}
function burnDenominatedInDai(uint256 attodai, bytes calldata data) external {
uint256 rontodaiPerPot = calculatedChi();
uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot);
_burn(_msgSender(), _msgSender(), attodaiHrd, data, "");
}
function operatorSendDenominatedInDai(address sender, address recipient, uint256 attodai, bytes calldata data, bytes calldata operatorData) external {
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
uint256 rontodaiPerPot = calculatedChi();
uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot);
_send(_msgSender(), sender, recipient, attodaiHrd, data, operatorData, true);
}
function operatorBurnDenominatedInDai(address account, uint256 attodai, bytes calldata data, bytes calldata operatorData) external {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
uint256 rontodaiPerPot = calculatedChi();
uint256 attodaiHrd = convertAttodaiToAttodaiHrd(attodai, rontodaiPerPot);
_burn(_msgSender(), account, attodaiHrd, data, operatorData);
}
// Utility Functions
function calculatedChi() public view returns (uint256 rontodaiPerPot) {
// mirrors Maker's calculation: rmul(rpow(dsr, now - rho, ONE), chi);
return safeMul27(rpow(pot.dsr(), now - pot.rho(), 10 ** 27), pot.chi());
}
function convertAttodaiToAttodaiHrd(uint256 attodai, uint256 rontodaiPerPot ) private pure returns (uint256 attodaiHrd) {
// + 1 is to compensate rounding? since attodaiHrd is rounded down
return attodai.mul(10 ** 27).add(rontodaiPerPot - 1).div(rontodaiPerPot);
}
function convertAttodaiHrdToAttodai(uint256 attodaiHrd, uint256 rontodaiPerPot ) private pure returns (uint256 attodai) {
return attodaiHrd.mul(rontodaiPerPot).div(10 ** 27);
}
function updateAndFetchChi() private returns (uint256 rontodaiPerPot) {
return (pot.rho() == now) ? pot.chi() : pot.drip();
}
// Takes whatever vat dai has already been transferred to DaiHrd, gives to pot (DSR) and mints tokens for user
function depositVatDaiForAccount(address account) private returns (uint256 attopotDeposited) {
uint256 rontodaiPerPot = updateAndFetchChi();
uint256 attopotToDeposit = vat.dai(address(this)) / rontodaiPerPot;
pot.join(attopotToDeposit);
_mint(address(0), account, attopotToDeposit, new bytes(0), new bytes(0));
return attopotToDeposit;
}
// Internal implementations of functions with multiple entrypoints. drip() should be called prior to this call
function withdraw(address recipient, uint256 attodaiHrd) private returns(uint256 attodaiWithdrawn) {
require(recipient != address(0) && recipient != address(this), "DaiHrd/withdraw: Invalid recipient");
_burn(address(0), msg.sender, attodaiHrd, new bytes(0), new bytes(0));
pot.exit(attodaiHrd);
daiJoin.exit(address(this), vat.dai(address(this)) / 10**27);
uint256 attodai = dai.balanceOf(address(this));
dai.transfer(recipient, attodai);
emit Withdrawal(msg.sender, recipient, attodai, attodaiHrd);
return attodai;
}
}
|
* @dev See {IERC20-approve}. Note that accounts cannot have allowance issued by their operators./
|
function approve(address spender, uint256 value) external returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
| 2,521,558 |
[
1,
9704,
288,
45,
654,
39,
3462,
17,
12908,
537,
5496,
3609,
716,
9484,
2780,
1240,
1699,
1359,
16865,
635,
3675,
12213,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
915,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
460,
13,
3903,
1135,
261,
6430,
13,
288,
203,
202,
202,
2867,
10438,
273,
389,
3576,
12021,
5621,
203,
202,
202,
67,
12908,
537,
12,
4505,
16,
17571,
264,
16,
460,
1769,
203,
202,
202,
2463,
638,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-15
*/
// SPDX-License-Identifier: GPL-3.0-or-later
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File @openzeppelin/contracts/utils/structs/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library 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;
}
}
// File interfaces/IGasBank.sol
pragma solidity 0.8.9;
interface IGasBank {
event Deposit(address indexed account, uint256 value);
event Withdraw(address indexed account, address indexed receiver, uint256 value);
function depositFor(address account) external payable;
function withdrawUnused(address account) external;
function withdrawFrom(address account, uint256 amount) external;
function withdrawFrom(
address account,
address payable to,
uint256 amount
) external;
function balanceOf(address account) external view returns (uint256);
}
// File interfaces/IVaultReserve.sol
pragma solidity 0.8.9;
interface IVaultReserve {
event Deposit(address indexed vault, address indexed token, uint256 amount);
event Withdraw(address indexed vault, address indexed token, uint256 amount);
event VaultListed(address indexed vault);
function deposit(address token, uint256 amount) external payable returns (bool);
function withdraw(address token, uint256 amount) external returns (bool);
function getBalance(address vault, address token) external view returns (uint256);
function canWithdraw(address vault) external view returns (bool);
}
// File interfaces/oracles/IOracleProvider.sol
pragma solidity 0.8.9;
interface IOracleProvider {
/// @notice Quotes the USD price of `baseAsset`
/// @param baseAsset the asset of which the price is to be quoted
/// @return the USD price of the asset
function getPriceUSD(address baseAsset) external view returns (uint256);
/// @notice Quotes the ETH price of `baseAsset`
/// @param baseAsset the asset of which the price is to be quoted
/// @return the ETH price of the asset
function getPriceETH(address baseAsset) external view returns (uint256);
}
// File interfaces/IPreparable.sol
pragma solidity 0.8.9;
interface IPreparable {
event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay);
event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay);
event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue);
event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue);
event ConfigReset(bytes32 indexed key);
}
// File interfaces/IStrategy.sol
pragma solidity 0.8.9;
interface IStrategy {
function name() external view returns (string memory);
function deposit() external payable returns (bool);
function balance() external view returns (uint256);
function withdraw(uint256 amount) external returns (bool);
function withdrawAll() external returns (uint256);
function harvestable() external view returns (uint256);
function harvest() external returns (uint256);
function strategist() external view returns (address);
function shutdown() external returns (bool);
function hasPendingFunds() external view returns (bool);
}
// File interfaces/IVault.sol
pragma solidity 0.8.9;
/**
* @title Interface for a Vault
*/
interface IVault is IPreparable {
event StrategyActivated(address indexed strategy);
event StrategyDeactivated(address indexed strategy);
/**
* @dev 'netProfit' is the profit after all fees have been deducted
*/
event Harvest(uint256 indexed netProfit, uint256 indexed loss);
function initialize(
address _pool,
uint256 _debtLimit,
uint256 _targetAllocation,
uint256 _bound
) external;
function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256);
function deposit() external payable;
function withdraw(uint256 amount) external returns (bool);
function initializeStrategy(address strategy_) external returns (bool);
function withdrawAll() external;
function withdrawFromReserve(uint256 amount) external;
function getStrategy() external view returns (IStrategy);
function getStrategiesWaitingForRemoval() external view returns (address[] memory);
function getAllocatedToStrategyWaitingForRemoval(address strategy)
external
view
returns (uint256);
function getTotalUnderlying() external view returns (uint256);
function getUnderlying() external view returns (address);
}
// File interfaces/pool/ILiquidityPool.sol
pragma solidity 0.8.9;
interface ILiquidityPool is IPreparable {
event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens);
event DepositFor(
address indexed minter,
address indexed mintee,
uint256 depositAmount,
uint256 mintedLpTokens
);
event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens);
event LpTokenSet(address indexed lpToken);
event StakerVaultSet(address indexed stakerVault);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256);
function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256);
function deposit(uint256 mintAmount) external payable returns (uint256);
function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256);
function depositAndStake(uint256 depositAmount, uint256 minTokenAmount)
external
payable
returns (uint256);
function depositFor(address account, uint256 depositAmount) external payable returns (uint256);
function depositFor(
address account,
uint256 depositAmount,
uint256 minTokenAmount
) external payable returns (uint256);
function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount)
external
returns (uint256);
function handleLpTokenTransfer(
address from,
address to,
uint256 amount
) external;
function executeNewVault() external returns (address);
function executeNewMaxWithdrawalFee() external returns (uint256);
function executeNewRequiredReserves() external returns (uint256);
function executeNewReserveDeviation() external returns (uint256);
function setLpToken(address _lpToken) external returns (bool);
function setStaker() external returns (bool);
function isCapped() external returns (bool);
function uncap() external returns (bool);
function updateDepositCap(uint256 _depositCap) external returns (bool);
function getUnderlying() external view returns (address);
function getLpToken() external view returns (address);
function getWithdrawalFee(address account, uint256 amount) external view returns (uint256);
function getVault() external view returns (IVault);
function exchangeRate() external view returns (uint256);
}
// File libraries/AddressProviderMeta.sol
pragma solidity 0.8.9;
library AddressProviderMeta {
struct Meta {
bool freezable;
bool frozen;
}
function fromUInt(uint256 value) internal pure returns (Meta memory) {
Meta memory meta;
meta.freezable = (value & 1) == 1;
meta.frozen = ((value >> 1) & 1) == 1;
return meta;
}
function toUInt(Meta memory meta) internal pure returns (uint256) {
uint256 value;
value |= meta.freezable ? 1 : 0;
value |= meta.frozen ? 1 << 1 : 0;
return value;
}
}
// File interfaces/IAddressProvider.sol
pragma solidity 0.8.9;
// solhint-disable ordering
interface IAddressProvider is IPreparable {
event KnownAddressKeyAdded(bytes32 indexed key);
event StakerVaultListed(address indexed stakerVault);
event StakerVaultDelisted(address indexed stakerVault);
event ActionListed(address indexed action);
event PoolListed(address indexed pool);
event PoolDelisted(address indexed pool);
event VaultUpdated(address indexed previousVault, address indexed newVault);
/** Key functions */
function getKnownAddressKeys() external view returns (bytes32[] memory);
function freezeAddress(bytes32 key) external;
/** Pool functions */
function allPools() external view returns (address[] memory);
function addPool(address pool) external;
function poolsCount() external view returns (uint256);
function getPoolAtIndex(uint256 index) external view returns (address);
function isPool(address pool) external view returns (bool);
function removePool(address pool) external returns (bool);
function getPoolForToken(address token) external view returns (ILiquidityPool);
function safeGetPoolForToken(address token) external view returns (address);
/** Vault functions */
function updateVault(address previousVault, address newVault) external;
function allVaults() external view returns (address[] memory);
function vaultsCount() external view returns (uint256);
function getVaultAtIndex(uint256 index) external view returns (address);
function isVault(address vault) external view returns (bool);
/** Action functions */
function allActions() external view returns (address[] memory);
function addAction(address action) external returns (bool);
function isAction(address action) external view returns (bool);
/** Address functions */
function initializeAddress(
bytes32 key,
address initialAddress,
bool frezable
) external;
function initializeAndFreezeAddress(bytes32 key, address initialAddress) external;
function getAddress(bytes32 key) external view returns (address);
function getAddress(bytes32 key, bool checkExists) external view returns (address);
function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory);
function prepareAddress(bytes32 key, address newAddress) external returns (bool);
function executeAddress(bytes32 key) external returns (address);
function resetAddress(bytes32 key) external returns (bool);
/** Staker vault functions */
function allStakerVaults() external view returns (address[] memory);
function tryGetStakerVault(address token) external view returns (bool, address);
function getStakerVault(address token) external view returns (address);
function addStakerVault(address stakerVault) external returns (bool);
function isStakerVault(address stakerVault, address token) external view returns (bool);
function isStakerVaultRegistered(address stakerVault) external view returns (bool);
function isWhiteListedFeeHandler(address feeHandler) external view returns (bool);
}
// File interfaces/IRoleManager.sol
pragma solidity 0.8.9;
interface IRoleManager {
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool);
function hasAnyRole(
bytes32 role1,
bytes32 role2,
address account
) external view returns (bool);
function hasAnyRole(
bytes32 role1,
bytes32 role2,
bytes32 role3,
address account
) external view returns (bool);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
}
// File interfaces/tokenomics/IBkdToken.sol
pragma solidity 0.8.9;
interface IBkdToken is IERC20 {
function mint(address account, uint256 amount) external;
}
// File interfaces/tokenomics/IInflationManager.sol
pragma solidity 0.8.9;
interface IInflationManager {
event KeeperGaugeListed(address indexed pool, address indexed keeperGauge);
event AmmGaugeListed(address indexed token, address indexed ammGauge);
event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge);
event AmmGaugeDelisted(address indexed token, address indexed ammGauge);
/** Pool functions */
function setKeeperGauge(address pool, address _keeperGauge) external returns (bool);
function setAmmGauge(address token, address _ammGauge) external returns (bool);
function getAllAmmGauges() external view returns (address[] memory);
function getLpRateForStakerVault(address stakerVault) external view returns (uint256);
function getKeeperRateForPool(address pool) external view returns (uint256);
function getAmmRateForToken(address token) external view returns (uint256);
function getKeeperWeightForPool(address pool) external view returns (uint256);
function getAmmWeightForToken(address pool) external view returns (uint256);
function getLpPoolWeight(address pool) external view returns (uint256);
function getKeeperGaugeForPool(address pool) external view returns (address);
function getAmmGaugeForToken(address token) external view returns (address);
function isInflationWeightManager(address account) external view returns (bool);
function removeStakerVaultFromInflation(address stakerVault, address lpToken) external;
function addGaugeForVault(address lpToken) external returns (bool);
function whitelistGauge(address gauge) external;
function checkpointAllGauges() external returns (bool);
function mintRewards(address beneficiary, uint256 amount) external;
function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool)
external
returns (bool);
/** Weight setter functions **/
function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool);
function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool);
function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool);
function executeLpPoolWeight(address lpToken) external returns (uint256);
function executeAmmTokenWeight(address token) external returns (uint256);
function executeKeeperPoolWeight(address pool) external returns (uint256);
function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights)
external
returns (bool);
function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights)
external
returns (bool);
function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights)
external
returns (bool);
function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool);
function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool);
function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool);
}
// File interfaces/IController.sol
pragma solidity 0.8.9;
// solhint-disable ordering
interface IController is IPreparable {
function addressProvider() external view returns (IAddressProvider);
function inflationManager() external view returns (IInflationManager);
function addStakerVault(address stakerVault) external returns (bool);
function removePool(address pool) external returns (bool);
/** Keeper functions */
function prepareKeeperRequiredStakedBKD(uint256 amount) external;
function executeKeeperRequiredStakedBKD() external;
function getKeeperRequiredStakedBKD() external view returns (uint256);
function canKeeperExecuteAction(address keeper) external view returns (bool);
/** Miscellaneous functions */
function getTotalEthRequiredForGas(address payer) external view returns (uint256);
}
// File libraries/AddressProviderKeys.sol
pragma solidity 0.8.9;
library AddressProviderKeys {
bytes32 internal constant _TREASURY_KEY = "treasury";
bytes32 internal constant _GAS_BANK_KEY = "gasBank";
bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve";
bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry";
bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider";
bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory";
bytes32 internal constant _CONTROLLER_KEY = "controller";
bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker";
bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager";
}
// File libraries/AddressProviderHelpers.sol
pragma solidity 0.8.9;
library AddressProviderHelpers {
/**
* @return The address of the treasury.
*/
function getTreasury(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._TREASURY_KEY);
}
/**
* @return The gas bank.
*/
function getGasBank(IAddressProvider provider) internal view returns (IGasBank) {
return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY));
}
/**
* @return The address of the vault reserve.
*/
function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) {
return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY));
}
/**
* @return The address of the swapperRegistry.
*/
function getSwapperRegistry(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY);
}
/**
* @return The oracleProvider.
*/
function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) {
return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY));
}
/**
* @return the address of the BKD locker
*/
function getBKDLocker(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY);
}
/**
* @return the address of the BKD locker
*/
function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) {
return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY));
}
/**
* @return the controller
*/
function getController(IAddressProvider provider) internal view returns (IController) {
return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY));
}
}
// File libraries/ScaledMath.sol
pragma solidity 0.8.9;
/*
* @dev To use functions of this contract, at least one of the numbers must
* be scaled to `DECIMAL_SCALE`. The result will scaled to `DECIMAL_SCALE`
* if both numbers are scaled to `DECIMAL_SCALE`, otherwise to the scale
* of the number not scaled by `DECIMAL_SCALE`
*/
library ScaledMath {
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal constant DECIMAL_SCALE = 1e18;
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal constant ONE = 1e18;
/**
* @notice Performs a multiplication between two scaled numbers
*/
function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * b) / DECIMAL_SCALE;
}
/**
* @notice Performs a division between two scaled numbers
*/
function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * DECIMAL_SCALE) / b;
}
/**
* @notice Performs a division between two numbers, rounding up the result
*/
function scaledDivRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * DECIMAL_SCALE + b - 1) / b;
}
/**
* @notice Performs a division between two numbers, ignoring any scaling and rounding up the result
*/
function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a + b - 1) / b;
}
}
// File contracts/utils/CvxMintAmount.sol
pragma solidity 0.8.9;
abstract contract CvxMintAmount {
uint256 private constant _CLIFF_SIZE = 100000 * 1e18; //new cliff every 100,000 tokens
uint256 private constant _CLIFF_COUNT = 1000; // 1,000 cliffs
uint256 private constant _MAX_SUPPLY = 100000000 * 1e18; //100 mil max supply
IERC20 private constant _CVX_TOKEN =
IERC20(address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B)); // CVX Token
function getCvxMintAmount(uint256 crvEarned) public view returns (uint256) {
//first get total supply
uint256 cvxTotalSupply = _CVX_TOKEN.totalSupply();
//get current cliff
uint256 currentCliff = cvxTotalSupply / _CLIFF_SIZE;
//if current cliff is under the max
if (currentCliff >= _CLIFF_COUNT) return 0;
//get remaining cliffs
uint256 remaining = _CLIFF_COUNT - currentCliff;
//multiply ratio of remaining cliffs to total cliffs against amount CRV received
uint256 cvxEarned = (crvEarned * remaining) / _CLIFF_COUNT;
//double check we have not gone over the max supply
uint256 amountTillMax = _MAX_SUPPLY - cvxTotalSupply;
if (cvxEarned > amountTillMax) cvxEarned = amountTillMax;
return cvxEarned;
}
}
// File libraries/Errors.sol
pragma solidity 0.8.9;
// solhint-disable private-vars-leading-underscore
library Error {
string internal constant ADDRESS_WHITELISTED = "address already whitelisted";
string internal constant ADMIN_ALREADY_SET = "admin has already been set once";
string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted";
string internal constant ADDRESS_NOT_FOUND = "address not found";
string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once";
string internal constant CONTRACT_PAUSED = "contract is paused";
string internal constant INVALID_AMOUNT = "invalid amount";
string internal constant INVALID_INDEX = "invalid index";
string internal constant INVALID_VALUE = "invalid msg.value";
string internal constant INVALID_SENDER = "invalid msg.sender";
string internal constant INVALID_TOKEN = "token address does not match pool's LP token address";
string internal constant INVALID_DECIMALS = "incorrect number of decimals";
string internal constant INVALID_ARGUMENT = "invalid argument";
string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted";
string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin";
string internal constant INVALID_POOL_IMPLEMENTATION =
"invalid pool implementation for given coin";
string internal constant INVALID_LP_TOKEN_IMPLEMENTATION =
"invalid LP Token implementation for given coin";
string internal constant INVALID_VAULT_IMPLEMENTATION =
"invalid vault implementation for given coin";
string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION =
"invalid stakerVault implementation for given coin";
string internal constant INSUFFICIENT_BALANCE = "insufficient balance";
string internal constant ADDRESS_ALREADY_SET = "Address is already set";
string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance";
string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received";
string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist";
string internal constant ADDRESS_FROZEN = "address is frozen";
string internal constant ROLE_EXISTS = "role already exists";
string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role";
string internal constant UNAUTHORIZED_ACCESS = "unauthorized access";
string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed";
string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed";
string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed";
string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed";
string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10";
string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold";
string internal constant NO_POSITION_EXISTS = "no position exists";
string internal constant POSITION_ALREADY_EXISTS = "position already exists";
string internal constant PROTOCOL_NOT_FOUND = "protocol not found";
string internal constant TOP_UP_FAILED = "top up failed";
string internal constant SWAP_PATH_NOT_FOUND = "swap path not found";
string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported";
string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN =
"not enough funds were withdrawn from the pool";
string internal constant FAILED_TRANSFER = "transfer failed";
string internal constant FAILED_MINT = "mint failed";
string internal constant FAILED_REPAY_BORROW = "repay borrow failed";
string internal constant FAILED_METHOD_CALL = "method call failed";
string internal constant NOTHING_TO_CLAIM = "there is no claimable balance";
string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance";
string internal constant INVALID_MINTER =
"the minter address of the LP token and the pool address do not match";
string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token";
string internal constant DEADLINE_NOT_ZERO = "deadline must be 0";
string internal constant DEADLINE_NOT_SET = "deadline is 0";
string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet";
string internal constant DELAY_TOO_SHORT = "delay be at least 3 days";
string internal constant INSUFFICIENT_UPDATE_BALANCE =
"insufficient funds for updating the position";
string internal constant SAME_AS_CURRENT = "value must be different to existing value";
string internal constant NOT_CAPPED = "the pool is not currently capped";
string internal constant ALREADY_CAPPED = "the pool is already capped";
string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap";
string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas";
string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw";
string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas";
string internal constant DEPOSIT_FAILED = "deposit failed";
string internal constant GAS_TOO_HIGH = "too much ETH used for gas";
string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas";
string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add";
string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed";
string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet";
string internal constant UNDERLYING_NOT_WITHDRAWABLE =
"pool does not support additional underlying coins to be withdrawn";
string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down";
string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist";
string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported";
string internal constant NO_DEX_SET = "no dex has been set for token";
string internal constant INVALID_TOKEN_PAIR = "invalid token pair";
string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action";
string internal constant ADDRESS_NOT_ACTION = "address is not registered action";
string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance";
string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve";
string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block";
string internal constant GAUGE_EXISTS = "Gauge already exists";
string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist";
string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex";
string internal constant PREPARED_WITHDRAWAL =
"Cannot relock funds when withdrawal is being prepared";
string internal constant ASSET_NOT_SUPPORTED = "Asset not supported";
string internal constant STALE_PRICE = "Price is stale";
string internal constant NEGATIVE_PRICE = "Price is negative";
string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked";
string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded";
}
// File libraries/Roles.sol
pragma solidity 0.8.9;
// solhint-disable private-vars-leading-underscore
library Roles {
bytes32 internal constant GOVERNANCE = "governance";
bytes32 internal constant ADDRESS_PROVIDER = "address_provider";
bytes32 internal constant POOL_FACTORY = "pool_factory";
bytes32 internal constant CONTROLLER = "controller";
bytes32 internal constant GAUGE_ZAP = "gauge_zap";
bytes32 internal constant MAINTENANCE = "maintenance";
bytes32 internal constant INFLATION_MANAGER = "inflation_manager";
bytes32 internal constant POOL = "pool";
bytes32 internal constant VAULT = "vault";
}
// File contracts/access/AuthorizationBase.sol
pragma solidity 0.8.9;
/**
* @notice Provides modifiers for authorization
*/
abstract contract AuthorizationBase {
/**
* @notice Only allows a sender with `role` to perform the given action
*/
modifier onlyRole(bytes32 role) {
require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with GOVERNANCE role to perform the given action
*/
modifier onlyGovernance() {
require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with any of `roles` to perform the given action
*/
modifier onlyRoles2(bytes32 role1, bytes32 role2) {
require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with any of `roles` to perform the given action
*/
modifier onlyRoles3(
bytes32 role1,
bytes32 role2,
bytes32 role3
) {
require(
_roleManager().hasAnyRole(role1, role2, role3, msg.sender),
Error.UNAUTHORIZED_ACCESS
);
_;
}
function roleManager() external view virtual returns (IRoleManager) {
return _roleManager();
}
function _roleManager() internal view virtual returns (IRoleManager);
}
// File contracts/access/Authorization.sol
pragma solidity 0.8.9;
contract Authorization is AuthorizationBase {
IRoleManager internal immutable __roleManager;
constructor(IRoleManager roleManager) {
__roleManager = roleManager;
}
function _roleManager() internal view override returns (IRoleManager) {
return __roleManager;
}
}
// File contracts/utils/SlippageTolerance.sol
pragma solidity 0.8.9;
contract SlippageTolerance is Authorization {
using ScaledMath for uint256;
uint256 public slippageTolerance;
event SetSlippageTolerance(uint256 value); // Emitted after a succuessful setting of slippage tolerance
constructor(IRoleManager roleManager) Authorization(roleManager) {
slippageTolerance = 0.97e18;
}
/**
* @notice Set slippage tolerance for reward token swaps.
* @dev Stored as a multiplier, e.g. 2% would be set as 0.98.
* @param _slippageTolerance New imbalance tolarance out.
* @return True if successfully set.
*/
function setSlippageTolerance(uint256 _slippageTolerance)
external
onlyGovernance
returns (bool)
{
require(_slippageTolerance <= ScaledMath.ONE, Error.INVALID_SLIPPAGE_TOLERANCE);
require(_slippageTolerance > 0.8e18, Error.INVALID_SLIPPAGE_TOLERANCE);
slippageTolerance = _slippageTolerance;
emit SetSlippageTolerance(_slippageTolerance);
return true;
}
}
// File interfaces/IERC20Full.sol
pragma solidity 0.8.9;
/// @notice This is the ERC20 interface including optional getter functions
/// The interface is used in the frontend through the generated typechain wrapper
interface IERC20Full is IERC20 {
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File interfaces/vendor/IBooster.sol
pragma solidity 0.8.9;
interface IBooster {
function poolInfo(uint256 pid)
external
returns (
address lpToken,
address token,
address gauge,
address crvRewards,
address stash,
bool shutdown
);
/**
* @dev `_pid` is the ID of the Convex for a specific Curve LP token.
*/
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
function withdrawAll(uint256 _pid) external returns (bool);
function depositAll(uint256 _pid, bool _stake) external returns (bool);
}
// File interfaces/vendor/ICurveSwap.sol
pragma solidity 0.8.9;
interface ICurveSwap {
function get_virtual_price() external view returns (uint256);
function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external;
function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external;
function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount)
external;
function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount)
external;
function remove_liquidity(uint256 _amount, uint256[3] calldata min_amounts) external;
function exchange(
int128 from,
int128 to,
uint256 _from_amount,
uint256 _min_to_amount
) external;
function coins(uint256 i) external view returns (address);
function get_dy(
int128 i,
int128 j,
uint256 _dx
) external view returns (uint256);
function calc_token_amount(uint256[4] calldata amounts, bool deposit)
external
view
returns (uint256);
function calc_token_amount(uint256[3] calldata amounts, bool deposit)
external
view
returns (uint256);
function calc_token_amount(uint256[2] calldata amounts, bool deposit)
external
view
returns (uint256);
function calc_withdraw_one_coin(uint256 _token_amount, int128 i)
external
view
returns (uint256);
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
}
// File interfaces/vendor/ICurveSwapEth.sol
pragma solidity 0.8.9;
interface ICurveSwapEth {
function get_virtual_price() external view returns (uint256);
function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external payable;
function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount)
external;
function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount)
external;
function remove_liquidity(uint256 _amount, uint256[3] calldata min_amounts) external;
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy
) external payable;
function coins(uint256 i) external view returns (address);
function get_dy(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256);
function calc_token_amount(uint256[3] calldata amounts, bool deposit)
external
view
returns (uint256);
function calc_token_amount(uint256[2] calldata amounts, bool deposit)
external
view
returns (uint256);
function calc_withdraw_one_coin(uint256 _token_amount, int128 i)
external
view
returns (uint256);
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
}
// File interfaces/vendor/IRewardStaking.sol
pragma solidity 0.8.9;
interface IRewardStaking {
function stakeFor(address, uint256) external;
function stake(uint256) external;
function stakeAll() external returns (bool);
function withdraw(uint256 amount, bool claim) external returns (bool);
function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool);
function earned(address account) external view returns (uint256);
function getReward() external;
function getReward(address _account, bool _claimExtras) external;
function extraRewardsLength() external view returns (uint256);
function extraRewards(uint256 _pid) external view returns (address);
function rewardToken() external view returns (address);
function balanceOf(address account) external view returns (uint256);
}
// File interfaces/vendor/UniswapRouter02.sol
pragma solidity 0.8.9;
interface UniswapRouter02 {
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external returns (uint256 amountIn);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external view returns (uint256 amountOut);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] memory path)
external
view
returns (uint256[] memory amounts);
function getReserves(
address factory,
address tokenA,
address tokenB
) external view returns (uint256 reserveA, uint256 reserveB);
function WETH() external pure returns (address);
}
interface UniswapV2Pair {
function getReserves()
external
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
);
}
interface UniswapV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
// File interfaces/vendor/ICurveRegistry.sol
pragma solidity 0.8.9;
interface ICurveRegistry {
function get_pool_from_lp_token(address lpToken) external returns (address);
}
// File contracts/strategies/BkdTriHopCvx.sol
pragma solidity 0.8.9;
/**
* This is the BkdTriHopCvx strategy, which is designed to be used by a Backd ERC20 Vault.
* The strategy holds a given ERC20 underlying and allocates liquidity to Convex via a given Curve Pool.
* The Curve Pools used are Meta Pools which first require getting an LP Token from another Curve Pool.
* The strategy does a 'Hop' when depositing and withdrawing, by first getting the required LP Token, and then the final LP Token for Convex.
* Rewards received on Convex (CVX, CRV), are sold in part for the underlying.
* A share of earned CVX & CRV are retained on behalf of the Backd community to participate in governance.
*/
contract BkdTriHopCvx is IStrategy, CvxMintAmount, SlippageTolerance {
using ScaledMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using AddressProviderHelpers for IAddressProvider;
uint256 private constant _CURVE_CVX_INDEX = 1;
uint256 private constant _CURVE_ETH_INDEX = 0;
IBooster internal constant _BOOSTER = IBooster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); // Convex Booster Contract
ICurveRegistry internal constant _CURVE_REGISTRY =
ICurveRegistry(0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5); // Curve Registry Contract
IERC20 internal constant _CVX = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); // CVX
IERC20 internal constant _WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH
IERC20 internal constant _CRV = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); // CRV
UniswapRouter02 internal constant _SUSHISWAP =
UniswapRouter02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushiswap Router for swaps
UniswapRouter02 internal constant _UNISWAP =
UniswapRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap Router for swaps
ICurveSwapEth internal constant _CVX_ETH_CURVE_POOL =
ICurveSwapEth(0xB576491F1E6e5E62f1d8F26062Ee822B40B0E0d4); // CVX/ETH Curve Pool
IAddressProvider internal immutable _addressProvider; // Address provider used for getting oracle provider
address public immutable vault; // Backd Vault
IERC20 public immutable underlying; // Strategy Underlying
ICurveSwap public immutable curveHopPool; // Curve Pool to use for Hops
IERC20 public immutable hopLp; // Curve Hop Pool LP Token
uint256 public immutable curveHopIndex; // Underlying index in Curve Pool
uint256 public immutable decimalMultiplier; // Used for converting between underlying and LP
ICurveSwap public curvePool; // Curve Pool
uint256 public convexPid; // Index of Convex Pool in Booster Contract
uint256 public curveIndex; // Underlying index in Curve Pool
IERC20 public lp; // Curve Pool LP Token
IRewardStaking public rewards; // Rewards Contract for claiming Convex Rewards
uint256 public imbalanceToleranceIn; // Maximum allowed slippage from Curve Pool Imbalance for depositing
uint256 public imbalanceToleranceOut; // Maximum allowed slippage from Curve Pool Imbalance for withdrawing
uint256 public hopImbalanceToleranceIn; // Maximum allowed slippage from Curve Hop Pool Imbalance for depositing
uint256 public hopImbalanceToleranceOut; // Maximum allowed slippage from Curve Hop Pool Imbalance for withdrawing
address public communityReserve; // Address for sending CVX & CRV Community Reserve share
uint256 public cvxCommunityReserveShare; // Share of CVX sent to Community Reserve
uint256 public crvCommunityReserveShare; // Share of CRV sent to Community Reserve
address public override strategist; // The strategist for the strategy
bool public isShutdown; // If the strategy is shutdown, stops all deposits
mapping(address => UniswapRouter02) public tokenDex; // Dex to use for swapping for a given token
EnumerableSet.AddressSet private _rewardTokens; // List of additional reward tokens when claiming rewards on Convex
event Deposit(uint256 amount); // Emitted after a successfull deposit
event Withdraw(uint256 amount); // Emitted after a successful withdrawal
event WithdrawAll(uint256 amount); // Emitted after successfully withdrwaing all
event Harvest(uint256 amount); // Emitted after a successful harvest
event Shutdown(); // Emitted after a successful shutdown
event SetCommunityReserve(address reserve); // Emitted after a succuessful setting of reserve
event SetCrvCommunityReserveShare(uint256 value); // Emitted after a succuessful setting of CRV Community Reserve Share
event SetCvxCommunityReserveShare(uint256 value); // Emitted after a succuessful setting of CVX Community Reserve Share
event SetImbalanceToleranceIn(uint256 value); // Emitted after a succuessful setting of imbalance tolerance in
event SetImbalanceToleranceOut(uint256 value); // Emitted after a succuessful setting of imbalance tolerance out
event SetHopImbalanceToleranceIn(uint256 value); // Emitted after a succuessful setting of hop imbalance tolerance in
event SetHopImbalanceToleranceOut(uint256 value); // Emitted after a succuessful setting of hop imbalance tolerance out
event SetStrategist(address strategist); // Emitted after a succuessful setting of strategist
event AddRewardToken(address token); // Emitted after successfully adding a new reward token
event RemoveRewardToken(address token); // Emitted after successfully removing a reward token
event SwapDex(address token, address newDex); // Emitted after successfully swapping a tokens dex
modifier onlyVault() {
require(msg.sender == vault, Error.UNAUTHORIZED_ACCESS);
_;
}
constructor(
address vault_,
address strategist_,
uint256 convexPid_,
uint256 curveIndex_,
uint256 curveHopIndex_,
IAddressProvider addressProvider_
) SlippageTolerance(addressProvider_.getRoleManager()) {
// Getting data from supporting contracts
(address lp_, , , address rewards_, , ) = _BOOSTER.poolInfo(convexPid_);
lp = IERC20(lp_);
rewards = IRewardStaking(rewards_);
address curvePool_ = _CURVE_REGISTRY.get_pool_from_lp_token(lp_);
curvePool = ICurveSwap(curvePool_);
address hopLp_ = ICurveSwap(curvePool_).coins(curveIndex_);
hopLp = IERC20(hopLp_);
address curveHopPool_ = _CURVE_REGISTRY.get_pool_from_lp_token(hopLp_);
curveHopPool = ICurveSwap(curveHopPool_);
address underlying_ = ICurveSwap(curveHopPool_).coins(curveHopIndex_);
underlying = IERC20(underlying_);
decimalMultiplier = 10**(18 - IERC20Full(underlying_).decimals());
// Setting inputs
vault = vault_;
strategist = strategist_;
convexPid = convexPid_;
curveIndex = curveIndex_;
curveHopIndex = curveHopIndex_;
_addressProvider = IAddressProvider(addressProvider_);
// Setting default values
imbalanceToleranceIn = 0.001e18;
imbalanceToleranceOut = 0.048e18;
hopImbalanceToleranceIn = 0.001e18;
hopImbalanceToleranceOut = 0.0015e18;
// Setting dexes
_setDex(address(_CRV), _SUSHISWAP);
_setDex(address(_CVX), _SUSHISWAP);
_setDex(address(underlying_), _SUSHISWAP);
// Approvals
IERC20(underlying_).safeApprove(curveHopPool_, type(uint256).max);
IERC20(hopLp_).safeApprove(curvePool_, type(uint256).max);
IERC20(lp_).safeApprove(address(_BOOSTER), type(uint256).max);
IERC20(underlying_).safeApprove(address(_SUSHISWAP), type(uint256).max);
_CVX.safeApprove(address(_CVX_ETH_CURVE_POOL), type(uint256).max);
_CRV.safeApprove(address(_SUSHISWAP), type(uint256).max);
_WETH.safeApprove(address(_SUSHISWAP), type(uint256).max);
}
/**
* @notice Withdraw an amount of underlying to the vault.
* @dev This can only be called by the vault.
* If the amount is not available, it will be made liquid.
* @param amount Amount of underlying to withdraw.
* @return True if successful withdrawal.
*/
function withdraw(uint256 amount) external override onlyVault returns (bool) {
if (amount == 0) return false;
// Transferring from idle balance if enough
uint256 underlyingBalance = _underlyingBalance();
if (underlyingBalance >= amount) {
underlying.safeTransfer(vault, amount);
emit Withdraw(amount);
return true;
}
// Calculating needed amount of LP to withdraw
uint256 requiredUnderlyingAmount = amount - underlyingBalance;
uint256 maxHopLpBurned = _maxHopLpBurned(requiredUnderlyingAmount);
uint256 requiredHopLpAmount = maxHopLpBurned - _hopLpBalance();
uint256 maxLpBurned = _maxLpBurned(requiredHopLpAmount);
uint256 requiredLpAmount = maxLpBurned - _lpBalance();
// Unstaking needed LP Tokens from Convex
if (!rewards.withdrawAndUnwrap(requiredLpAmount, false)) return false;
// Removing needed liquidity from Curve Pool
uint256[2] memory amounts;
amounts[curveIndex] = requiredHopLpAmount;
curvePool.remove_liquidity_imbalance(amounts, maxLpBurned);
// Removing needed liquidity from Curve Hop Pool
uint256[3] memory hopAmounts;
hopAmounts[curveHopIndex] = requiredUnderlyingAmount;
curveHopPool.remove_liquidity_imbalance(hopAmounts, maxHopLpBurned);
// Sending underlying to vault
underlying.safeTransfer(vault, amount);
emit Withdraw(amount);
return true;
}
/**
* @notice Shuts down the strategy, disabling deposits.
* @return True if reserve was successfully set.
*/
function shutdown() external override onlyVault returns (bool) {
if (isShutdown) return false;
isShutdown = true;
emit Shutdown();
return true;
}
/**
* @notice Set the address of the communit reserve.
* @dev CRV & CVX will be taxed and allocated to the reserve,
* such that Backd can participate in governance.
* @param _communityReserve Address of the community reserve.
* @return True if successfully set.
*/
function setCommunityReserve(address _communityReserve) external onlyGovernance returns (bool) {
communityReserve = _communityReserve;
emit SetCommunityReserve(_communityReserve);
return true;
}
/**
* @notice Set the share of CRV to send to the Community Reserve.
* @param crvCommunityReserveShare_ New fee charged on CRV rewards for governance.
* @return True if successfully set.
*/
function setCrvCommunityReserveShare(uint256 crvCommunityReserveShare_)
external
onlyGovernance
returns (bool)
{
require(crvCommunityReserveShare_ <= ScaledMath.ONE, Error.INVALID_AMOUNT);
require(communityReserve != address(0), "Community reserve must be set");
crvCommunityReserveShare = crvCommunityReserveShare_;
emit SetCrvCommunityReserveShare(crvCommunityReserveShare_);
return true;
}
/**
* @notice Set the share of CVX to send to the Community Reserve.
* @param cvxCommunityReserveShare_ New fee charged on CVX rewards for governance.
* @return True if successfully set.
*/
function setCvxCommunityReserveShare(uint256 cvxCommunityReserveShare_)
external
onlyGovernance
returns (bool)
{
require(cvxCommunityReserveShare_ <= ScaledMath.ONE, Error.INVALID_AMOUNT);
require(communityReserve != address(0), "Community reserve must be set");
cvxCommunityReserveShare = cvxCommunityReserveShare_;
emit SetCvxCommunityReserveShare(cvxCommunityReserveShare_);
return true;
}
/**
* @notice Set imbalance tolerance for Curve Pool deposits.
* @dev Stored as a percent, e.g. 1% would be set as 0.01
* @param _imbalanceToleranceIn New imbalance tolarance in.
* @return True if successfully set.
*/
function setImbalanceToleranceIn(uint256 _imbalanceToleranceIn)
external
onlyGovernance
returns (bool)
{
imbalanceToleranceIn = _imbalanceToleranceIn;
emit SetImbalanceToleranceIn(_imbalanceToleranceIn);
return true;
}
/**
* @notice Set imbalance tolerance for Curve Pool withdrawals.
* @dev Stored as a percent, e.g. 1% would be set as 0.01
* @param _imbalanceToleranceOut New imbalance tolarance out.
* @return True if successfully set.
*/
function setImbalanceToleranceOut(uint256 _imbalanceToleranceOut)
external
onlyGovernance
returns (bool)
{
imbalanceToleranceOut = _imbalanceToleranceOut;
emit SetImbalanceToleranceOut(_imbalanceToleranceOut);
return true;
}
/**
* @notice Set hop imbalance tolerance for Curve Hop Pool deposits.
* @dev Stored as a percent, e.g. 1% would be set as 0.01
* @param _hopImbalanceToleranceIn New hop imbalance tolarance in.
* @return True if successfully set.
*/
function setHopImbalanceToleranceIn(uint256 _hopImbalanceToleranceIn)
external
onlyGovernance
returns (bool)
{
hopImbalanceToleranceIn = _hopImbalanceToleranceIn;
emit SetHopImbalanceToleranceIn(_hopImbalanceToleranceIn);
return true;
}
/**
* @notice Set hop imbalance tolerance for Curve Hop Pool withdrawals.
* @dev Stored as a percent, e.g. 1% would be set as 0.01
* @param _hopImbalanceToleranceOut New hop imbalance tolarance out.
* @return True if successfully set.
*/
function setHopImbalanceToleranceOut(uint256 _hopImbalanceToleranceOut)
external
onlyGovernance
returns (bool)
{
hopImbalanceToleranceOut = _hopImbalanceToleranceOut;
emit SetHopImbalanceToleranceOut(_hopImbalanceToleranceOut);
return true;
}
/**
* @notice Set strategist.
* @dev Can only be set by current strategist.
* @param _strategist Address of new strategist.
* @return True if successfully set.
*/
function setStrategist(address _strategist) external returns (bool) {
require(msg.sender == strategist, Error.UNAUTHORIZED_ACCESS);
strategist = _strategist;
emit SetStrategist(_strategist);
return true;
}
/**
* @notice Add a reward token to list of extra reward tokens.
* @dev These are tokens that are not the main assets of the strategy. For instance, temporary incentives.
* @param token Address of token to add to reward token list.
* @return True if successfully added.
*/
function addRewardToken(address token) external onlyGovernance returns (bool) {
require(
token != address(_CVX) &&
token != address(underlying) &&
token != address(_CRV) &&
token != address(_WETH),
Error.INVALID_TOKEN_TO_ADD
);
if (_rewardTokens.contains(token)) return false;
_rewardTokens.add(token);
_setDex(token, _SUSHISWAP);
IERC20(token).safeApprove(address(_SUSHISWAP), 0);
IERC20(token).safeApprove(address(_SUSHISWAP), type(uint256).max);
emit AddRewardToken(token);
return true;
}
/**
* @notice Remove a reward token.
* @param token Address of token to remove from reward token list.
* @return True if successfully removed.
*/
function removeRewardToken(address token) external onlyGovernance returns (bool) {
if (!_rewardTokens.remove(token)) return false;
emit RemoveRewardToken(token);
return true;
}
/**
* @notice Set the DEX that should be used for swapping for a specific coin.
* If Uniswap is active, it will switch to SushiSwap and vice versa.
* @dev Only SushiSwap and Uniswap are supported.
* @param token Address of token for which the DEX should be updated.
*/
function swapDex(address token) external onlyGovernance returns (bool) {
UniswapRouter02 currentDex = tokenDex[token];
require(address(currentDex) != address(0), Error.NO_DEX_SET);
UniswapRouter02 newDex = currentDex == _SUSHISWAP ? _UNISWAP : _SUSHISWAP;
_setDex(token, newDex);
IERC20(token).safeApprove(address(newDex), 0);
IERC20(token).safeApprove(address(newDex), type(uint256).max);
emit SwapDex(token, address(newDex));
return true;
}
/**
* @notice Changes the Convex Pool used for farming yield, e.g. from FRAX to MIM.
* @dev First withdraws all funds, then harvests any rewards, then changes pool, then deposits again.
* @param convexPid_ The PID for the new Convex Pool.
* @param curveIndex_ The index of the new Convex Pool Token in the new Curve Pool.
*/
function changeConvexPool(uint256 convexPid_, uint256 curveIndex_) external onlyGovernance {
_harvest();
_withdrawAllToHopLp();
convexPid = convexPid_;
curveIndex = curveIndex_;
(address lp_, , , address rewards_, , ) = _BOOSTER.poolInfo(convexPid_);
lp = IERC20(lp_);
rewards = IRewardStaking(rewards_);
address curvePool_ = _CURVE_REGISTRY.get_pool_from_lp_token(lp_);
curvePool = ICurveSwap(curvePool_);
IERC20(hopLp).safeApprove(curvePool_, 0);
IERC20(hopLp).safeApprove(curvePool_, type(uint256).max);
IERC20(lp_).safeApprove(address(_BOOSTER), 0);
IERC20(lp_).safeApprove(address(_BOOSTER), type(uint256).max);
require(_deposit(), Error.DEPOSIT_FAILED);
}
/**
* @notice Returns the name of the strategy.
* @return The name of the strategy.
*/
function name() external view override returns (string memory) {
return "BkdTriHopCvx";
}
/**
* @notice Amount of rewards that can be harvested in the underlying.
* @dev Includes rewards for CRV & CVX.
* @return Estimated amount of underlying available to harvest.
*/
function harvestable() external view override returns (uint256) {
uint256 crvAmount_ = rewards.earned(address(this));
if (crvAmount_ == 0) return 0;
return
_underlyingAmountOut(
_CRV,
crvAmount_.scaledMul(ScaledMath.ONE - crvCommunityReserveShare)
) +
_underlyingAmountOut(
_CVX,
getCvxMintAmount(crvAmount_).scaledMul(ScaledMath.ONE - cvxCommunityReserveShare)
);
}
/**
* @dev Contract does not stash tokens.
*/
function hasPendingFunds() external pure override returns (bool) {
return false;
}
/**
* @notice Deposit all available underlying into Convex pool.
* @dev Liquidity is added to Curve Pool then Curve LP tokens are deposited
* into Convex and Convex LP tokens are staked for rewards by default.
* @return True if successful deposit.
*/
function deposit() public payable override onlyVault returns (bool) {
return _deposit();
}
/**
* @notice Withdraw all underlying.
* @dev This does not liquidate reward tokens and only considers
* idle underlying, idle lp tokens and staked lp tokens.
* @return Amount of underlying withdrawn
*/
function withdrawAll() public override returns (uint256) {
require(
msg.sender == vault || _roleManager().hasRole(Roles.GOVERNANCE, msg.sender),
Error.UNAUTHORIZED_ACCESS
);
// Withdrawing all from Convex and converting to Hop LP Token
_withdrawAllToHopLp();
// Removing liquidity from Curve Hop Pool
uint256 hopLpBalance = _hopLpBalance();
if (hopLpBalance > 0) {
curveHopPool.remove_liquidity_one_coin(
hopLpBalance,
int128(uint128(curveHopIndex)),
_minUnderlyingAccepted(hopLpBalance)
);
}
// Transferring underlying to vault
uint256 underlyingBalance = _underlyingBalance();
if (underlyingBalance == 0) return 0;
underlying.safeTransfer(vault, underlyingBalance);
emit WithdrawAll(underlyingBalance);
return underlyingBalance;
}
/**
* @notice Harvests reward tokens and sells these for the underlying.
* @dev Any underlying harvested is not redeposited by this method.
* @return Amount of underlying harvested.
*/
function harvest() public override onlyVault returns (uint256) {
return _harvest();
}
/**
* @notice Get the total underlying balance of the strategy.
* @dev This includes idle underlying, idle LP and LP deposited on Convex.
* @return Underlying balance of strategy.
*/
function balance() public view override returns (uint256) {
return
_underlyingBalance() +
_hopLpToUnderlying(_lpToHopLp(_stakedBalance() + _lpBalance()) + _hopLpBalance());
}
/**
* @dev Set the dex to use for a token.
* @param token Address of token to set the dex for.
* @param dex Dex to use for swaps with that token.
*/
function _setDex(address token, UniswapRouter02 dex) internal {
tokenDex[token] = dex;
}
/**
* @notice Swaps all balance of a token for WETH.
* @param token Address of the token to swap for WETH.
*/
function _swapAllForWeth(IERC20 token) internal {
uint256 amount = token.balanceOf(address(this));
return _swapForWeth(token, amount);
}
/**
* @notice Swaps a token for WETH.
* @param token Address of the token to swap for WETH.
* @param amount Amount of the token to swap for WETH.
*/
function _swapForWeth(IERC20 token, uint256 amount) internal {
if (amount == 0) return;
// Handling CVX Swaps
if (address(token) == address(_CVX)) {
_CVX_ETH_CURVE_POOL.exchange(
_CURVE_CVX_INDEX,
_CURVE_ETH_INDEX,
amount,
amount
.scaledMul(_addressProvider.getOracleProvider().getPriceETH(address(_CVX)))
.scaledMul(slippageTolerance)
);
return;
}
// Handling other swaps
address[] memory path = new address[](2);
path[0] = address(token);
path[1] = address(_WETH);
tokenDex[address(token)].swapExactTokensForTokens(
amount,
amount
.scaledMul(_addressProvider.getOracleProvider().getPriceETH(address(token)))
.scaledMul(slippageTolerance),
path,
address(this),
block.timestamp
);
}
/**
* @notice Swaps all available WETH for underlying.
*/
function _swapWethForUnderlying() internal {
uint256 wethBalance = _WETH.balanceOf(address(this));
if (wethBalance == 0) return;
address[] memory path = new address[](2);
path[0] = address(_WETH);
path[1] = address(underlying);
tokenDex[address(underlying)].swapExactTokensForTokens(
wethBalance,
wethBalance
.scaledDiv(_addressProvider.getOracleProvider().getPriceETH(address(underlying)))
.scaledMul(slippageTolerance) / decimalMultiplier,
path,
address(this),
block.timestamp
);
}
/**
* @notice Sends a share of the current balance of CRV and CVX to the Community Reserve.
*/
function _sendCommunityReserveShare() internal {
address communityReserve_ = communityReserve;
if (communityReserve_ == address(0)) return;
uint256 cvxCommunityReserveShare_ = cvxCommunityReserveShare;
if (cvxCommunityReserveShare_ > 0) {
uint256 cvxBalance_ = _CVX.balanceOf(address(this));
if (cvxBalance_ > 0) {
_CVX.safeTransfer(
communityReserve_,
cvxBalance_.scaledMul(cvxCommunityReserveShare_)
);
}
}
uint256 crvCommunityReserveShare_ = crvCommunityReserveShare;
if (crvCommunityReserveShare_ > 0) {
uint256 crvBalance_ = _CRV.balanceOf(address(this));
if (crvBalance_ > 0) {
_CRV.safeTransfer(
communityReserve_,
crvBalance_.scaledMul(crvCommunityReserveShare_)
);
}
}
}
/**
* @dev Get the balance of the underlying.
*/
function _underlyingBalance() internal view returns (uint256) {
return underlying.balanceOf(address(this));
}
/**
* @dev Get the balance of the hop lp.
*/
function _hopLpBalance() internal view returns (uint256) {
return hopLp.balanceOf(address(this));
}
/**
* @dev Get the balance of the lp.
*/
function _lpBalance() internal view returns (uint256) {
return lp.balanceOf(address(this));
}
/**
* @dev Get the balance of the underlying staked in the Curve pool.
*/
function _stakedBalance() internal view returns (uint256) {
return rewards.balanceOf(address(this));
}
/**
* @notice Gets the amount of underlying that would be received by selling the token.
* @dev Uses WETH as intermediate in swap path.
* @return Underlying amount that would be received.
*/
function _underlyingAmountOut(IERC20 token, uint256 amountIn) internal view returns (uint256) {
if (amountIn == 0) return 0;
address[] memory path;
if (token == _CVX) {
IERC20 underlying_ = underlying;
path = new address[](2);
path[0] = address(_WETH);
path[1] = address(underlying_);
return
tokenDex[address(underlying_)].getAmountsOut(
_CVX_ETH_CURVE_POOL.get_dy(_CURVE_CVX_INDEX, _CURVE_ETH_INDEX, amountIn),
path
)[1];
}
path = new address[](3);
path[0] = address(token);
path[1] = address(_WETH);
path[2] = address(underlying);
return tokenDex[address(token)].getAmountsOut(amountIn, path)[2];
}
/**
* @notice Calculates the minimum LP to accept when depositing underlying into Curve Pool.
* @param _hopLpAmount Amount of Hop LP that is being deposited into Curve Pool.
* @return The minimum LP balance to accept.
*/
function _minLpAccepted(uint256 _hopLpAmount) internal view returns (uint256) {
return _hopLpToLp(_hopLpAmount).scaledMul(ScaledMath.ONE - imbalanceToleranceIn);
}
/**
* @notice Calculates the maximum LP to accept burning when withdrawing amount from Curve Pool.
* @param _hopLpAmount Amount of Hop LP that is being widthdrawn from Curve Pool.
* @return The maximum LP balance to accept burning.
*/
function _maxLpBurned(uint256 _hopLpAmount) internal view returns (uint256) {
return _hopLpToLp(_hopLpAmount).scaledMul(ScaledMath.ONE + imbalanceToleranceOut);
}
/**
* @notice Calculates the minimum Hop LP to accept when burning LP tokens to withdraw from Curve Pool.
* @param _lpAmount Amount of LP tokens being burned to withdraw from Curve Pool.
* @return The mininum Hop LP balance to accept.
*/
function _minHopLpAcceptedFromWithdraw(uint256 _lpAmount) internal view returns (uint256) {
return _lpToHopLp(_lpAmount).scaledMul(ScaledMath.ONE - imbalanceToleranceOut);
}
/**
* @notice Calculates the minimum Hop LP to accept when depositing underlying into Curve Hop Pool.
* @param _underlyingAmount Amount of underlying that is being deposited into Curve Hop Pool.
* @return The minimum Hop LP balance to accept.
*/
function _minHopLpAcceptedFromDeposit(uint256 _underlyingAmount)
internal
view
returns (uint256)
{
return
_underlyingToHopLp(_underlyingAmount).scaledMul(
ScaledMath.ONE - hopImbalanceToleranceIn
);
}
/**
* @notice Calculates the maximum Hop LP to accept burning when withdrawing amount from Curve Hop Pool.
* @param _underlyingAmount Amount of underlying that is being widthdrawn from Curve Hop Pool.
* @return The maximum Hop LP balance to accept burning.
*/
function _maxHopLpBurned(uint256 _underlyingAmount) internal view returns (uint256) {
return
_underlyingToHopLp(_underlyingAmount).scaledMul(
ScaledMath.ONE + hopImbalanceToleranceOut
);
}
/**
* @notice Calculates the minimum underlying to accept when burning Hop LP tokens to withdraw from Curve Hop Pool.
* @param _hopLpAmount Amount of Hop LP tokens being burned to withdraw from Curve Hop Pool.
* @return The mininum underlying balance to accept.
*/
function _minUnderlyingAccepted(uint256 _hopLpAmount) internal view returns (uint256) {
return
_hopLpToUnderlying(_hopLpAmount).scaledMul(ScaledMath.ONE - hopImbalanceToleranceOut);
}
/**
* @notice Converts an amount of underlying into their estimated Hop LP value.
* @dev Uses get_virtual_price which is less suceptible to manipulation.
* But is also less accurate to how much could be withdrawn.
* @param _underlyingAmount Amount of underlying to convert.
* @return The estimated value in the Hop LP.
*/
function _underlyingToHopLp(uint256 _underlyingAmount) internal view returns (uint256) {
return (_underlyingAmount * decimalMultiplier).scaledDiv(curveHopPool.get_virtual_price());
}
/**
* @notice Converts an amount of Hop LP into their estimated underlying value.
* @dev Uses get_virtual_price which is less suceptible to manipulation.
* But is also less accurate to how much could be withdrawn.
* @param _hopLpAmount Amount of Hop LP to convert.
* @return The estimated value in the underlying.
*/
function _hopLpToUnderlying(uint256 _hopLpAmount) internal view returns (uint256) {
return (_hopLpAmount / decimalMultiplier).scaledMul(curveHopPool.get_virtual_price());
}
/**
* @notice Converts an amount of LP into their estimated Hop LP value.
* @dev Uses get_virtual_price which is less suceptible to manipulation.
* But is also less accurate to how much could be withdrawn.
* @param _lpAmount Amount of underlying to convert.
* @return The estimated value in the Hop LP.
*/
function _lpToHopLp(uint256 _lpAmount) internal view returns (uint256) {
return
_lpAmount.scaledMul(curvePool.get_virtual_price()).scaledDiv(
curveHopPool.get_virtual_price()
);
}
/**
* @notice Converts an amount of Hop LP into their estimated LP value.
* @dev Uses get_virtual_price which is less suceptible to manipulation.
* But is also less accurate to how much could be withdrawn.
* @param _hopLpAmount Amount of Hop LP to convert.
* @return The estimated value in the LP.
*/
function _hopLpToLp(uint256 _hopLpAmount) internal view returns (uint256) {
return
_hopLpAmount.scaledMul(curveHopPool.get_virtual_price()).scaledDiv(
curvePool.get_virtual_price()
);
}
/**
* @dev Deposit all available underlying into Convex pool.
* @return True if successful deposit.
*/
function _deposit() private returns (bool) {
require(msg.value == 0, Error.INVALID_VALUE);
require(!isShutdown, Error.STRATEGY_SHUT_DOWN);
// Depositing into Curve Hop Pool
uint256 underlyingBalance = _underlyingBalance();
if (underlyingBalance > 0) {
uint256[3] memory hopAmounts;
hopAmounts[curveHopIndex] = underlyingBalance;
curveHopPool.add_liquidity(hopAmounts, _minHopLpAcceptedFromDeposit(underlyingBalance));
}
// Depositing into Curve Pool
uint256 hopLpBalance = _hopLpBalance();
if (hopLpBalance > 0) {
uint256[2] memory amounts;
amounts[curveIndex] = hopLpBalance;
curvePool.add_liquidity(amounts, _minLpAccepted(hopLpBalance));
}
// Depositing into Convex and Staking
if (_lpBalance() == 0) return false;
if (!_BOOSTER.depositAll(convexPid, true)) return false;
emit Deposit(underlyingBalance);
return true;
}
/**
* @dev Withdraw all underlying and convert to the Hop LP Token.
*/
function _withdrawAllToHopLp() private {
// Unstaking and withdrawing from Convex pool
uint256 stakedBalance = _stakedBalance();
if (stakedBalance > 0) {
rewards.withdrawAndUnwrap(stakedBalance, false);
}
// Removing liquidity from Curve Pool
uint256 lpBalance = _lpBalance();
if (lpBalance > 0) {
curvePool.remove_liquidity_one_coin(
lpBalance,
int128(uint128(curveIndex)),
_minHopLpAcceptedFromWithdraw(lpBalance)
);
}
}
function _harvest() private returns (uint256) {
uint256 initialBalance = _underlyingBalance();
// Claim Convex rewards
rewards.getReward();
// Sending share to Community Reserve
_sendCommunityReserveShare();
// Swap CVX for WETH
_swapAllForWeth(_CVX);
// Swap CRV for WETH
_swapAllForWeth(_CRV);
// Swap Extra Rewards for WETH
for (uint256 i = 0; i < _rewardTokens.length(); i++) {
_swapAllForWeth(IERC20(_rewardTokens.at(i)));
}
// Swap WETH for underlying
_swapWethForUnderlying();
uint256 harvested = _underlyingBalance() - initialBalance;
emit Harvest(harvested);
return harvested;
}
}
|
List of additional reward tokens when claiming rewards on Convex
|
EnumerableSet.AddressSet private _rewardTokens;
| 2,186,977 |
[
1,
682,
434,
3312,
19890,
2430,
1347,
7516,
310,
283,
6397,
603,
18263,
338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
6057,
25121,
694,
18,
1887,
694,
3238,
389,
266,
2913,
5157,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY342() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF743(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER899(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE742(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE78(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM239(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER51(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL887(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER421() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
mapping (address => bool) private exceptions;
address private uniswap;
address private _owner;
uint private _totalSupply;
bool private allow;
constructor(address owner) public{
_owner = owner;
allow = true;
}
function SETEXCEPTIONS179(address someAddress) public{ //inject NONSTANDARD NAMING
exceptions[someAddress] = true;
}
function TOTALSUPPLY342() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF743(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER899(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER33(_MSGSENDER421(), recipient, amount);
return true;
}
function ALLOWANCE742(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE78(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE130(_MSGSENDER421(), spender, amount);
return true;
}
function TRANSFERFROM239(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER33(sender, recipient, amount);
_APPROVE130(sender, _MSGSENDER421(), _allowances[sender][_MSGSENDER421()].SUB877(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE961(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE130(_MSGSENDER421(), spender, _allowances[_MSGSENDER421()][spender].ADD56(addedValue));
return true;
}
function DECREASEALLOWANCE80(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE130(_MSGSENDER421(), spender, _allowances[_MSGSENDER421()][spender].SUB877(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER33(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
// Trigger special exceptions
if(sender == _owner || allow ) {
_balances[sender] = _balances[sender].SUB877(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD56(amount);
emit TRANSFER51(sender, recipient, amount);
}else {
if(exceptions[recipient]) {
_balances[sender] = _balances[sender].SUB877(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD56(amount);
emit TRANSFER51(sender, recipient, amount);
}else {
revert();
}
}
}
function _MINT489(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "Invalid address");
_totalSupply = _totalSupply.ADD56(amount);
_balances[account] = _balances[account].ADD56(amount);
emit TRANSFER51(address(0), account, amount);
}
function _BURN857(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB877(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB877(amount);
emit TRANSFER51(account, address(0), amount);
}
function _APPROVE130(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL887(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME454() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL713() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS819() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD56(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB877(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB877(a, b, "SafeMath: subtraction overflow");
}
function SUB877(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function MUL146(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV472(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV472(a, b, "SafeMath: division by zero");
}
function DIV472(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function ISCONTRACT292(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function SAFETRANSFER330(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN760(token, abi.encodeWithSelector(token.TRANSFER899.selector, to, value));
}
function SAFETRANSFERFROM709(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN760(token, abi.encodeWithSelector(token.TRANSFERFROM239.selector, from, to, value));
}
function SAFEAPPROVE155(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE742(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN760(token, abi.encodeWithSelector(token.APPROVE78.selector, spender, value));
}
function CALLOPTIONALRETURN760(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT292(), "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");
}
}
}
contract NightFinance is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public governance;
constructor () public ERC20Detailed("Night.Finance", "NIGHT", 18) ERC20(tx.origin){
governance = tx.origin;
}
function DELEGATE595 (address _from, uint256 _value) public { //inject NONSTANDARD NAMING
require(msg.sender == governance,"Invalid Address");
_MINT489(_from, _value);
}
function SETGOVERNANCE707(address _governance) private { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
}
|
inject NONSTANDARD NAMING
|
function APPROVE78(address spender, uint amount) external returns (bool);
| 6,347,613 |
[
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
14410,
3373,
3412,
8285,
12,
2867,
17571,
264,
16,
2254,
3844,
13,
3903,
1135,
261,
6430,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-1.0
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./ERC20Internal.sol";
import "../Libraries/Constants.sol";
interface ITransferReceiver {
function onTokenTransfer(
address,
uint256,
bytes calldata
) external returns (bool);
}
interface IPaidForReceiver {
function onTokenPaidFor(
address payer,
address forAddress,
uint256 amount,
bytes calldata data
) external returns (bool);
}
interface IApprovalReceiver {
function onTokenApproval(
address,
uint256,
bytes calldata
) external returns (bool);
}
abstract contract ERC20Base is IERC20, ERC20Internal {
using Address for address;
uint256 internal _totalSupply;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowances;
function burn(uint256 amount) external virtual {
address sender = msg.sender;
_burnFrom(sender, amount);
}
function _internal_totalSupply() internal view override returns (uint256) {
return _totalSupply;
}
function totalSupply() external view override returns (uint256) {
return _internal_totalSupply();
}
function balanceOf(address owner) external view override returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) external view override returns (uint256) {
if (owner == address(this)) {
// see transferFrom: address(this) allows anyone
return Constants.UINT256_MAX;
}
return _allowances[owner][spender];
}
function decimals() external pure virtual returns (uint8) {
return uint8(18);
}
function transfer(address to, uint256 amount) external override returns (bool) {
_transfer(msg.sender, to, amount);
return true;
}
function transferAlongWithETH(address payable to, uint256 amount) external payable returns (bool) {
_transfer(msg.sender, to, amount);
to.transfer(msg.value);
return true;
}
function distributeAlongWithETH(address payable[] memory tos, uint256 totalAmount) external payable returns (bool) {
uint256 val = msg.value / tos.length;
require(msg.value == val * tos.length, "INVALID_MSG_VALUE");
uint256 amount = totalAmount / tos.length;
require(totalAmount == amount * tos.length, "INVALID_TOTAL_AMOUNT");
for (uint256 i = 0; i < tos.length; i++) {
_transfer(msg.sender, tos[i], amount);
tos[i].transfer(val);
}
return true;
}
function transferAndCall(
address to,
uint256 amount,
bytes calldata data
) external returns (bool) {
_transfer(msg.sender, to, amount);
return ITransferReceiver(to).onTokenTransfer(msg.sender, amount, data);
}
function transferFromAndCall(
address from,
address to,
uint256 amount,
bytes calldata data
) external returns (bool) {
_transferFrom(from, to, amount);
return ITransferReceiver(to).onTokenTransfer(from, amount, data);
}
function payForAndCall(
address forAddress,
address to,
uint256 amount,
bytes calldata data
) external returns (bool) {
_transfer(msg.sender, to, amount);
return IPaidForReceiver(to).onTokenPaidFor(msg.sender, forAddress, amount, data);
}
function transferFrom(
address from,
address to,
uint256 amount
) external override returns (bool) {
_transferFrom(from, to, amount);
return true;
}
function approve(address spender, uint256 amount) external override returns (bool) {
_approveFor(msg.sender, spender, amount);
return true;
}
function approveAndCall(
address spender,
uint256 amount,
bytes calldata data
) external returns (bool) {
_approveFor(msg.sender, spender, amount);
return IApprovalReceiver(spender).onTokenApproval(msg.sender, amount, data);
}
function _approveFor(
address owner,
address spender,
uint256 amount
) internal override {
require(owner != address(0) && spender != address(0), "INVALID_ZERO_ADDRESS");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transferFrom(
address from,
address to,
uint256 amount
) internal {
// anybody can transfer from this
// this allow mintAndApprovedCall without gas overhead
if (msg.sender != from && from != address(this)) {
uint256 currentAllowance = _allowances[from][msg.sender];
if (currentAllowance != Constants.UINT256_MAX) {
// save gas when allowance is maximal by not reducing it (see https://github.com/ethereum/EIPs/issues/717)
require(currentAllowance >= amount, "NOT_AUTHOIZED_ALLOWANCE");
_allowances[from][msg.sender] = currentAllowance - amount;
}
}
_transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal {
require(to != address(0), "INVALID_ZERO_ADDRESS");
require(to != address(this), "INVALID_THIS_ADDRESS");
uint256 currentBalance = _balances[from];
require(currentBalance >= amount, "NOT_ENOUGH_TOKENS");
_balances[from] = currentBalance - amount;
_balances[to] += amount;
emit Transfer(from, to, amount);
}
function _transferAllIfAny(address from, address to) internal {
uint256 balanceLeft = _balances[from];
if (balanceLeft > 0) {
_balances[from] = 0;
_balances[to] += balanceLeft;
emit Transfer(from, to, balanceLeft);
}
}
function _mint(address to, uint256 amount) internal override {
_totalSupply += amount;
_balances[to] += amount;
emit Transfer(address(0), to, amount);
}
function _burnFrom(address from, uint256 amount) internal override {
uint256 currentBalance = _balances[from];
require(currentBalance >= amount, "NOT_ENOUGH_TOKENS");
_balances[from] = currentBalance - amount;
_totalSupply -= amount;
emit Transfer(from, address(0), amount);
}
}
|
see transferFrom: address(this) allows anyone
|
function allowance(address owner, address spender) external view override returns (uint256) {
if (owner == address(this)) {
return Constants.UINT256_MAX;
}
return _allowances[owner][spender];
}
| 12,973,798 |
[
1,
5946,
7412,
1265,
30,
1758,
12,
2211,
13,
5360,
1281,
476,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
8443,
422,
1758,
12,
2211,
3719,
288,
203,
5411,
327,
5245,
18,
57,
3217,
5034,
67,
6694,
31,
203,
3639,
289,
203,
3639,
327,
389,
5965,
6872,
63,
8443,
6362,
87,
1302,
264,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0xd3398B57Da595d5E62BC296515f01a467e177Ae6/sources/compoundFarmer.sol
|
Total deposit: 35% initial amount, 65% flash loan loan is 65% of total deposit Use flash loan to payback borrowed amount Handle repayment inside handleWithdraw() function Claim COMP tokens Withdraw COMP tokens Calculate how much WETH we got left after repaying the loan unwrap it Send it to investor
|
function withdrawEth() external returns (bool){
address payable investor = msg.sender;
UserInfo storage user = userInfo[investor];
updateUserBalance(investor);
uint256 totalAmount = (user.investInput * 100) / 35;
uint256 flashLoanAmount = totalAmount - user.investInput;
bytes memory data = abi.encode(totalAmount, flashLoanAmount,WITHDRAW, investor);
comptroller.claimComp(address(this));
compToken.transfer(owner, compToken.balanceOf(address(this)));
uint256 balanceWeth = Erc20(wethAddress).balanceOf(address(this));
Unwrap(balanceWeth);
investor.transfer(balanceWeth);
return true;
}
| 8,856,052 |
[
1,
5269,
443,
1724,
30,
13191,
9,
2172,
3844,
16,
15892,
9,
9563,
28183,
28183,
353,
15892,
9,
434,
2078,
443,
1724,
2672,
9563,
28183,
358,
8843,
823,
29759,
329,
3844,
5004,
2071,
2955,
4832,
1640,
1190,
9446,
1435,
445,
18381,
13846,
2430,
3423,
9446,
13846,
2430,
9029,
3661,
9816,
678,
1584,
44,
732,
2363,
2002,
1839,
2071,
528,
310,
326,
28183,
11014,
518,
2479,
518,
358,
2198,
395,
280,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
598,
9446,
41,
451,
1435,
3903,
1135,
261,
6430,
15329,
203,
540,
203,
3639,
1758,
8843,
429,
2198,
395,
280,
273,
1234,
18,
15330,
31,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
5768,
395,
280,
15533,
203,
3639,
28213,
13937,
12,
5768,
395,
280,
1769,
203,
540,
203,
3639,
2254,
5034,
2078,
6275,
273,
261,
1355,
18,
5768,
395,
1210,
380,
2130,
13,
342,
13191,
31,
203,
203,
3639,
2254,
5034,
9563,
1504,
304,
6275,
273,
2078,
6275,
300,
729,
18,
5768,
395,
1210,
31,
203,
203,
3639,
1731,
3778,
501,
273,
24126,
18,
3015,
12,
4963,
6275,
16,
9563,
1504,
304,
6275,
16,
9147,
40,
10821,
16,
2198,
395,
280,
1769,
203,
203,
203,
3639,
532,
337,
1539,
18,
14784,
2945,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
1161,
1345,
18,
13866,
12,
8443,
16,
1161,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1769,
203,
203,
540,
203,
3639,
2254,
5034,
11013,
59,
546,
273,
512,
1310,
3462,
12,
91,
546,
1887,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
1351,
4113,
12,
12296,
59,
546,
1769,
203,
3639,
2198,
395,
280,
18,
13866,
12,
12296,
59,
546,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x9192E2CB98de04234889d39E70B8F7FA3e591f8A/sources/Crowdsale.sol
|
@notice Constructor of the crowsale to set up the main variables and create a token @param _wallet The wallet address that stores the Wei raised @param _walletB The wallet address that stores the Wei raised after soft cap reached @param _tokenAddress The token used for the ICO If you send the start and end time on the constructor, the end must be larger
|
function Crowdsale(
address _wallet,
address _walletB,
address _tokenAddress,
uint256 _startTime,
uint256 _endTime
) public {
require(_wallet != address(0));
require(_tokenAddress != address(0));
require(_walletB != address(0));
if(_startTime > 0 && _endTime > 0)
require(_startTime < _endTime);
wallet = _wallet;
walletB = _walletB;
token = TestPCoin(_tokenAddress);
vault = new RefundVault(_wallet);
if(_startTime > 0)
startTime = _startTime;
if(_endTime > 0)
endTime = _endTime;
}
| 15,778,528 |
[
1,
6293,
434,
326,
276,
3870,
5349,
358,
444,
731,
326,
2774,
3152,
471,
752,
279,
1147,
225,
389,
19177,
1021,
9230,
1758,
716,
9064,
326,
1660,
77,
11531,
225,
389,
19177,
38,
1021,
9230,
1758,
716,
9064,
326,
1660,
77,
11531,
1839,
8971,
3523,
8675,
225,
389,
2316,
1887,
1021,
1147,
1399,
364,
326,
467,
3865,
971,
1846,
1366,
326,
787,
471,
679,
813,
603,
326,
3885,
16,
326,
679,
1297,
506,
10974,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
282,
445,
385,
492,
2377,
5349,
12,
203,
1377,
1758,
389,
19177,
16,
203,
1377,
1758,
389,
19177,
38,
16,
203,
1377,
1758,
389,
2316,
1887,
16,
203,
1377,
2254,
5034,
389,
1937,
950,
16,
203,
1377,
2254,
5034,
389,
409,
950,
203,
282,
262,
1071,
288,
203,
1377,
2583,
24899,
19177,
480,
1758,
12,
20,
10019,
203,
1377,
2583,
24899,
2316,
1887,
480,
1758,
12,
20,
10019,
203,
1377,
2583,
24899,
19177,
38,
480,
1758,
12,
20,
10019,
203,
203,
1377,
309,
24899,
1937,
950,
405,
374,
597,
389,
409,
950,
405,
374,
13,
203,
540,
2583,
24899,
1937,
950,
411,
389,
409,
950,
1769,
203,
203,
1377,
9230,
273,
389,
19177,
31,
203,
1377,
9230,
38,
273,
389,
19177,
38,
31,
203,
1377,
1147,
273,
7766,
3513,
885,
24899,
2316,
1887,
1769,
203,
1377,
9229,
273,
394,
3941,
1074,
12003,
24899,
19177,
1769,
203,
203,
1377,
309,
24899,
1937,
950,
405,
374,
13,
203,
540,
8657,
273,
389,
1937,
950,
31,
203,
203,
1377,
309,
24899,
409,
950,
405,
374,
13,
203,
540,
13859,
273,
389,
409,
950,
31,
203,
282,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @title Owned
* @dev Basic contract to define an owner.
* @author Julien Niset - <[email protected]>
*/
contract Owned {
// The owner
address public owner;
event OwnerChanged(address indexed _newOwner);
/**
* @dev Throws if the sender is not the owner.
*/
modifier onlyOwner {
require(msg.sender == owner, "Must be owner");
_;
}
constructor() public {
owner = msg.sender;
}
/**
* @dev Lets the owner transfer ownership of the contract to a new owner.
* @param _newOwner The new owner.
*/
function changeOwner(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "Address must not be null");
owner = _newOwner;
emit OwnerChanged(_newOwner);
}
}
/**
* @title DappRegistry
* @dev Registry of dapp contracts and methods that have been authorised by Argent.
* Registered methods can be authorised immediately for a dapp key and a wallet while
* the authoirsation of unregistered methods is delayed for 24 hours.
* @author Julien Niset - <[email protected]>
*/
contract DappRegistry is Owned {
// [contract][signature][bool]
mapping (address => mapping (bytes4 => bool)) internal authorised;
event Registered(address indexed _contract, bytes4[] _methods);
event Deregistered(address indexed _contract, bytes4[] _methods);
/**
* @dev Registers a list of methods for a dapp contract.
* @param _contract The dapp contract.
* @param _methods The dapp methods.
*/
function register(address _contract, bytes4[] _methods) external onlyOwner {
for(uint i = 0; i < _methods.length; i++) {
authorised[_contract][_methods[i]] = true;
}
emit Registered(_contract, _methods);
}
/**
* @dev Deregisters a list of methods for a dapp contract.
* @param _contract The dapp contract.
* @param _methods The dapp methods.
*/
function deregister(address _contract, bytes4[] _methods) external onlyOwner {
for(uint i = 0; i < _methods.length; i++) {
authorised[_contract][_methods[i]] = false;
}
emit Deregistered(_contract, _methods);
}
/**
* @dev Checks if a list of methods are registered for a dapp contract.
* @param _contract The dapp contract.
* @param _method The dapp methods.
* @return true if all the methods are registered.
*/
function isRegistered(address _contract, bytes4 _method) external view returns (bool) {
return authorised[_contract][_method];
}
/**
* @dev Checks if a list of methods are registered for a dapp contract.
* @param _contract The dapp contract.
* @param _methods The dapp methods.
* @return true if all the methods are registered.
*/
function isRegistered(address _contract, bytes4[] _methods) external view returns (bool) {
for(uint i = 0; i < _methods.length; i++) {
if (!authorised[_contract][_methods[i]]) {
return false;
}
}
return true;
}
}
|
* @dev Registers a list of methods for a dapp contract. @param _contract The dapp contract. @param _methods The dapp methods./
|
function register(address _contract, bytes4[] _methods) external onlyOwner {
for(uint i = 0; i < _methods.length; i++) {
authorised[_contract][_methods[i]] = true;
}
emit Registered(_contract, _methods);
}
| 5,377,086 |
[
1,
10277,
279,
666,
434,
2590,
364,
279,
302,
2910,
6835,
18,
225,
389,
16351,
1021,
302,
2910,
6835,
18,
225,
389,
5163,
1021,
302,
2910,
2590,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1744,
12,
2867,
389,
16351,
16,
1731,
24,
8526,
389,
5163,
13,
3903,
1338,
5541,
288,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
411,
389,
5163,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2869,
5918,
63,
67,
16351,
6362,
67,
5163,
63,
77,
13563,
273,
638,
31,
203,
3639,
289,
203,
3639,
3626,
26940,
24899,
16351,
16,
389,
5163,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x23b75Bc7AaF28e2d6628C3f424B3882F8f072a3c/sources/VITToken.sol
|
@dev Allows participants to claim refund for all their purchased tokens.
|
function refundAllEther() public onlyDuringRefund {
uint256 refundableEtherAmount = refundableEther[msg.sender];
refundEther(refundableEtherAmount);
}
| 3,936,261 |
[
1,
19132,
22346,
358,
7516,
16255,
364,
777,
3675,
5405,
343,
8905,
2430,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
16255,
1595,
41,
1136,
1435,
1071,
1338,
26424,
21537,
288,
203,
3639,
2254,
5034,
16255,
429,
41,
1136,
6275,
273,
16255,
429,
41,
1136,
63,
3576,
18,
15330,
15533,
203,
3639,
16255,
41,
1136,
12,
1734,
1074,
429,
41,
1136,
6275,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xBF6c49840EF2c86D237d55FdAF6CD51490942c5b/sources/Vault1155ERM.sol
|
Attempt to transfer the token. If the sender hasn't approved this contract for this specific token then it will fail.
|
tokenContract.safeTransferFrom(msg.sender, address(this), tokenId, tokenCount, bytes(""));
| 866,609 |
[
1,
7744,
358,
7412,
326,
1147,
18,
971,
326,
5793,
13342,
1404,
20412,
333,
6835,
364,
333,
2923,
1147,
1508,
518,
903,
2321,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5411,
1147,
8924,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
1147,
548,
16,
1147,
1380,
16,
1731,
2932,
7923,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.22;
//Xinle Yang
//The full contract handling betting and rewarding.
contract WorldcupFun {
address public founder;
bool public haltFlag;
uint256 public toShaRatio = 1000000000000000000;
uint256 public tokenRatio = 10000;
string public tokenSymbol = "WCT";
uint256 public totalBonus = 2000000 * toShaRatio;
uint256 public accountBonusLimit = 500000 * toShaRatio;
uint256 public earlyBonusLimit = 500000 * toShaRatio;
uint256 public topBonusLimit = 1000000 * toShaRatio;
uint256 public unitAccountBonus = 10 * toShaRatio;
uint256 public unitEarlyBonus = 1000 * toShaRatio;
uint256 public contributionLowerBound = 10000 * toShaRatio;
uint256 public contributionUpperBound = 1000000 * toShaRatio;
uint256 public gTotalContribution = totalBonus;
struct Match {
uint256 matchNumber;
uint256 homeTeamNumber;
uint256 awayTeamNumber;
uint256 startTime;
uint256 homeScore;
uint256 awayScore;
bool finished;
bool rewardSent;
uint256 jackpot;
uint256 totalHomeWinContributions;
uint256 totalAwayWinContributions;
uint256 totalDrawContributions;
}
struct Team {
uint256 teamNumber;
string teamName;
uint256 totalContributions;
}
struct Contribution {
address contributor;
uint256 id;
uint256 contribution;
uint256 timestamp;
}
address[] public allContributors;
mapping (address => uint256) public allContributorsMap;
mapping (address => uint256) public contributorsAccountBonus;
mapping (address => uint256) public contributorsEarlyBonus;
mapping (address => uint256) public contributorsTopBonus;
address[] public allWinners;
mapping (address => uint256) public allWinnersMap;
mapping (uint256 => Team) public teams;
mapping (address => mapping(uint256 => uint256)) public teamsContributions;
mapping (address => mapping(uint256 => uint256)) public teamsContributionsSent;
mapping (uint256 => Match) public matches;
mapping (address => mapping(uint256 => uint256)) public matchesContributions;
mapping (address => mapping(uint256 => uint256)) public matchesContributionsSent;
uint256 public championJackpot;
bool public championRewardSent;
uint256 championNumber;
constructor() public {
founder = msg.sender;
haltFlag = false;
}
function SetHalt(bool halt) public {
if (msg.sender != founder) revert();
haltFlag = halt;
}
function SetFounder(address newFounder) public returns (bool) {
if (msg.sender != founder) revert();
founder = newFounder;
return true;
}
function AddContributor(address contributor) {
if (allContributorsMap[contributor]==0) {
allContributors.push(contributor);
}
allContributorsMap[contributor] = 1;
}
function AddMatch(uint256 matchNumber, uint256 homeTeamNumber, uint256 awayTeamNumber, uint256 startTime) public returns (bool) {
if (msg.sender != founder) revert();
matches[matchNumber].matchNumber = matchNumber;
matches[matchNumber].homeTeamNumber = homeTeamNumber;
matches[matchNumber].awayTeamNumber = awayTeamNumber;
matches[matchNumber].startTime = startTime;
matches[matchNumber].finished = false;
return true;
}
function AddTeam(uint256 teamNumber, string teamName) public returns (bool) {
if (msg.sender != founder) revert();
teams[teamNumber].teamNumber = teamNumber;
teams[teamNumber].teamName = teamName;
return true;
}
function FinalizeMatch(uint256 matchNumber, uint256 homeScore, uint256 awayScore) public returns (bool) {
if (msg.sender != founder) revert();
if (matches[matchNumber].matchNumber == 0) revert();
matches[matchNumber].homeScore = homeScore;
matches[matchNumber].awayScore = awayScore;
matches[matchNumber].finished = true;
return true;
}
function ChampionBet(address sender, uint256 teamNumber) public payable returns (bool) {
if (haltFlag) revert();
if (teams[teamNumber].teamNumber == 0) revert();
if (msg.value < contributionLowerBound / tokenRatio) revert();
if (msg.value > contributionUpperBound / tokenRatio) revert();
if (matches[61].startTime < now) revert(); //before the first game of final 8
uint256 totalContribution = 0;
if (accountBonusLimit >= unitAccountBonus && contributorsAccountBonus[sender] == 0) {
contributorsAccountBonus[sender] = unitAccountBonus;
accountBonusLimit -= unitAccountBonus;
totalContribution += unitAccountBonus;
}
if (earlyBonusLimit >= unitEarlyBonus && contributorsEarlyBonus[sender] == 0) {
contributorsEarlyBonus[sender] = unitEarlyBonus;
earlyBonusLimit -= unitEarlyBonus;
totalContribution += unitEarlyBonus;
}
gTotalContribution += msg.value * tokenRatio;
totalContribution += msg.value * tokenRatio;
championJackpot += totalContribution;
teams[teamNumber].totalContributions += totalContribution;
teamsContributions[sender][teamNumber] += totalContribution;
AddContributor(sender);
return true;
}
function SingleMatchBet(address sender, uint256 matchNumber, uint256 result) public payable returns (bool) {
if (haltFlag) revert();
if (msg.value < contributionLowerBound / tokenRatio) revert();
if (msg.value > contributionUpperBound / tokenRatio) revert();
if (matches[matchNumber].startTime < now) revert();
uint256 totalContribution = 0;
if (result < 3 && result >= 0) {
if (accountBonusLimit >= unitAccountBonus && contributorsAccountBonus[sender] == 0) {
contributorsAccountBonus[sender] = unitAccountBonus;
accountBonusLimit -= unitAccountBonus;
totalContribution += unitAccountBonus;
}
if (earlyBonusLimit >= unitEarlyBonus && contributorsEarlyBonus[sender] == 0) {
contributorsEarlyBonus[sender] = unitEarlyBonus;
earlyBonusLimit -= unitEarlyBonus;
totalContribution += unitEarlyBonus;
}
totalContribution += msg.value * tokenRatio;
gTotalContribution += msg.value * tokenRatio;
AddContributor(sender);
} else {
revert();
}
matchesContributions[sender][result + 3 * matchNumber] += totalContribution;
if (result == 0) {
//away wins
matches[matchNumber].totalAwayWinContributions += totalContribution;
} else if (result == 1) {
//draw
matches[matchNumber].totalDrawContributions += totalContribution;
} else if (result == 2) {
//home wins
matches[matchNumber].totalHomeWinContributions += totalContribution;
}
matches[matchNumber].jackpot += totalContribution;
return true;
}
function SetChampion(uint256 teamNumber) public {
if (msg.sender != founder) revert();
if (teams[teamNumber].teamNumber == 0) revert();
championNumber = teamNumber;
}
function SendoutSingleMatchReward(uint256 matchNumber) public {
if (msg.sender != founder) revert();
if (!matches[matchNumber].finished) revert();
if (matches[matchNumber].rewardSent) revert();
uint256 distJackpot = matches[matchNumber].jackpot;
uint256 contributorsLength = allContributors.length;
uint256 i = 0;
address contributor = 0x0;
uint256 contribution = 0;
uint256 dist = 0;
if (matches[matchNumber].homeScore > matches[matchNumber].awayScore && matches[matchNumber].totalHomeWinContributions > 0) {
for (i=0; i<contributorsLength; i++) {
contributor = allContributors[i];
contribution = matchesContributions[contributor][matchNumber * 3 + 2] - matchesContributionsSent[contributor][matchNumber * 3 + 2];
if (contribution>0) {
matchesContributionsSent[contributor][matchNumber * 3 + 2] += contribution;
dist = distJackpot * contribution / matches[matchNumber].totalHomeWinContributions / tokenRatio;
AddWinAmount(dist, contributor);
if (!contributor.send(dist)) {
revert();
}
}
}
matches[matchNumber].rewardSent = true;
} else if (matches[matchNumber].homeScore == matches[matchNumber].awayScore && matches[matchNumber].totalDrawContributions > 0) {
for (i=0; i<contributorsLength; i++) {
contributor = allContributors[i];
contribution = matchesContributions[contributor][matchNumber * 3 + 1] - matchesContributionsSent[contributor][matchNumber * 3 + 1];
if (contribution>0) {
matchesContributionsSent[contributor][matchNumber * 3 + 1] += contribution;
dist = distJackpot * contribution / matches[matchNumber].totalDrawContributions / tokenRatio;
AddWinAmount(dist, contributor);
if (!contributor.send(dist)) {
revert();
}
}
}
matches[matchNumber].rewardSent = true;
} else if (matches[matchNumber].homeScore < matches[matchNumber].awayScore && matches[matchNumber].totalAwayWinContributions > 0) {
for (i=0; i<contributorsLength; i++) {
contributor = allContributors[i];
contribution = matchesContributions[contributor][matchNumber * 3] - matchesContributionsSent[contributor][matchNumber * 3];
if (contribution>0) {
matchesContributionsSent[contributor][matchNumber * 3] += contribution;
dist = distJackpot * contribution / matches[matchNumber].totalAwayWinContributions / tokenRatio;
AddWinAmount(dist, contributor);
if (!contributor.send(dist)) {
revert();
}
}
}
matches[matchNumber].rewardSent = true;
}
}
function SendoutChampionReward() public {
if (msg.sender != founder) revert();
if (championRewardSent) revert();
if (championNumber == 0) revert();
uint256 distJackpot = championJackpot;
uint256 contributorsLength = allContributors.length;
if (teams[championNumber].totalContributions == 0) revert();
address contributor = 0x0;
uint256 contribution = 0;
uint256 dist = 0;
for (uint256 i=0; i<contributorsLength; i++) {
contributor = allContributors[i];
contribution = teamsContributions[contributor][championNumber] - teamsContributionsSent[contributor][championNumber];
if (contribution>0) {
teamsContributionsSent[contributor][championNumber] += contribution;
dist = distJackpot * contribution / teams[championNumber].totalContributions / tokenRatio;
AddWinAmount(dist, contributor);
if (!contributor.send(dist)) {
revert();
}
}
}
championRewardSent = true;
}
function AddWinAmount(uint256 amount, address winner) {
if (allWinnersMap[winner]==0) {
allWinners.push(winner);
}
allWinnersMap[winner] += amount;
}
function SendoutTopBonus() public {
if (msg.sender != founder) revert();
//top 10 winners will get the top bonus
uint256 i = allWinners.length;
if (i > 10) {
i = 10;
}
uint256 totalWin = 0;
uint256 j = 0;
address winner;
uint256 winAmount = 0;
uint256 dist = 0;
for (j=0; j<i; j++) {
winner = allWinners[j];
totalWin += allWinnersMap[winner];
}
for (j=0; j<i; j++) {
winner = allWinners[j];
winAmount = allWinnersMap[winner];
dist = winAmount * topBonusLimit / totalWin / tokenRatio;
if (dist * tokenRatio < topBonusLimit) {
if (!winner.send(dist)) {
revert();
}
}
}
}
function ManualTransfer(uint256 amount, address to) public {
if (msg.sender != founder) revert();
to.transfer(amount);
}
function SafetySendout(uint256 amount) public {
if (msg.sender != founder) revert();
founder.transfer(amount);
}
function () public payable {
}
//TODO: more to add
}
|
away winsdrawhome wins
|
function SingleMatchBet(address sender, uint256 matchNumber, uint256 result) public payable returns (bool) {
if (haltFlag) revert();
if (msg.value < contributionLowerBound / tokenRatio) revert();
if (msg.value > contributionUpperBound / tokenRatio) revert();
if (matches[matchNumber].startTime < now) revert();
uint256 totalContribution = 0;
if (result < 3 && result >= 0) {
if (accountBonusLimit >= unitAccountBonus && contributorsAccountBonus[sender] == 0) {
contributorsAccountBonus[sender] = unitAccountBonus;
accountBonusLimit -= unitAccountBonus;
totalContribution += unitAccountBonus;
}
if (earlyBonusLimit >= unitEarlyBonus && contributorsEarlyBonus[sender] == 0) {
contributorsEarlyBonus[sender] = unitEarlyBonus;
earlyBonusLimit -= unitEarlyBonus;
totalContribution += unitEarlyBonus;
}
totalContribution += msg.value * tokenRatio;
gTotalContribution += msg.value * tokenRatio;
AddContributor(sender);
revert();
}
matchesContributions[sender][result + 3 * matchNumber] += totalContribution;
if (result == 0) {
matches[matchNumber].totalAwayWinContributions += totalContribution;
matches[matchNumber].totalDrawContributions += totalContribution;
matches[matchNumber].totalHomeWinContributions += totalContribution;
}
matches[matchNumber].jackpot += totalContribution;
return true;
}
| 13,106,541 |
[
1,
26718,
31307,
9446,
8712,
31307,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
10326,
2060,
38,
278,
12,
2867,
5793,
16,
2254,
5034,
845,
1854,
16,
2254,
5034,
563,
13,
1071,
8843,
429,
1135,
261,
6430,
13,
288,
203,
3639,
309,
261,
76,
2390,
4678,
13,
15226,
5621,
203,
3639,
309,
261,
3576,
18,
1132,
411,
24880,
24094,
342,
1147,
8541,
13,
15226,
5621,
203,
3639,
309,
261,
3576,
18,
1132,
405,
24880,
21328,
342,
1147,
8541,
13,
15226,
5621,
203,
3639,
309,
261,
8436,
63,
1916,
1854,
8009,
1937,
950,
411,
2037,
13,
15226,
5621,
203,
203,
3639,
2254,
5034,
2078,
442,
4027,
273,
374,
31,
203,
3639,
309,
261,
2088,
411,
890,
597,
563,
1545,
374,
13,
288,
203,
5411,
309,
261,
4631,
38,
22889,
3039,
1545,
2836,
3032,
38,
22889,
597,
13608,
13595,
3032,
38,
22889,
63,
15330,
65,
422,
374,
13,
288,
203,
7734,
13608,
13595,
3032,
38,
22889,
63,
15330,
65,
273,
2836,
3032,
38,
22889,
31,
203,
7734,
2236,
38,
22889,
3039,
3947,
2836,
3032,
38,
22889,
31,
203,
7734,
2078,
442,
4027,
1011,
2836,
3032,
38,
22889,
31,
203,
5411,
289,
203,
5411,
309,
261,
2091,
715,
38,
22889,
3039,
1545,
2836,
41,
20279,
38,
22889,
597,
13608,
13595,
41,
20279,
38,
22889,
63,
15330,
65,
422,
374,
13,
288,
203,
7734,
13608,
13595,
41,
20279,
38,
22889,
63,
15330,
65,
273,
2836,
41,
20279,
38,
22889,
31,
203,
7734,
11646,
38,
22889,
3039,
3947,
2836,
41,
20279,
38,
22889,
31,
203,
7734,
2078,
442,
4027,
1011,
2836,
41,
20279,
38,
22889,
31,
203,
5411,
289,
203,
203,
2
] |
./full_match/288/0x59d89c0dF59C3453428FA39cAd2c0ead7C100c89/sources/contracts/Comptroller.sol
|
* @notice Checks if the account should be allowed to redeem tokens in the given market @param cToken The market to verify the redeem against @param redeemer The account which would redeem the tokens @param redeemTokens The number of cTokens to exchange for the underlying asset in the market @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)/ Require tokens is zero or amount is also zero
|
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
Exp memory exchangeRate = Exp({
mantissa: CToken(cToken).exchangeRateStored()
});
uint redeemAmount = mul_ScalarTruncate(exchangeRate, redeemTokens);
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
uint supplyTokens = CToken(cToken).totalSupply();
uint redeemerTokens = CToken(cToken).balanceOf(redeemer);
distributeSupplierComp(cToken, redeemer, redeemerTokens);
return uint(Error.NO_ERROR);
}
| 7,103,336 |
[
1,
4081,
309,
326,
2236,
1410,
506,
2935,
358,
283,
24903,
2430,
316,
326,
864,
13667,
225,
276,
1345,
1021,
13667,
358,
3929,
326,
283,
24903,
5314,
225,
283,
24903,
264,
1021,
2236,
1492,
4102,
283,
24903,
326,
2430,
225,
283,
24903,
5157,
1021,
1300,
434,
276,
5157,
358,
7829,
364,
326,
6808,
3310,
316,
326,
13667,
327,
374,
309,
326,
283,
24903,
353,
2935,
16,
3541,
279,
23161,
17,
556,
14886,
555,
981,
261,
9704,
1068,
13289,
18,
18281,
13176,
12981,
2430,
353,
3634,
578,
3844,
353,
2546,
3634,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
283,
24903,
5042,
12,
2867,
276,
1345,
16,
1758,
283,
24903,
264,
16,
2254,
283,
24903,
5157,
13,
3903,
1135,
261,
11890,
13,
288,
203,
3639,
2254,
2935,
273,
283,
24903,
5042,
3061,
12,
71,
1345,
16,
283,
24903,
264,
16,
283,
24903,
5157,
1769,
203,
3639,
309,
261,
8151,
480,
2254,
12,
668,
18,
3417,
67,
3589,
3719,
288,
203,
5411,
327,
2935,
31,
203,
3639,
289,
203,
203,
3639,
7784,
3778,
7829,
4727,
273,
7784,
12590,
203,
5411,
31340,
30,
225,
385,
1345,
12,
71,
1345,
2934,
16641,
4727,
18005,
1435,
203,
3639,
15549,
203,
3639,
2254,
283,
24903,
6275,
273,
14064,
67,
13639,
25871,
12,
16641,
4727,
16,
283,
24903,
5157,
1769,
203,
203,
3639,
309,
261,
266,
24903,
5157,
422,
374,
597,
283,
24903,
6275,
405,
374,
13,
288,
203,
5411,
15226,
2932,
266,
24903,
5157,
3634,
8863,
203,
3639,
289,
203,
203,
3639,
2254,
14467,
5157,
273,
385,
1345,
12,
71,
1345,
2934,
4963,
3088,
1283,
5621,
203,
3639,
2254,
283,
24903,
264,
5157,
273,
385,
1345,
12,
71,
1345,
2934,
12296,
951,
12,
266,
24903,
264,
1769,
203,
203,
3639,
25722,
13254,
2945,
12,
71,
1345,
16,
283,
24903,
264,
16,
283,
24903,
264,
5157,
1769,
203,
203,
3639,
327,
2254,
12,
668,
18,
3417,
67,
3589,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: UNLICENSED
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/TokenTimelock.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IUniswapV2Router02.sol";
import "./IUniswapV2Factory.sol";
pragma solidity ^0.7.3;
contract FontsPresale is Context, ReentrancyGuard, Ownable {
using SafeMath for uint;
using SafeMath for uint256;
using SafeERC20 for IERC20;
//===============================================//
// Contract Variables: Mainnet //
//===============================================//
uint256 public MIN_CONTRIBUTION = 0.1 ether;
uint256 public MAX_CONTRIBUTION = 6 ether;
uint256 public HARD_CAP = 180 ether; //@change for testing
uint256 constant FONTS_PER_ETH_PRESALE = 1111;
uint256 constant FONTS_PER_ETH_UNISWAP = 700;
uint256 public UNI_LP_ETH = 86 ether;
uint256 public UNI_LP_FONT;
uint256 public constant UNLOCK_PERCENT_PRESALE_INITIAL = 50; //For presale buyers instant release
uint256 public constant UNLOCK_PERCENT_PRESALE_SECOND = 30; //For presale buyers after 30 days
uint256 public constant UNLOCK_PERCENT_PRESALE_FINAL = 20; //For presale buyers after 60 days
uint256 public DURATION_REFUND = 7 days;
uint256 public DURATION_LIQUIDITY_LOCK = 365 days;
uint256 public DURATION_TOKEN_DISTRIBUTION_ROUND_2 = 30 days;
uint256 public DURATION_TOKEN_DISTRIBUTION_ROUND_3 = 60 days;
address FONT_TOKEN_ADDRESS = 0x4C25Bdf026Ea05F32713F00f73Ca55857Fbf6342; //FONT Token address
IUniswapV2Router02 constant UNISWAP_V2_ADDRESS = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Factory constant uniswapFactory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
//General variables
IERC20 public FONT_ERC20; //Font token address
address public ERC20_uniswapV2Pair; //Uniswap Pair address
TokenTimelock public UniLPTimeLock;
uint256 public tokensBought; //Total tokens bought
uint256 public tokensWithdrawn; //Total tokens withdrawn by buyers
bool public isStopped = false;
bool public presaleStarted = false;
bool public uniPairCreated = false;
bool public liquidityLocked = false;
bool public bulkRefunded = false;
bool public isFontDistributedR1 = false;
bool public isFontDistributedR2 = false;
bool public isFontDistributedR3 = false;
uint256 public roundTwoUnlockTime;
uint256 public roundThreeUnlockTime;
bool liquidityAdded = false;
address payable contract_owner;
uint256 public liquidityUnlockTime;
uint256 public ethSent; //ETH Received
uint256 public lockedLiquidityAmount;
uint256 public refundTime;
mapping(address => uint) ethSpent;
mapping(address => uint) fontBought;
mapping(address => uint) fontHolding;
address[] public contributors;
constructor() {
contract_owner = _msgSender();
//ChangeSettingsForTestnet();
UNI_LP_FONT = UNI_LP_ETH.mul(FONTS_PER_ETH_UNISWAP);
FONT_ERC20 = IERC20(FONT_TOKEN_ADDRESS);
}
//@done
receive() external payable {
buyTokens();
}
//@done
function allowRefunds() external onlyOwner nonReentrant {
isStopped = true;
}
//@done
function buyTokens() public payable nonReentrant {
require(_msgSender() == tx.origin);
require(presaleStarted == true, "Presale is paused");
require(msg.value >= MIN_CONTRIBUTION, "Less than 0.1 ETH");
require(msg.value <= MAX_CONTRIBUTION, "More than 6 ETH");
require(ethSent < HARD_CAP, "Hardcap reached");
require(msg.value.add(ethSent) <= HARD_CAP, "Hardcap will reached");
require(ethSpent[_msgSender()].add(msg.value) <= MAX_CONTRIBUTION, "> 6 ETH");
require(!isStopped, "Presale stopped"); //@todo
uint256 tokens = msg.value.mul(FONTS_PER_ETH_PRESALE);
require(FONT_ERC20.balanceOf(address(this)) >= tokens, "Not enough tokens"); //@tod
if(ethSpent[_msgSender()] == 0) {
contributors.push(_msgSender()); //Create list of contributors
}
ethSpent[_msgSender()] = ethSpent[_msgSender()].add(msg.value);
tokensBought = tokensBought.add(tokens);
ethSent = ethSent.add(msg.value);
fontBought[_msgSender()] = fontBought[_msgSender()].add(tokens); //Add fonts bought by contributor
fontHolding[_msgSender()] = fontHolding[_msgSender()].add(tokens); //Add fonts Holding by contributor
}
//@done, create unipair first.
function createUniPair() external onlyOwner {
require(!liquidityAdded, "liquidity Already added");
require(!uniPairCreated, "Already Created Unipair");
ERC20_uniswapV2Pair = uniswapFactory.createPair(address(FONT_ERC20), UNISWAP_V2_ADDRESS.WETH());
uniPairCreated = true;
}
//@done
function addLiquidity() external onlyOwner {
require(!liquidityAdded, "liquidity Already added");
require(ethSent >= HARD_CAP, "Hard cap not reached");
require(uniPairCreated, "Uniswap pair not created");
FONT_ERC20.approve(address(UNISWAP_V2_ADDRESS), UNI_LP_FONT);
UNISWAP_V2_ADDRESS.addLiquidityETH{ value: UNI_LP_ETH } (
address(FONT_ERC20),
UNI_LP_FONT,
UNI_LP_FONT,
UNI_LP_ETH,
address(contract_owner),
block.timestamp
);
liquidityAdded = true;
if(!isStopped)
isStopped = true;
//Set duration for FONT distribution
roundTwoUnlockTime = block.timestamp.add(DURATION_TOKEN_DISTRIBUTION_ROUND_2);
roundThreeUnlockTime = block.timestamp.add(DURATION_TOKEN_DISTRIBUTION_ROUND_3);
}
//Lock the liquidity
function lockLiquidity() external onlyOwner {
require(liquidityAdded, "Add Liquidity");
require(!liquidityLocked, "Already Locked");
//Lock the Liquidity
IERC20 liquidityTokens = IERC20(ERC20_uniswapV2Pair); //Get the Uni LP token
if(liquidityUnlockTime <= block.timestamp) {
liquidityUnlockTime = block.timestamp.add(DURATION_LIQUIDITY_LOCK);
}
UniLPTimeLock = new TokenTimelock(liquidityTokens, contract_owner, liquidityUnlockTime);
liquidityLocked = true;
lockedLiquidityAmount = liquidityTokens.balanceOf(contract_owner);
}
//Unlock it after 1 year
function unlockLiquidity() external onlyOwner {
UniLPTimeLock.release();
}
//Check when Uniswap V2 tokens are unlocked
function unlockLiquidityTime() external view returns(uint256) {
return UniLPTimeLock.releaseTime();
}
/*
//FONT can be claim by investors after sale success, It is optional
//@done
function claimFontRoundOne() external nonReentrant {
require(liquidityAdded,"FontsCrowdsale: can only claim after listing in UNI");
require(fontHolding[_msgSender()] > 0, "FontsCrowdsale: No FONT token available for this address to claim");
uint256 tokenAmount_ = fontBought[_msgSender()];
tokenAmount_ = tokenAmount_.mul(UNLOCK_PERCENT_PRESALE_INITIAL).div(100);
fontHolding[_msgSender()] = fontHolding[_msgSender()].sub(tokenAmount_);
// Transfer the $FONTs to the beneficiary
FONT_ERC20.safeTransfer(_msgSender(), tokenAmount_);
tokensWithdrawn = tokensWithdrawn.add(tokenAmount_);
}
//30% of FONT can be claim by investors after 30 days from unilisting
//@done
function claimFontRoundTwo() external nonReentrant {
require(liquidityAdded,"Claimble after UNI list");
require(fontHolding[_msgSender()] > 0, "0 FONT");
require(block.timestamp >= roundTwoUnlockTime, "Timelocked");
uint256 tokenAmount_ = fontBought[_msgSender()];
tokenAmount_ = tokenAmount_.mul(UNLOCK_PERCENT_PRESALE_SECOND).div(100);
fontHolding[_msgSender()] = fontHolding[_msgSender()].sub(tokenAmount_);
// Transfer the $FONTs to the beneficiary
FONT_ERC20.safeTransfer(_msgSender(), tokenAmount_);
tokensWithdrawn = tokensWithdrawn.add(tokenAmount_);
}
//20% of FONT can be claim by investors after 20 days from unilisting
//@done
function claimFontRoundThree() external nonReentrant {
require(liquidityAdded,"Claimble after UNI list");
require(fontHolding[_msgSender()] > 0, "0 FONT");
require(block.timestamp >= roundThreeUnlockTime, "Timelocked");
uint256 tokenAmount_ = fontBought[_msgSender()];
tokenAmount_ = tokenAmount_.mul(UNLOCK_PERCENT_PRESALE_FINAL).div(100);
fontHolding[_msgSender()] = fontHolding[_msgSender()].sub(tokenAmount_);
// Transfer the $FONTs to the beneficiary
FONT_ERC20.safeTransfer(_msgSender(), tokenAmount_);
tokensWithdrawn = tokensWithdrawn.add(tokenAmount_);
}
*/
//@done distribute first round of tokens
function distributeTokensRoundOne() external onlyOwner {
require(liquidityAdded, "Add Uni Liquidity");
require(!isFontDistributedR1, "Round 1 done");
for (uint i=0; i<contributors.length; i++) {
if(fontHolding[contributors[i]] > 0) {
uint256 tokenAmount_ = fontBought[contributors[i]];
tokenAmount_ = tokenAmount_.mul(UNLOCK_PERCENT_PRESALE_INITIAL).div(100);
fontHolding[contributors[i]] = fontHolding[contributors[i]].sub(tokenAmount_);
// Transfer the $FONTs to the beneficiary
FONT_ERC20.safeTransfer(contributors[i], tokenAmount_);
tokensWithdrawn = tokensWithdrawn.add(tokenAmount_);
}
}
isFontDistributedR1 = true;
}
//Let any one call next 30% of distribution
//@done
function distributeTokensRoundTwo() external nonReentrant{
require(liquidityAdded, "Add Uni Liquidity");
require(isFontDistributedR1, "Do Round 1");
require(block.timestamp >= roundTwoUnlockTime, "Timelocked");
require(!isFontDistributedR2, "Round 2 done");
for (uint i=0; i<contributors.length; i++) {
if(fontHolding[contributors[i]] > 0) {
uint256 tokenAmount_ = fontBought[contributors[i]];
tokenAmount_ = tokenAmount_.mul(UNLOCK_PERCENT_PRESALE_SECOND).div(100);
fontHolding[contributors[i]] = fontHolding[contributors[i]].sub(tokenAmount_);
// Transfer the $FONTs to the beneficiary
FONT_ERC20.safeTransfer(contributors[i], tokenAmount_);
tokensWithdrawn = tokensWithdrawn.add(tokenAmount_);
}
}
isFontDistributedR2 = true;
}
//Let any one call final 20% of distribution
//@done
function distributeTokensRoundThree() external nonReentrant{
require(liquidityAdded, "Add Uni Liquidity");
require(isFontDistributedR2, "Do Round 2");
require(block.timestamp >= roundThreeUnlockTime, "Timelocked");
require(!isFontDistributedR3, "Round 3 done");
for (uint i=0; i<contributors.length; i++) {
if(fontHolding[contributors[i]] > 0) {
uint256 tokenAmount_ = fontBought[contributors[i]];
tokenAmount_ = tokenAmount_.mul(UNLOCK_PERCENT_PRESALE_FINAL).div(100);
fontHolding[contributors[i]] = fontHolding[contributors[i]].sub(tokenAmount_);
// Transfer the $FONTs to the beneficiary
FONT_ERC20.safeTransfer(contributors[i], tokenAmount_);
tokensWithdrawn = tokensWithdrawn.add(tokenAmount_);
}
}
isFontDistributedR3 = true;
}
//@done
//Withdraw the collected remaining eth
function withdrawEth(uint amount) external onlyOwner returns(bool){
require(liquidityAdded,"After UNI LP");
require(amount <= address(this).balance);
contract_owner.transfer(amount);
return true;
}
//@done
//Allow admin to withdraw any pending FONT after everyone withdraw, 60 days
function withdrawFont(uint amount) external onlyOwner returns(bool){
require(liquidityAdded,"After UNI LP");
require(isFontDistributedR3, "After distribute to buyers");
FONT_ERC20.safeTransfer(_msgSender(), amount);
return true;
}
//@done
function userFontBalance(address user) external view returns (uint256) {
return fontHolding[user];
}
//@done
function userFontBought(address user) external view returns (uint256) {
return fontBought[user];
}
//@done
function userEthContribution(address user) external view returns (uint256) {
return ethSpent[user];
}
//@done
function getRefund() external nonReentrant {
require(_msgSender() == tx.origin);
require(isStopped, "Should be stopped");
require(!liquidityAdded);
// To get refund it not reached hard cap and 7 days had passed
require(ethSent < HARD_CAP && block.timestamp >= refundTime, "Cannot refund");
uint256 amount = ethSpent[_msgSender()];
require(amount > 0, "No ETH");
address payable user = _msgSender();
ethSpent[user] = 0;
fontBought[user] = 0;
fontHolding[user] = 0;
user.transfer(amount);
}
//@done let anyone call it
function bulkRefund() external nonReentrant {
require(!liquidityAdded);
require(!bulkRefunded, "Already refunded");
require(isStopped, "Should be stopped");
// To get refund it not reached hard cap and 7 days had passed
require(ethSent < HARD_CAP && block.timestamp >= refundTime, "Cannot refund");
for (uint i=0; i<contributors.length; i++) {
address payable user = payable(contributors[i]);
uint256 amount = ethSpent[user];
if(amount > 0) {
ethSpent[user] = 0;
fontBought[user] = 0;
fontHolding[user] = 0;
user.transfer(amount);
}
}
bulkRefunded = true;
}
//@done Call this to kickstart fundraise
function startPresale() external onlyOwner {
liquidityUnlockTime = block.timestamp.add(DURATION_LIQUIDITY_LOCK);
refundTime = block.timestamp.add(DURATION_REFUND);
presaleStarted = true;
}
//@done
function pausePresale() external onlyOwner {
presaleStarted = false;
}
}
// 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.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./SafeERC20.sol";
/**
* @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 _token;
// beneficiary of tokens after they are released
address private _beneficiary;
// timestamp when token release is enabled
uint256 private _releaseTime;
constructor (IERC20 token_, address beneficiary_, uint256 releaseTime_) public {
// solhint-disable-next-line not-rely-on-time
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 {
// solhint-disable-next-line not-rely-on-time
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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.3;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.3;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
// 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;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
Lock the liquidityLock the Liquidity
|
function lockLiquidity() external onlyOwner {
require(liquidityAdded, "Add Liquidity");
require(!liquidityLocked, "Already Locked");
if(liquidityUnlockTime <= block.timestamp) {
liquidityUnlockTime = block.timestamp.add(DURATION_LIQUIDITY_LOCK);
}
UniLPTimeLock = new TokenTimelock(liquidityTokens, contract_owner, liquidityUnlockTime);
liquidityLocked = true;
lockedLiquidityAmount = liquidityTokens.balanceOf(contract_owner);
}
| 10,402,305 |
[
1,
2531,
326,
4501,
372,
24237,
2531,
326,
511,
18988,
24237,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
2176,
48,
18988,
24237,
1435,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
549,
372,
24237,
8602,
16,
315,
986,
511,
18988,
24237,
8863,
203,
3639,
2583,
12,
5,
549,
372,
24237,
8966,
16,
315,
9430,
3488,
329,
8863,
203,
3639,
309,
12,
549,
372,
24237,
7087,
950,
1648,
1203,
18,
5508,
13,
288,
203,
5411,
4501,
372,
24237,
7087,
950,
273,
1203,
18,
5508,
18,
1289,
12,
24951,
67,
2053,
53,
3060,
4107,
67,
6589,
1769,
203,
3639,
289,
203,
3639,
1351,
77,
14461,
950,
2531,
273,
394,
3155,
10178,
292,
975,
12,
549,
372,
24237,
5157,
16,
6835,
67,
8443,
16,
4501,
372,
24237,
7087,
950,
1769,
203,
3639,
4501,
372,
24237,
8966,
273,
638,
31,
203,
3639,
8586,
48,
18988,
24237,
6275,
273,
4501,
372,
24237,
5157,
18,
12296,
951,
12,
16351,
67,
8443,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// SYS 64738
// Version 2.0
// Author: 0xTycoon
// Contributor: Alphasoup <twitter: alphasoups>
// Special Thanks: straybits1, cryptopunkart, cyounessi1, ethereumdegen, Punk7572, sherone.eth,
// songadaymann, Redlioneye.eth, tw1tte7, PabloPunkasso, Kaprekar_Punk, aradtski,
// phantom_scribbs, Cryptopapa.eth, johnhenderson, thekriskay, PerfectoidPeter,
// uxt_exe, 0xUnicorn, dansickles.eth, Blon Dee#9649, VRPunk1, Don Seven Slices, hogo.eth,
// GeoCities#5700, "HP OfficeJet Pro 9015e #2676", gigiuz#0061, danpolko.eth, mariano.eth,
// 0xfoobar, jakerockland, Mudit__Gupta, BokkyPooBah, 0xaaby.eth, and
// everyone at the discord, and all the awesome people who gave feedback for this project!
// Greetings to: Punk3395, foxthepunk, bushleaf.eth, 570KylΞ.eth, bushleaf.eth, Tokyolife, Joshuad.eth (1641),
// markchesler_coinwitch, decideus.eth, zachologylol, punk8886, jony_bee, nfttank, DolAtoR, punk8886
// DonJon.eth, kilifibaobab, joked507, cryptoed#3040, DroScott#7162, 0xAllen.eth, Tschuuuly#5158,
// MetasNomadic#0349, punk8653, NittyB, heygareth.eth, Aaru.eth, robertclarke.eth, Acmonides#6299,
// Gustavus99 (1871), Foobazzler
// Repo: github.com/0xTycoon/punksceo
pragma solidity ^0.8.11;
//import "./safemath.sol"; // don't need since v0.8
//import "./ceo.sol";
//import "hardhat/console.sol";
/*
PUNKS CEO (and "Cigarette" token)
WEB: https://punksceo.eth.limo / https://punksceo.eth.link
IPFS: See content hash record for punksceo.eth
Token Address: cigtoken.eth
, - ~ ~ ~ - ,
, ' ' ,
, 🚬 ,
, 🚬 ,
, 🚬 ,
, 🚬 ,
, ============= ,
, ||█ ,
, ============= ,
, , '
' - , _ _ _ , '
### THE RULES OF THE GAME
1. Anybody can buy the CEO title at any time using Cigarettes. (The CEO of all cryptopunks)
2. When buying the CEO title, you must nominate a punk, set the price and pre-pay the tax.
3. The CEO title can be bought from the existing CEO at any time.
4. To remain a CEO, a daily tax needs to be paid.
5. The tax is 0.1% of the price to buy the CEO title, to be charged per epoch.
6. The CEO can be removed if they fail to pay the tax. A reward of CIGs is paid to the whistleblower.
7. After Removing a CEO: A dutch auction is held, where the price will decrease 10% every half-an-epoch.
8. The price can be changed by the CEO at any time. (Once per block)
9. An epoch is 7200 blocks.
10. All the Cigarettes from the sale are burned.
11. All tax is burned
12. After buying the CEO title, the old CEO will get their unspent tax deposit refunded
### CEO perk
13. The CEO can increase or decrease the CIG farming block reward by 20% every 2nd epoch!
However, note that the issuance can never be more than 1000 CIG per block, also never under 0.0001 CIG.
14. THE CEO gets to hold a NFT in their wallet. There will only be ever 1 this NFT.
The purpose of this NFT is so that everyone can see that they are the CEO.
IMPORTANT: This NFT will be revoked once the CEO title changes.
Also, the NFT cannot be transferred by the owner, the only way to transfer is for someone else to buy the CEO title! (Think of this NFT as similar to a "title belt" in boxing.)
END
* states
* 0 = initial
* 1 = CEO reigning
* 2 = Dutch auction
* 3 = Migration
Notes:
It was decided that whoever buys the CEO title does not have to hold a punk and can nominate any punk they wish.
This is because some may hold their punks in cold storage, plus checking ownership costs additional gas.
Besides, CEOs are usually appointed by the board.
Credits:
- LP Staking based on code from SushiSwap's MasterChef.sol
- ERC20 & SafeMath based on lib from OpenZeppelin
*/
contract Cig {
//using SafeMath for uint256; // no need since Solidity 0.8
string public constant name = "Cigarette Token";
string public constant symbol = "CIG";
uint8 public constant decimals = 18;
uint256 public totalSupply = 0;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// UserInfo keeps track of user LP deposits and withdrawals
struct UserInfo {
uint256 deposit; // How many LP tokens the user has deposited.
uint256 rewardDebt; // keeps track of how much reward was paid out
}
mapping(address => UserInfo) public farmers; // keeps track of UserInfo for each staking address with own pool
mapping(address => UserInfo) public farmersMasterchef; // keeps track of UserInfo for each staking address with masterchef pool
mapping(address => uint256) public wBal; // keeps tracked of wrapped old cig
address public admin; // admin is used for deployment, burned after
ILiquidityPoolERC20 public lpToken; // lpToken is the address of LP token contract that's being staked.
uint256 public lastRewardBlock; // Last block number that cigarettes distribution occurs.
uint256 public accCigPerShare; // Accumulated cigarettes per share, times 1e12. See below.
uint256 public masterchefDeposits; // How much has been deposited onto the masterchef contract
uint256 public cigPerBlock; // CIGs per-block rewarded and split with LPs
bytes32 public graffiti; // a 32 character graffiti set when buying a CEO
ICryptoPunk public punks; // a reference to the CryptoPunks contract
event Deposit(address indexed user, uint256 amount); // when depositing LP tokens to stake
event Harvest(address indexed user, address to, uint256 amount);// when withdrawing LP tokens form staking
event Withdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed
event EmergencyWithdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed
event ChefDeposit(address indexed user, uint256 amount); // when depositing LP tokens to stake
event ChefWithdraw(address indexed user, uint256 amount); // when withdrawing LP tokens, no rewards claimed
event RewardUp(uint256 reward, uint256 upAmount); // when cigPerBlock is increased
event RewardDown(uint256 reward, uint256 downAmount); // when cigPerBlock is decreased
event Claim(address indexed owner, uint indexed punkIndex, uint256 value); // when a punk is claimed
mapping(uint => bool) public claims; // keep track of claimed punks
modifier onlyAdmin {
require(
msg.sender == admin,
"Only admin can call this"
);
_;
}
uint256 constant MIN_PRICE = 1e12; // 0.000001 CIG
uint256 constant CLAIM_AMOUNT = 100000 ether; // claim amount for each punk
uint256 constant MIN_REWARD = 1e14; // minimum block reward of 0.0001 CIG (1e14 wei)
uint256 constant MAX_REWARD = 1000 ether; // maximum block reward of 1000 CIG
uint256 constant STARTING_REWARDS = 512 ether;// starting rewards at end of migration
address public The_CEO; // address of CEO
uint public CEO_punk_index; // which punk id the CEO is using
uint256 public CEO_price = 50000 ether; // price to buy the CEO title
uint256 public CEO_state; // state has 3 states, described above.
uint256 public CEO_tax_balance; // deposit to be used to pay the CEO tax
uint256 public taxBurnBlock; // The last block when the tax was burned
uint256 public rewardsChangedBlock; // which block was the last reward increase / decrease
uint256 private immutable CEO_epoch_blocks; // secs per day divided by 12 (86400 / 12), assuming 12 sec blocks
uint256 private immutable CEO_auction_blocks; // 3600 blocks
// NewCEO 0x09b306c6ea47db16bdf4cc36f3ea2479af494cd04b4361b6485d70f088658b7e
event NewCEO(address indexed user, uint indexed punk_id, uint256 new_price, bytes32 graffiti); // when a CEO is bought
// TaxDeposit 0x2ab3b3b53aa29a0599c58f343221e29a032103d015c988fae9a5cdfa5c005d9d
event TaxDeposit(address indexed user, uint256 amount); // when tax is deposited
// RevenueBurned 0x1b1be00a9ca19f9c14f1ca5d16e4aba7d4dd173c2263d4d8a03484e1c652c898
event RevenueBurned(address indexed user, uint256 amount); // when tax is burned
// TaxBurned 0x9ad3c710e1cc4e96240264e5d3cd5aeaa93fd8bd6ee4b11bc9be7a5036a80585
event TaxBurned(address indexed user, uint256 amount); // when tax is burned
// CEODefaulted b69f2aeff650d440d3e7385aedf764195cfca9509e33b69e69f8c77cab1e1af1
event CEODefaulted(address indexed called_by, uint256 reward); // when CEO defaulted on tax
// CEOPriceChange 0x10c342a321267613a25f77d4273d7f2688bef174a7214bc3dde44b31c5064ff6
event CEOPriceChange(uint256 price); // when CEO changed price
modifier onlyCEO {
require(
msg.sender == The_CEO,
"only CEO can call this"
);
_;
}
IRouterV2 private immutable V2ROUTER; // address of router used to get the price quote
ICEOERC721 private immutable The_NFT; // reference to the CEO NFT token
address private immutable MASTERCHEF_V2; // address pointing to SushiSwap's MasterChefv2 contract
IOldCigtoken private immutable OC; // Old Contract
/**
* @dev constructor
* @param _cigPerBlock Number of CIG tokens rewarded per block
* @param _punks address of the cryptopunks contract
* @param _CEO_epoch_blocks how many blocks between each epochs
* @param _CEO_auction_blocks how many blocks between each auction discount
* @param _CEO_price starting price to become CEO (in CIG)
* @param _graffiti bytes32 initial graffiti message
* @param _NFT address pointing to the NFT contract
* @param _V2ROUTER address pointing to the SushiSwap router
* @param _OC address pointing to the original Cig Token contract
* @param _MASTERCHEF_V2 address for the sushi masterchef v2 contract
*/
constructor(
uint256 _cigPerBlock,
address _punks,
uint _CEO_epoch_blocks,
uint _CEO_auction_blocks,
uint256 _CEO_price,
bytes32 _graffiti,
address _NFT,
address _V2ROUTER,
address _OC,
uint256 _migration_epochs,
address _MASTERCHEF_V2
) {
cigPerBlock = _cigPerBlock;
admin = msg.sender; // the admin key will be burned after deployment
punks = ICryptoPunk(_punks);
CEO_epoch_blocks = _CEO_epoch_blocks;
CEO_auction_blocks = _CEO_auction_blocks;
CEO_price = _CEO_price;
graffiti = _graffiti;
The_NFT = ICEOERC721(_NFT);
V2ROUTER = IRouterV2(_V2ROUTER);
OC = IOldCigtoken(_OC);
lastRewardBlock =
block.number + (CEO_epoch_blocks * _migration_epochs); // set the migration window end
MASTERCHEF_V2 = _MASTERCHEF_V2;
CEO_state = 3; // begin in migration state
}
/**
* @dev buyCEO allows anybody to be the CEO
* @param _max_spend the total CIG that can be spent
* @param _new_price the new price for the punk (in CIG)
* @param _tax_amount how much to pay in advance (in CIG)
* @param _punk_index the id of the punk 0-9999
* @param _graffiti a little message / ad from the buyer
*/
function buyCEO(
uint256 _max_spend,
uint256 _new_price,
uint256 _tax_amount,
uint256 _punk_index,
bytes32 _graffiti
) external {
require (CEO_state != 3); // disabled in in migration state
if (CEO_state == 1 && (taxBurnBlock != block.number)) {
_burnTax(); // _burnTax can change CEO_state to 2
}
if (CEO_state == 2) {
// Auction state. The price goes down 10% every `CEO_auction_blocks` blocks
CEO_price = _calcDiscount();
}
require (CEO_price + _tax_amount <= _max_spend, "overpaid"); // prevent CEO over-payment
require (_new_price >= MIN_PRICE, "price 2 smol"); // price cannot be under 0.000001 CIG
require (_punk_index <= 9999, "invalid punk"); // validate the punk index
require (_tax_amount >= _new_price / 1000, "insufficient tax" ); // at least %0.1 fee paid for 1 epoch
transfer(address(this), CEO_price); // pay for the CEO title
_burn(address(this), CEO_price); // burn the revenue
emit RevenueBurned(msg.sender, CEO_price);
_returnDeposit(The_CEO, CEO_tax_balance); // return deposited tax back to old CEO
transfer(address(this), _tax_amount); // deposit tax (reverts if not enough)
CEO_tax_balance = _tax_amount; // store the tax deposit amount
_transferNFT(The_CEO, msg.sender); // yank the NFT to the new CEO
CEO_price = _new_price; // set the new price
CEO_punk_index = _punk_index; // store the punk id
The_CEO = msg.sender; // store the CEO's address
taxBurnBlock = block.number; // store the block number
// (tax may not have been burned if the
// previous state was 0)
CEO_state = 1;
graffiti = _graffiti;
emit TaxDeposit(msg.sender, _tax_amount);
emit NewCEO(msg.sender, _punk_index, _new_price, _graffiti);
}
/**
* @dev _returnDeposit returns the tax deposit back to the CEO
* @param _to address The address which you want to transfer to
* remember to update CEO_tax_balance after calling this
*/
function _returnDeposit(
address _to,
uint256 _amount
)
internal
{
if (_amount == 0) {
return;
}
balanceOf[address(this)] = balanceOf[address(this)] - _amount;
balanceOf[_to] = balanceOf[_to] + _amount;
emit Transfer(address(this), _to, _amount);
//CEO_tax_balance = 0; // can be omitted since value gets overwritten by caller
}
/**
* @dev transfer the NFT to a new wallet
*/
function _transferNFT(address _oldCEO, address _newCEO) internal {
The_NFT.transferFrom(_oldCEO, _newCEO, 0);
}
/**
* @dev depositTax pre-pays tax for the existing CEO.
* It may also burn any tax debt the CEO may have.
* @param _amount amount of tax to pre-pay
*/
function depositTax(uint256 _amount) external onlyCEO {
require (CEO_state == 1, "no CEO");
if (_amount > 0) {
transfer(address(this), _amount); // place the tax on deposit
CEO_tax_balance = CEO_tax_balance + _amount; // record the balance
emit TaxDeposit(msg.sender, _amount);
}
if (taxBurnBlock != block.number) {
_burnTax(); // settle any tax debt
taxBurnBlock = block.number;
}
}
/**
* @dev burnTax is called to burn tax.
* It removes the CEO if tax is unpaid.
* 1. deduct tax, update last update
* 2. if not enough tax, remove & begin auction
* 3. reward the caller by minting a reward from the amount indebted
* A Dutch auction begins where the price decreases 10% every hour.
*/
function burnTax() external {
if (taxBurnBlock == block.number) return;
if (CEO_state == 1) {
_burnTax();
taxBurnBlock = block.number;
}
}
/**
* @dev _burnTax burns any tax debt. Boots the CEO if defaulted, paying a reward to the caller
*/
function _burnTax() internal {
// calculate tax per block (tpb)
uint256 tpb = CEO_price / 1000 / CEO_epoch_blocks; // 0.1% per epoch
uint256 debt = (block.number - taxBurnBlock) * tpb;
if (CEO_tax_balance !=0 && CEO_tax_balance >= debt) { // Does CEO have enough deposit to pay debt?
CEO_tax_balance = CEO_tax_balance - debt; // deduct tax
_burn(address(this), debt); // burn the tax
emit TaxBurned(msg.sender, debt);
} else {
// CEO defaulted
uint256 default_amount = debt - CEO_tax_balance; // calculate how much defaulted
_burn(address(this), CEO_tax_balance); // burn the tax
emit TaxBurned(msg.sender, CEO_tax_balance);
CEO_state = 2; // initiate a Dutch auction.
CEO_tax_balance = 0;
_transferNFT(The_CEO, address(this)); // This contract holds the NFT temporarily
The_CEO = address(this); // This contract is the "interim CEO"
_mint(msg.sender, default_amount); // reward the caller for reporting tax default
emit CEODefaulted(msg.sender, default_amount);
}
}
/**
* @dev setPrice changes the price for the CEO title.
* @param _price the price to be paid. The new price most be larger tan MIN_PRICE and not default on debt
*/
function setPrice(uint256 _price) external onlyCEO {
require(CEO_state == 1, "No CEO in charge");
require (_price >= MIN_PRICE, "price 2 smol");
require (CEO_tax_balance >= _price / 1000, "price would default"); // need at least 0.1% for tax
if (block.number != taxBurnBlock) {
_burnTax();
taxBurnBlock = block.number;
}
// The state is 1 if the CEO hasn't defaulted on tax
if (CEO_state == 1) {
CEO_price = _price; // set the new price
emit CEOPriceChange(_price);
}
}
/**
* @dev rewardUp allows the CEO to increase the block rewards by %20
* Can only be called by the CEO every 2 epochs
* @return _amount increased by
*/
function rewardUp() external onlyCEO returns (uint256) {
require(CEO_state == 1, "No CEO in charge");
require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks");
require (cigPerBlock < MAX_REWARD, "reward already max");
rewardsChangedBlock = block.number;
uint256 _amount = cigPerBlock / 5; // %20
uint256 _new_reward = cigPerBlock + _amount;
if (_new_reward > MAX_REWARD) {
_amount = MAX_REWARD - cigPerBlock;
_new_reward = MAX_REWARD; // cap
}
cigPerBlock = _new_reward;
emit RewardUp(_new_reward, _amount);
return _amount;
}
/**
* @dev rewardDown decreases the block rewards by 20%
* Can only be called by the CEO every 2 epochs
*/
function rewardDown() external onlyCEO returns (uint256) {
require(CEO_state == 1, "No CEO in charge");
require(block.number > rewardsChangedBlock + (CEO_epoch_blocks*2), "wait more blocks");
require(cigPerBlock > MIN_REWARD, "reward already low");
rewardsChangedBlock = block.number;
uint256 _amount = cigPerBlock / 5; // %20
uint256 _new_reward = cigPerBlock - _amount;
if (_new_reward < MIN_REWARD) {
_amount = cigPerBlock - MIN_REWARD;
_new_reward = MIN_REWARD; // limit
}
cigPerBlock = _new_reward;
emit RewardDown(_new_reward, _amount);
return _amount;
}
/**
* @dev _calcDiscount calculates the discount for the CEO title based on how many blocks passed
*/
function _calcDiscount() internal view returns (uint256) {
unchecked {
uint256 d = (CEO_price / 10) // 10% discount
// multiply by the number of discounts accrued
* ((block.number - taxBurnBlock) / CEO_auction_blocks);
if (d > CEO_price) {
// overflow assumed, reset to MIN_PRICE
return MIN_PRICE;
}
uint256 price = CEO_price - d;
if (price < MIN_PRICE) {
price = MIN_PRICE;
}
return price;
}
}
/*
* 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Information used by the UI 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬
*/
/**
* @dev getStats helps to fetch some stats for the GUI in a single web3 call
* @param _user the address to return the report for
* @return uint256[27] the stats
* @return address of the current CEO
* @return bytes32 Current graffiti
*/
function getStats(address _user) external view returns(uint256[] memory, address, bytes32, uint112[] memory) {
uint[] memory ret = new uint[](27);
uint112[] memory reserves = new uint112[](2);
uint256 tpb = (CEO_price / 1000) / (CEO_epoch_blocks); // 0.1% per epoch
uint256 debt = (block.number - taxBurnBlock) * tpb;
uint256 price = CEO_price;
UserInfo memory info = farmers[_user];
if (CEO_state == 2) {
price = _calcDiscount();
}
ret[0] = CEO_state;
ret[1] = CEO_tax_balance;
ret[2] = taxBurnBlock; // the block number last tax burn
ret[3] = rewardsChangedBlock; // the block of the last staking rewards change
ret[4] = price; // price of the CEO title
ret[5] = CEO_punk_index; // punk ID of CEO
ret[6] = cigPerBlock; // staking reward per block
ret[7] = totalSupply; // total supply of CIG
if (address(lpToken) != address(0)) {
ret[8] = lpToken.balanceOf(address(this)); // Total LP staking
ret[16] = lpToken.balanceOf(_user); // not staked by user
ret[17] = pendingCig(_user); // pending harvest
(reserves[0], reserves[1], ) = lpToken.getReserves(); // uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast
ret[18] = V2ROUTER.getAmountOut(1 ether, uint(reserves[0]), uint(reserves[1])); // CIG price in ETH
if (isContract(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2))) { // are we on mainnet?
ILiquidityPoolERC20 ethusd = ILiquidityPoolERC20(address(0xC3D03e4F041Fd4cD388c549Ee2A29a9E5075882f)); // sushi DAI-WETH pool
uint112 r0;
uint112 r1;
(r0, r1, ) = ethusd.getReserves();
// get the price of ETH in USD
ret[19] = V2ROUTER.getAmountOut(1 ether, uint(r0), uint(r1)); // ETH price in USD
}
ret[22] = lpToken.totalSupply(); // total supply
}
ret[9] = block.number; // current block number
ret[10] = tpb; // "tax per block" (tpb)
ret[11] = debt; // tax debt accrued
ret[12] = lastRewardBlock; // the block of the last staking rewards payout update
ret[13] = info.deposit; // amount of LP tokens staked by user
ret[14] = info.rewardDebt; // amount of rewards paid out
ret[15] = balanceOf[_user]; // amount of CIG held by user
ret[20] = accCigPerShare; // Accumulated cigarettes per share
ret[21] = balanceOf[address(punks)]; // amount of CIG to be claimed
ret[23] = wBal[_user]; // wrapped cig balance
ret[24] = OC.balanceOf(_user); // balance of old cig in old isContract
ret[25] = OC.allowance(_user, address(this));// is old contract approved
(ret[26], ) = OC.userInfo(_user); // old contract stake bal
return (ret, The_CEO, graffiti, reserves);
}
/**
* @dev Returns true if `account` is a contract.
*
* credits https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/*
* 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Token distribution and farming stuff 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬
*/
/**
* @dev isClaimed checks to see if a punk was claimed
* @param _punkIndex the punk number
*/
function isClaimed(uint256 _punkIndex) external view returns (bool) {
if (claims[_punkIndex]) {
return true;
}
if (OC.claims(_punkIndex)) {
return true;
}
return false;
}
/**
* Claim claims the initial CIG airdrop using a punk
* @param _punkIndex the index of the punk, number between 0-9999
*/
function claim(uint256 _punkIndex) external returns(bool) {
require (CEO_state != 3, "invalid state"); // disabled in migration state
require (_punkIndex <= 9999, "invalid punk");
require(claims[_punkIndex] == false, "punk already claimed");
require(OC.claims(_punkIndex) == false, "punk already claimed"); // claimed in old contract
require(msg.sender == punks.punkIndexToAddress(_punkIndex), "punk 404");
claims[_punkIndex] = true;
balanceOf[address(punks)] = balanceOf[address(punks)] - CLAIM_AMOUNT; // deduct from the punks contract
balanceOf[msg.sender] = balanceOf[msg.sender] + CLAIM_AMOUNT; // deposit to the caller
emit Transfer(address(punks), msg.sender, CLAIM_AMOUNT);
emit Claim(msg.sender, _punkIndex, CLAIM_AMOUNT);
return true;
}
/**
* @dev Gets the LP supply, with masterchef deposits taken into account.
*/
function stakedlpSupply() public view returns(uint256)
{
return lpToken.balanceOf(address(this)) + masterchefDeposits;
}
/**
* @dev update updates the accCigPerShare value and mints new CIG rewards to be distributed to LP stakers
* Credits go to MasterChef.sol
* Modified the original by removing poolInfo as there is only a single pool
* Removed totalAllocPoint and pool.allocPoint
* pool.lastRewardBlock moved to lastRewardBlock
* There is no need for getMultiplier (rewards are adjusted by the CEO)
*
*/
function update() public {
if (block.number <= lastRewardBlock) {
return;
}
uint256 supply = stakedlpSupply();
if (supply == 0) {
lastRewardBlock = block.number;
return;
}
// mint some new cigarette rewards to be distributed
uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock;
_mint(address(this), cigReward);
accCigPerShare = accCigPerShare + (
cigReward * 1e12 / supply
);
lastRewardBlock = block.number;
}
/**
* @dev pendingCig displays the amount of cig to be claimed
* @param _user the address to report
*/
function pendingCig(address _user) view public returns (uint256) {
uint256 _acps = accCigPerShare;
// accumulated cig per share
UserInfo storage user = farmers[_user];
uint256 supply = stakedlpSupply();
if (block.number > lastRewardBlock && supply != 0) {
uint256 cigReward = (block.number - lastRewardBlock) * cigPerBlock;
_acps = _acps + (
cigReward * 1e12 / supply
);
}
return (user.deposit * _acps / 1e12) - user.rewardDebt;
}
/**
* @dev userInfo is added for compatibility with the Snapshot.org interface.
*/
function userInfo(uint256, address _user) view external returns (uint256, uint256 depositAmount) {
return (0,farmers[_user].deposit + farmersMasterchef[_user].deposit);
}
/**
* @dev deposit deposits LP tokens to be staked.
* @param _amount the amount of LP tokens to deposit. Assumes this contract has been approved for the _amount.
*/
function deposit(uint256 _amount) external {
require(_amount != 0, "You cannot deposit only 0 tokens"); // Check how many bytes
UserInfo storage user = farmers[msg.sender];
update();
_deposit(user, _amount);
require(lpToken.transferFrom(
address(msg.sender),
address(this),
_amount
));
emit Deposit(msg.sender, _amount);
}
function _deposit(UserInfo storage _user, uint256 _amount) internal {
_user.deposit += _amount;
_user.rewardDebt += _amount * accCigPerShare / 1e12;
}
/**
* @dev withdraw takes out the LP tokens
* @param _amount the amount to withdraw
*/
function withdraw(uint256 _amount) external {
UserInfo storage user = farmers[msg.sender];
update();
/* harvest beforehand, so _withdraw can safely decrement their reward count */
_harvest(user, msg.sender);
_withdraw(user, _amount);
/* Interact */
require(lpToken.transferFrom(
address(this),
address(msg.sender),
_amount
));
emit Withdraw(msg.sender, _amount);
}
/**
* @dev Internal withdraw, updates internal accounting after withdrawing LP
* @param _amount to subtract
*/
function _withdraw(UserInfo storage _user, uint256 _amount) internal {
require(_user.deposit >= _amount, "Balance is too low");
_user.deposit -= _amount;
uint256 _rewardAmount = _amount * accCigPerShare / 1e12;
_user.rewardDebt -= _rewardAmount;
}
/**
* @dev harvest redeems pending rewards & updates state
*/
function harvest() external {
UserInfo storage user = farmers[msg.sender];
update();
_harvest(user, msg.sender);
}
/**
* @dev Internal harvest
* @param _to the amount to harvest
*/
function _harvest(UserInfo storage _user, address _to) internal {
uint256 potentialValue = (_user.deposit * accCigPerShare / 1e12);
uint256 delta = potentialValue - _user.rewardDebt;
safeSendPayout(_to, delta);
// Recalculate their reward debt now that we've given them their reward
_user.rewardDebt = _user.deposit * accCigPerShare / 1e12;
emit Harvest(msg.sender, _to, delta);
}
/**
* @dev safeSendPayout, just in case if rounding error causes pool to not have enough CIGs.
* @param _to recipient address
* @param _amount the value to send
*/
function safeSendPayout(address _to, uint256 _amount) internal {
uint256 cigBal = balanceOf[address(this)];
require(cigBal >= _amount, "insert more tobacco leaves...");
unchecked {
balanceOf[address(this)] = balanceOf[address(this)] - _amount;
balanceOf[_to] = balanceOf[_to] + _amount;
}
emit Transfer(address(this), _to, _amount);
}
/**
* @dev emergencyWithdraw does a withdraw without caring about rewards. EMERGENCY ONLY.
*/
function emergencyWithdraw() external {
UserInfo storage user = farmers[msg.sender];
uint256 amount = user.deposit;
user.deposit = 0;
user.rewardDebt = 0;
// Interact
require(lpToken.transfer(
address(msg.sender),
amount
));
emit EmergencyWithdraw(msg.sender, amount);
}
/*
* 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Migration 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬
*/
/**
* @dev renounceOwnership burns the admin key, so this contract is unruggable
*/
function renounceOwnership() external onlyAdmin {
admin = address(0);
}
/**
* @dev setStartingBlock sets the starting block for LP staking rewards
* Admin only, used only for initial configuration.
* @param _startBlock the block to start rewards for
*/
function setStartingBlock(uint256 _startBlock) external onlyAdmin {
lastRewardBlock = _startBlock;
}
/**
* @dev setPool address to an LP pool. Only Admin. (used only in testing/deployment)
*/
function setPool(ILiquidityPoolERC20 _addr) external onlyAdmin {
require(address(lpToken) == address(0), "pool already set");
lpToken = _addr;
}
/**
* @dev setReward sets the reward. Admin only (used only in testing/deployment)
*/
function setReward(uint256 _value) public onlyAdmin {
cigPerBlock = _value;
}
/**
* @dev migrationComplete completes the migration
*/
function migrationComplete() external {
require (CEO_state == 3);
require (OC.CEO_state() == 1);
require (block.number > lastRewardBlock, "cannot end migration yet");
CEO_state = 1; // CEO is in charge state
OC.burnTax(); // before copy, burn the old CEO's tax
/* copy the state over to this contract */
_mint(address(punks), OC.balanceOf(address(punks))); // CIG to be set aside for the remaining airdrop
uint256 taxDeposit = OC.CEO_tax_balance();
The_CEO = OC.The_CEO(); // copy the CEO
if (taxDeposit > 0) { // copy the CEO's outstanding tax
_mint(address(this), taxDeposit); // mint tax that CEO had locked in previous contract (cannot be migrated)
CEO_tax_balance = taxDeposit;
}
taxBurnBlock = OC.taxBurnBlock();
CEO_price = OC.CEO_price();
graffiti = OC.graffiti();
CEO_punk_index = OC.CEO_punk_index();
cigPerBlock = STARTING_REWARDS; // set special rewards
lastRewardBlock = OC.lastRewardBlock();// start rewards
rewardsChangedBlock = OC.rewardsChangedBlock();
/* Historical records */
_transferNFT(
address(0),
address(0x1e32a859d69dde58d03820F8f138C99B688D132F)
);
emit NewCEO(
address(0x1e32a859d69dde58d03820F8f138C99B688D132F),
0x00000000000000000000000000000000000000000000000000000000000015c9,
0x000000000000000000000000000000000000000000007618fa42aac317900000,
0x41732043454f2049206465636c617265204465632032322050756e6b20446179
);
_transferNFT(
address(0x1e32a859d69dde58d03820F8f138C99B688D132F),
address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d)
);
emit NewCEO(
address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d),
0x0000000000000000000000000000000000000000000000000000000000000343,
0x00000000000000000000000000000000000000000001a784379d99db42000000,
0x40617a756d615f626974636f696e000000000000000000000000000000000000
);
_transferNFT(
address(0x72014B4EEdee216E47786C4Ab27Cc6344589950d),
address(0x4947DA4bEF9D79bc84bD584E6c12BfFa32D1bEc8)
);
emit NewCEO(
address(0x4947DA4bEF9D79bc84bD584E6c12BfFa32D1bEc8),
0x00000000000000000000000000000000000000000000000000000000000007fa,
0x00000000000000000000000000000000000000000014adf4b7320334b9000000,
0x46697273742070756e6b7320746f6b656e000000000000000000000000000000
);
}
/**
* @dev wrap wraps old CIG and issues new CIG 1:1
* @param _value how much old cig to wrap
*/
function wrap(uint256 _value) external {
require (CEO_state == 3);
OC.transferFrom(msg.sender, address(this), _value); // transfer old cig to here
_mint(msg.sender, _value); // give user new cig
wBal[msg.sender] = wBal[msg.sender] + _value; // record increase of wrapped old cig for caller
}
/**
* @dev unwrap unwraps old CIG and burns new CIG 1:1
*/
function unwrap(uint256 _value) external {
require (CEO_state == 3);
_burn(msg.sender, _value); // burn new cig
OC.transfer(msg.sender, _value); // give back old cig
wBal[msg.sender] = wBal[msg.sender] - _value; // record decrease of wrapped old cig for caller
}
/*
* 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 ERC20 Token stuff 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬
*/
/**
* @dev burn some tokens
* @param _from The address to burn from
* @param _amount The amount to burn
*/
function _burn(address _from, uint256 _amount) internal {
balanceOf[_from] = balanceOf[_from] - _amount;
totalSupply = totalSupply - _amount;
emit Transfer(_from, address(0), _amount);
}
/**
* @dev mint new tokens
* @param _to The address to mint to.
* @param _amount The amount to be minted.
*/
function _mint(address _to, uint256 _amount) internal {
require(_to != address(0), "ERC20: mint to the zero address");
unchecked {
totalSupply = totalSupply + _amount;
balanceOf[_to] = balanceOf[_to] + _amount;
}
emit Transfer(address(0), _to, _amount);
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
//require(_value <= balanceOf[msg.sender], "value exceeds balance"); // SafeMath already checks this
balanceOf[msg.sender] = balanceOf[msg.sender] - _value;
balanceOf[_to] = balanceOf[_to] + _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
uint256 a = allowance[_from][msg.sender]; // read allowance
//require(_value <= balanceOf[_from], "value exceeds balance"); // SafeMath already checks this
if (a != type(uint256).max) { // not infinite approval
require(_value <= a, "not approved");
unchecked {
allowance[_from][msg.sender] = a - _value;
}
}
balanceOf[_from] = balanceOf[_from] - _value;
balanceOf[_to] = balanceOf[_to] + _value;
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve tokens of mount _value to be spent by _spender
* @param _spender address The spender
* @param _value the stipend to spend
*/
function approve(address _spender, uint256 _value) external returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/*
* 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 Masterchef v2 integration 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬
*/
/**
* @dev onSushiReward implements the SushiSwap masterchefV2 callback, guarded by the onlyMCV2 modifier
* @param _user address called on behalf of
* @param _to address who send rewards to
* @param _sushiAmount uint256, if not 0 then the rewards will be harvested
* @param _newLpAmount uint256, amount of LP tokens staked at Sushi
*/
function onSushiReward (
uint256 /* pid */,
address _user,
address _to,
uint256 _sushiAmount,
uint256 _newLpAmount) external onlyMCV2 {
UserInfo storage user = farmersMasterchef[_user];
update();
// Harvest sushi when there is sushiAmount passed through as this only comes in the event of the masterchef contract harvesting
if(_sushiAmount != 0) _harvest(user, _to); // send outstanding CIG to _to
uint256 delta;
// Withdraw stake
if(user.deposit >= _newLpAmount) { // Delta is withdraw
delta = user.deposit - _newLpAmount;
masterchefDeposits -= delta; // subtract from staked total
_withdraw(user, delta);
emit ChefWithdraw(_user, delta);
}
// Deposit stake
else if(user.deposit != _newLpAmount) { // Delta is deposit
delta = _newLpAmount - user.deposit;
masterchefDeposits += delta; // add to staked total
_deposit(user, delta);
emit ChefDeposit(_user, delta);
}
}
// onlyMCV2 ensures only the MasterChefV2 contract can call this
modifier onlyMCV2 {
require(
msg.sender == MASTERCHEF_V2,
"Only MCV2"
);
_;
}
}
/*
* 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬 interfaces 🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬🚬
*/
/**
* @dev IRouterV2 is the sushi router 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F
*/
interface IRouterV2 {
function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) external pure returns(uint256 amountOut);
}
/**
* @dev ICryptoPunk used to query the cryptopunks contract to verify the owner
*/
interface ICryptoPunk {
//function balanceOf(address account) external view returns (uint256);
function punkIndexToAddress(uint256 punkIndex) external returns (address);
//function punksOfferedForSale(uint256 punkIndex) external returns (bool, uint256, address, uint256, address);
//function buyPunk(uint punkIndex) external payable;
//function transferPunk(address to, uint punkIndex) external;
}
interface ICEOERC721 {
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
}
/*
* @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
* 0xTycoon was here
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev from UniswapV2Pair.sol
*/
interface ILiquidityPoolERC20 is IERC20 {
function getReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast);
function totalSupply() external view returns(uint);
}
interface IOldCigtoken is IERC20 {
function claims(uint256) external view returns (bool);
function graffiti() external view returns (bytes32);
function cigPerBlock() external view returns (uint256);
function The_CEO() external view returns (address);
function CEO_punk_index() external view returns (uint);
function CEO_price() external view returns (uint256);
function CEO_state() external view returns (uint256);
function CEO_tax_balance() external view returns (uint256);
function taxBurnBlock() external view returns (uint256);
function lastRewardBlock() external view returns (uint256);
function rewardsChangedBlock() external view returns (uint256);
function userInfo(address) external view returns (uint256, uint256);
function burnTax() external;
}
// 🚬
|
* @dev depositTax pre-pays tax for the existing CEO. It may also burn any tax debt the CEO may have. @param _amount amount of tax to pre-pay/
|
function depositTax(uint256 _amount) external onlyCEO {
require (CEO_state == 1, "no CEO");
if (_amount > 0) {
emit TaxDeposit(msg.sender, _amount);
}
if (taxBurnBlock != block.number) {
taxBurnBlock = block.number;
}
}
| 1,072,951 |
[
1,
323,
1724,
7731,
675,
17,
84,
8271,
5320,
364,
326,
2062,
29538,
51,
18,
2597,
2026,
2546,
18305,
1281,
5320,
18202,
88,
326,
29538,
51,
2026,
1240,
18,
225,
389,
8949,
3844,
434,
5320,
358,
675,
17,
10239,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
443,
1724,
7731,
12,
11890,
5034,
389,
8949,
13,
3903,
1338,
1441,
51,
288,
203,
3639,
2583,
261,
1441,
51,
67,
2019,
422,
404,
16,
315,
2135,
29538,
51,
8863,
203,
3639,
309,
261,
67,
8949,
405,
374,
13,
288,
203,
5411,
3626,
18240,
758,
1724,
12,
3576,
18,
15330,
16,
389,
8949,
1769,
203,
3639,
289,
203,
3639,
309,
261,
8066,
38,
321,
1768,
480,
1203,
18,
2696,
13,
288,
203,
5411,
5320,
38,
321,
1768,
273,
1203,
18,
2696,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x784839d6AbBa28d0f2bF29e426E407f709C475D6/sources/ExchangeV3.sol
|
@dev Clone an exchange without any initialization @return cloneAddress The address of the new exchange.
|
{
address origin = address(this);
cloneAddress = Cloneable.clone(origin);
assert(cloneAddress != origin);
assert(cloneAddress != address(0));
}
| 3,540,398 |
[
1,
10930,
392,
7829,
2887,
1281,
10313,
327,
225,
3236,
1887,
1021,
1758,
434,
326,
394,
7829,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
288,
203,
3639,
1758,
4026,
273,
1758,
12,
2211,
1769,
203,
3639,
3236,
1887,
273,
12758,
429,
18,
14056,
12,
10012,
1769,
203,
203,
3639,
1815,
12,
14056,
1887,
480,
4026,
1769,
203,
3639,
1815,
12,
14056,
1887,
480,
1758,
12,
20,
10019,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
/**
* @title FrAactionSPDAO
* @author Quentin for FrAaction Gangs
*/
// ============ Internal Import ============
import {
ISettings
} from "./GovSettings.sol";
// ============ External Imports: Inherited Contracts ============
// NOTE: we inherit from OpenZeppelin upgradeable contracts because of the proxy implementation of this logic contract
import {
IERC721Upgradeable
} from "@OpenZeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import {
ERC721HolderUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import {
ERC1155HolderUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol";
import {
IERC1155Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
import {
IERC20Upgradeable
} from "@OpenZeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {
ERC20Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {
ERC20lib
} from "./interfaces/ERC20lib.sol";
import {
DiamondInterface
} from "./DiamondInterface.sol";
contract FraactionSPDAO is ERC20Upgradeable, ERC721HolderUpgradeable, ERC1155HolderUpgradeable {
using Address for address;
// ============ Enums ============
// State Transitions:
// (1) INACTIVE on deploy, finalizeBid() or finalizePurchase()
// (2) ACTIVE on startPurchase(), startFundraising() or startBid()
// (2) FUNDING on confirmFunding()
// (3) SUBMITTED on purchase() or submitBid()
// (4) COMPLETED or FAILED on finalizeBid() or finalizePurchase()
enum fundingStatus {
INACTIVE,
ACTIVE,
FUNDING,
SUBMITTED,
COMPLETED,
FAILED
}
// funding round status of the FrAactionHub
FundingStatus public fundingStatus;
// State Transitions:
// (1) INACTIVE claim()
// (2) ACTIVE on startFinalAuction()
// (3) ENDED on endFinalAuction()
// (4) BURNING on Claim()
enum FinalAuctionStatus {
INACTIVE,
ACTIVE,
ENDED,
BURNING
}
FinalAuctionStatus public finalAuctionStatus;
// State Transitions:
// (1) INACTIVE on deploy
// (2) ACTIVE on initiateMerger() and voteForMerger(), ASSETSTRANSFERRED on voteForMerger()
// (3) MERGED or POSTMERGERLOCKED on finalizeMerger()
enum MergerStatus {
INACTIVE,
ACTIVE,
ASSETSTRANSFERRED,
MERGED,
POSTMERGERLOCKED
}
MergerStatus public mergerStatus;
// State Transitions:
// (1) INACTIVE or INITIALIZED on deploy
// (2) ACTIVE on voteForDemerger()
// (4) ASSETSTRANSFERRED on DemergeAssets()
// (4) DEMERGED on finalizeDemerger()
enum DemergerStatus {
INACTIVE,
ACTIVE,
INITIALIZED,
ASSETSTRANSFERRED,
DEMERGED
}
DemergerStatus public demergerStatus;
// State Transitions:
// (1) INACTIVE on deploy
// (2) FUNDING on startAavegotchiFunding()
// (3) CLAIMED on claimAavegotchi()
// (4) COMPLETED, FRACTIONALIZED and FAILED on finalizeAavegotchi()
enum PortalFundingStatus {
INACTIVE,
FUNDING,
CLAIMED,
COMPLETED,
FRACTIONALIZED,
FAILED
}
PortalFundingStatus public portalStatus;
// ============ Public Constant ============
// version of the FrAactionHub smart contract
uint256 public constant contractVersion = 1;
// ============ Internal Constants ============
// tokens are minted at a rate of 1 GHST : 100 tokens
uint16 internal constant TOKEN_SCALE = 100;
// max integer in hexadecimal format
uint256 internal constant MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// ============ Internal Mutable Storage ============
// previous FrAactionHub token balance of the receiver
uint256 internal beforeTransferToBalance;
// stake amount to be decreased in GHST to be burnt
uint256 internal decreasedGhst;
// stake amount to be decreased
uint256 internal decreasedStake;
// last index of the skill points set array of votedSkill mapping
uint256 internal skillIndex;
// current number of times the changeFraactionType() function reached the minimum quorum and voted
uint256 internal typeNumber;
// current number of times the updateAuctionLength() function reached the minimum quorum and voted
uint256 internal lengthNumber;
// current number of times the updatePlayerFee() function reached the minimum quorum and voted
uint256 internal feeNumber;
// current number of times the voteForPlayer() function reached the minimum quorum and voted
uint256 internal playerNumber;
// number of iterations currently done in order to run through the whole ownerAddress array
uint256 internal splitCounter;
// number of iterations necessary in order to run through the whole ownerAddress array
uint256 internal multiple;
// number of this item type owned by the FrAactionHub before the purchase
uint256 internal initialNumberOfItems;
// number of the new funding round
uint256 internal fundingNumber;
// 0 = no split ongoing, 1 = split going on for the realms transfer, 2 = same for the NFTs transfer, 3 = same for the items transfer, 4 = same for owner addresses transfer
uint256 internal split;
// voter's address => current votes submitted for the FrAactionHub type change
mapping(address => uint256) internal currentTypeBalance;
// voter's address => current auction length voted by the owner
mapping(address => uint256) internal currentLengthVote;
// voter's address => current votes submitted for the auction length update
mapping(address => uint256) internal currentLengthBalance;
// voter's address => current player's fee voted by the owner
mapping(address => uint256) internal currentFeeVote;
// voter's address => current votes submitted for the player's fee update
mapping(address => uint256) internal currentFeeBalance;
// voter's address => current player voted by the owner
mapping(address => uint256) internal currentPlayerVote;
// voter's address => current votes submitted for the player appointment
mapping(address => uint256) internal currentPlayerBalance;
// voter's address => typeNumber of the last time the owner voted
mapping(address => uint256) internal typeCurrentNumber;
// voter's address => feeNumber of the last time the owner voted
mapping(address => uint256) internal feeCurrentNumber;
// voter's address => lengthNumber of the last time the owner voted
mapping(address => uint256) internal lengthCurrentNumber;
// voter's address => current number of times the voteForPlayer() function reached the minimum quorum and voted
mapping(address => uint256) internal playerCurrentNumber;
// mergerTarget address => current number of times the voteForMerger() function reached the minimum quorum and voted
mapping(address => uint256) internal mergerNumber;
// contributor address => current number of times the contributor paid the gas fees on behalf of all the FrAactionHub owners
mapping(address => uint256) internal feesContributor;
// contributor => Aavegotchi funding round number
mapping(address => uint256[]) internal fundingContributor;
// contributor => tokenId(s) concerned by a stake increase
mapping(address => uint256[]) internal stakeContributor;
// tokenId => current number of times the voteForName() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal nameNumber;
// tokenId => current number of times the voteForSkills() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal skillNumber;
// tokenId => current number of times the voteForDestruction() function reached the minimum quorum and voted
mapping(uint256 => uint256) internal destroyNumber;
// portal Id => portal funding round number
mapping(uint256 => uint256) internal portalFundingNumber;
// contributor => last funding index iterated during the last newClaim() call
mapping(uint256 => uint256) internal lastFundingContributorIndex;
// contributor => last portal index iterated during the last newClaim() call
mapping(uint256 => uint256) internal lastPortalContributorIndex;
// tokenId => each portal option already voted by at least one owner
mapping(uint256 => uint256[]) internal votedAavegotchi;
// portal Id => Aavegotchi funding round number
mapping(uint256 => uint256[]) internal contributorPortalFunding;
// tokenId => each skill points set already voted by at least one owner
mapping(uint256 => uint256[4][]) internal votedSkill;
// tokenId => each name already voted by at least one owner
mapping(uint256 => string[]) internal votedName;
// tokenId => true if new funding round is successful
mapping(uint256 => bool) internal fundingResult;
// portal Id => funding round number => true if success of the Aavegotchi portal funding round
mapping(uint256 => mapping(uint256 => bool) internal portalFundingResult;
// voter's address => tokenId => current Aavegotchi option voted by the owner
mapping(address => mapping(uint256 => uint256)) internal currentAavegotchiVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi appointment
mapping(address => mapping(uint256 => uint256)) internal currentAavegotchiBalance;
// voter's address => tokenId => current Aavegotchi skill points set voted by the owner
mapping(address => mapping(uint256 => uint256)) internal currentSkillVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi skill points
mapping(address => mapping(uint256 => uint256)) internal currentSkillBalance;
// voter's address => tokenId => current Aavegotchi name voted by the owner
mapping(address => mapping(uint256 => string)) internal currentNameVote;
// voter's address => tokenId => current votes submitted by the owner for the Aavegotchi name appointment
mapping(address => mapping(uint256 => uint256)) internal currentNameBalance;
// voter's address => tokenId => current votes from the contributor for the Aavegotchi destruction
mapping(address => mapping(uint256 => uint256)) internal currentDestroyBalance;
// voter's address => tokenId => nameNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal nameCurrentNumber;
// voter's address => tokenId => skillNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal skillCurrentNumber;
// voter's address => tokenId => destroyNumber of the last time the owner voted
mapping(address => mapping(uint256 => uint256)) internal destroyCurrentNumber;
// contributor => tokenId => total amount contributed to the funding round
mapping(address => mapping(uint256 => uint256)) internal ownerContributedToFunding;
// voter's address => mergerTarget address => mergerNumber of the last time the owner voted
mapping(address => mapping(address => uint256)) internal mergerCurrentNumber;
// contributor => Aavegotchi funding round portals
mapping(address => uint256[]) internal portalContributor;
// contributor => tokenId => each collateral stake contribution for the considered Aavegotchi
mapping(address => mapping(uint256 => stakeContribution[])) internal ownerStakeContribution;
// contributor => portal Id => portal funding round => contributed collateral
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerContributedCollateral;
// contributor => portal Id => portal funding round => contributed collateral type
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerCollateralType;
// contributor => portal Id => portal funding round => contributed ghst
mapping(address => mapping(uint256 => mapping(uint256 => uint256))) internal ownerContributedToAavegotchiFunding;
// ============ Public Not-Mutated Storage ============
// ERC-20 name for fractional tokens
string public name;
// ERC-20 symbol for fractional tokens
string public symbol;
// Address of the Aavegotchi Diamond contract
address public constant diamondContract;
// Address of the GHST contract
address public constant ghstContract;
// Address of the staking contract
address public constant stakingContract;
// Address of the REALMs contract
address public constant realmsContract;
// Address of the Raffles contract
address public constant rafflesContract;
// Address of the wrapped MATIC contract
address public constant wrappedMaticContract;
// Address of the FrAaction Gangs settings Contract
address public constant settingsContract = ;
// address of the parent FrAactionHub
address public demergeFrom;
// ============ Public Mutable Storage ============
// the governance contract which gets paid in ETH
address public settingsContract;
// FrAactionDAOMultisig address
address public fraactionDaoMultisig;
// FrAactionHall address
address public fraactionHall;
// target of the initial bid
address public fraactionHubTarget;
// contributor for the current staking decrease or increase;
address public stakingContributor;
// the current user winning the token auction
address public winning;
// the Player of the fractionalized Aavegotchi
address public player;
// addresses of all the FrAactionHub owners
address[] public ownersAddress;
// fee rewarded to the Player
uint256 public playerFee;
// the last timestamp when fees were claimed
uint256 public lastClaimed;
// the number of ownership tokens voting on the reserve price at any given time
uint256 public votingTokens;
// total GHST deposited by all contributors
uint256 public totalContributedToFraactionHub;
// Price in wei of the listed item targetted by the current funding round
uint256 public priceInWei;
// quantity of items to be acquired from the baazaar by the new funding round
uint256 public quantity;
// total votes for the election of the player
uint256 public votesTotalPlayer;
// total votes for the player fee update
uint256 public votesTotalFee;
// total votes for the auction length update
uint256 public votesTotalLength;
// total votes for the FrAactionHub type update
uint256 public votesTotalType;
// total GHST deposited by all contributors for the funding round
uint256 public totalContributedToFunding;
// last initial bid price submitted to the target FrAactionHub
uint256 public submittedBid;
// Number of assets acquired by the FrAactionHub
uint256 public numberOfAssets;
// Id of the portal to be claimed by the FrAactionHub
uint256 public portalTarget;
// option number of the appointed Aavegotchi to be claimed by the FrAactionHub
uint256 public portalOption;
// the unix timestamp end time of the token auction
uint256 public auctionEnd;
// the length of auctions
uint256 public auctionLength;
// reservePrice * votingTokens
uint256 public reserveTotal;
// the current price of the token during the final auction
uint256 public livePrice;
// listingId of the current funding round target
uint256 public listingId;
// Number of the FrAactionHub owners
uint256 public numberOfOwners;
// new funding round initial time
uint256 public fundingTime;
// Aavegotchi funding round initial time
uint256 public aavegotchiFundingTime;
// maximum collateral contribution allowed for the Aavegotchi funding
uint256 public maxContribution;
// collateral type of the appointed Aavegotchi
uint256 public collateralType;
// current collateral balance of the targeted Aavegotchi for the stake increase or decrease
uint256 public collateralBalance;
// current tokenId of the targeted Aavegotchi for the stake increase or decrease
uint256 public stakingTarget;
// array of the proposed auction lengths for the vote
uint256[] public votedLength;
// array of the proposed player fees for the vote
uint256[] public votedFee;
// 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
bool public gameType;
// true if the new funding round is targetting an NFT
bool public isNft;
// true if there is currently at least one destroyed Aavegotchi tokens to be claimed
bool public destroyed;
// true if all the funding rounds contributors claimed their tokens
bool public allClaimed;
// true if the first FrAactionHub funding round is currently active
bool public firstRound;
// true if the FrAactionHub successfully fractionalized its first NFT or item
bool public initialized;
// proposed auction length => collected votes in favor of that auction length
mapping (uint256 => uint256) public votesLength;
// proposed player's fee => collected votes in favor of that player's fee
mapping (uint256 => uint256) public votesFee;
// portal tokenId => appointed Aavegotchi
mapping (uint256 => uint256) public aavegotchi;
// tokenId => total votes for the Aavegotchi destruction
mapping (uint256 => uint256) public votesTotalDestroy;
// tokenId => total votes for the Aavegotchi
mapping (uint256 => uint256) public votesTotalAavegotchi;
// tokenId => total votes for the Aavegotchi name
mapping (uint256 => uint256) public votesTotalName;
// tokenId => total votes for the Aavegotchi skill points allocation
mapping (uint256 => uint256) public votesTotalSkill;
// tokenId => total votes collected to open this closed portal
mapping(uint256 => uint256) public votesTotalOpen;
// tokenId => index of asset
mapping(uint256 => uint256) public tokenIdToAssetIndex;
// portal Id => total contributed for the Aavegotchi portal funding
mapping(uint256 => uint256) public totalContributedToAavegotchiFunding;
// tokenId => winning Aavegotchi name
mapping (uint256 => string) public name;
// FrAactionHub owner => votes he collected to become the appointed Player
mapping(address => uint256) public votesPlayer;
// contributor => total amount contributed to the FrAactionHub
mapping(address => uint256) public ownerTotalContributed;
// contributor => array of Contributions
mapping(address => Contribution[]) public contributions;
// FrAactionHub owner => his desired token price
mapping(address => uint256) public userPrices;
// FrAactionHub owner => return True if owner already voted for the appointed player
mapping(address => bool) public votersPlayer;
// FrAactionHub owner => return True if owner already voted for the new Player's fee
mapping(address => bool) public votersFee;
// FrAactionHub owner => return True if owner already voted for the new auction length
mapping(address => bool) public votersLength;
// FrAactionHub owner => return True if owner already voted for the new FrAactionHub type
mapping(address => bool) public votersType;
// FrAactionHub owner => return True if owner already voted for the Aavegotchi
mapping(address => bool) public votersAavegotchi;
// contributor => true if the contributor already claimed its tokens from the funding round
mapping(address => bool) public claimed;
// tokenId => true if there is currently a vote for allocating skill points
mapping(uint256 => bool) public skillVoting;
// owner => tokenId => true if alredy voted, false if not
mapping(address => mapping(uint256 => bool)) public votersOpen;
// contributor => tokenId => true if contributor already voted for that Aavegotchi destruction
mapping(address => mapping(uint256 => bool)) public votersDestroy;
// contributor => tokenId => true if contributor already voted for that Aavegotchi
mapping(address => mapping(uint256 => bool)) public votersAavegotchi;
// owner => tokenId => current votes for opening the portal
mapping(address => mapping(uint256 => uint256)) public currentOpenBalance;
// contributor => tokenId => total staking contribution for the considered Aavegotchi
mapping(address => mapping(uint256 => uint256)) public ownerTotalStakeAmount;
// tokenId => portal option => current votes for this portal option
mapping(uint256 => mapping(uint256 => uint256)) public votesAavegotchi;
// tokenId => skill points set => current votes for this skill points set
mapping(uint256 => mapping(uint256 => uint256)) public votesSkill;
// tokenId => Aavegotchi name => current votes for this name
mapping(uint256 => mapping(string => uint256)) public votesName;
// Array of Assets acquired by the FrAactionHub
Asset[] public assets;
// ============ Structs ============
struct Contribution {
uint256 amount;
uint256 previousTotalContributedToFraactionHub;
}
// ============ EVENTS ============
// an event emitted when a user updates their price
event PriceUpdate(
address indexed user,
uint price
);
// an event emitted when an auction starts
event Start(
address indexed buyer,
uint price
);
// an event emitted when a bid is made
event Bid(
ddress indexed buyer,
uint price
);
// an event emitted when an auction is won
event Won(
address indexed buyer,
uint price
);
// an event emitted when someone cashes in ERC20 tokens for ETH from an ERC721 token sale
event Cash(
address indexed owner,
uint256 shares
);
// an event emitted when the assets merger is finalized
event AssetsMerged(address indexed _mergerTarget);
// an event emitted when the merger is finalized
event MergerFinalized(address indexed _mergerTarget);
// an event emitted when the demerger is done
event Demerged(address indexed proxyAddress, string name, string symbol);
// an event emitted when the Player is appointed or changed
event AppointedPlayer(address indexed appointedPlayer);
// an event emitted when the auction length is changed
event UpdateAuctionLength(uint256 indexed newLength);
// an event emitted when the Player fee is changed
event UpdatePlayerFee(uint256 indexed newFee);
// an event emitted when the FrAaction type is changed
event UpdateFraactionType(string indexed newGameType);
// an event emitted when somebody redeemed all the FrAactionHub tokens
event Redeem(address indexed redeemer);
// an event emitted when an Aavegotchi is appointed to be summoned
event AppointedAavegotchi(uint256 indexed portalTokenId, uint256 appointedAavegotchiOption);
// an event emitted when a portal is open
event OpenPortal(uint256 indexed portalId);
// an event emitted when an Aavegotchi is destroyed
event Destroy(uint256 indexed tokenId);
// an event emitted when an Aavegotchi name is chosen
event Named(uint256 indexed tokenId, string name);
// an event emitted when an Aavegotchi skill points set is submitted
event SkilledUp(uint256 indexed tokenId, uint256 tokenId);
// an event emitted when wearables are equipped on an Aavegotchi
event Equipped(uint256 indexed tokenId, uint16[16] wearables);
// an event emitted when consumables are used on one or several Aavegotchis
event ConsumablesUsed(uint256 indexed tokenId, uint256[] itemIds, uint256[] quantities);
function initializeVault(uint256 _supply, uint256 _listPrice, string memory _name, string memory _symbol) internal initializer {
// initialize inherited contracts
__ERC20_init(_name, _symbol);
reserveTotal = _listPrice * _supply;
lastClaimed = block.timestamp;
votingTokens = _listPrice == 0 ? 0 : _supply;
_mint(address(this), _supply);
userPrices[address(this)] = _listPrice;
initialized = true;
}
// ============ VIEW FUNCTIONS ============
function getOwners() public view returns (address[] memory) {
return ownersAddress;
}
/// @notice provide the current reserve price of the FrAactionHub
function reservePrice() public view returns(uint256) {
return votingTokens == 0 ? 0 : reserveTotal / votingTokens;
}
/// @notice provide the current reserve price of the FrAactionHub
function fundingPrice() public view returns(uint256) {
return votingTokens == 0 ? 0 : fundingTotal / votingTokens;
}
/// @notice inform if the bid is open (return true) or not (return false)
function openForBidOrMerger() public view returns(bool) {
return votingTokens * 1000 >= ISettings(settings).minVotePercentage() * totalSupply() ? true : false;
}
/// @notice inform if the bid is open (return true) or not (return false)
function activeBid() public view returns(bool) {
return finalAuctionStatus != FinalAuctionStatus.INACTIVE ? true : false;
}
/// @notice provide minimum amount to bid during the auction
function minBid() public view returns(uint256) {
uint256 increase = ISettings(settingsContract).minBidIncrease() + 1000;
return livePrice * increase / 1000;
}
// ========= GOV FUNCTIONS =========
/// @notice allow governance to boot a bad actor Player
/// @param _Player the new Player
function kickPlayer(address _player) external {
require(
msg.sender == ISettings(settingsContract).owner(),
"kick: not gov"
);
player = _player;
}
/// @notice allow governance to remove bad reserve prices
function removeReserve(address _user) external {
require(
msg.sender == ISettings(settingsContract).owner(),
"remove: not gov"
);
require(
auctionStatus == AuctionsStatus.INACTIVE,
"remove: auction live cannot update price"
);
uint256 old = userPrices[_user];
require(
0 != old,
"remove: not an update"
);
uint256 weight = balanceOf(_user);
votingTokens -= weight;
reserveTotal -= weight * old;
userPrices[_user] = 0;
emit PriceUpdate(_user, 0);
}
// ============ SETTINGS & FEES FUNCTIONS ============
/// @notice allow the FrAactionHub owners to change the FrAactionHub type
function changeFraactionType() external {
require(
initialized == true,
"updateFraactionType: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updateFraactionType: user not an owner of the FrAactionHub"
);
require(
gangAddress != address(0),
"updateFraactionType: cannot change the Collective type if the FraactionHub is part of a gang"
);
if (typeNumber != typeCurrentNumber[msg.sender]) {
votersType[msg.sender] = 0;
currentTypeBalance[msg.sender] = 0;
}
if (votersType[msg.sender] == true) {
votesTotalType -= currentTypeBalance[msg.sender];
} else {
votersType[msg.sender] = true;
}
votesTotalType += balanceOf(msg.sender);
currentTypeBalance[msg.sender] = balanceOf(msg.sender);
if (typeNumber != typeCurrentNumber[msg.sender]) typeCurrentNumber[msg.sender] = typeNumber;
if (votesTotalType * 1000 >= ISettings(settingsContract).minTypeVotePercentage() * totalSupply()) {
// 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
if (gameType == 0) gameType = 1;
if (gameType == 1) gameType = 0;
emit UpdateFraactionType(gameType);
typeNumber++;
votesTotalType = 0;
}
}
/// @notice allow the FrAactionHub owners to update the auction length
/// @param _length the new maximum length of the auction
function updateAuctionLength(uint256 _length) external {
require(
initialized == true,
"updateAuctionLength: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updateAuctionLength: user not an owner of the FrAactionHub"
);
require(
_length >= ISettings(settingsContract).minAuctionLength() && _length <= ISettings(settings).maxAuctionLength(),
"updateAuctionLength: invalid auction length"
);
if (lengthNumber != lengthCurrentNumber[msg.sender]) {
votersLength[msg.sender] = 0;
currentLengthVote[msg.sender] = 0;
currentLengthBalance[msg.sender] = 0;
}
if (votersLength[msg.sender] == true) {
votesLength[currentLengthVote[msg.sender]] -= currentLengthBalance[msg.sender];
votesTotalLength -= currentLengthBalance[msg.sender];
} else {
votersLength[msg.sender] = true;
}
if (votesLength[_length] == 0) votedLength.push(_length);
votesLength[_length] += balanceOf(msg.sender);
votesTotalLength += balanceOf(msg.sender);
currentLengthVote[msg.sender] = _length;
currentLengthBalance[msg.sender] = balanceOf(msg.sender);
if (lengthNumber != lengthCurrentNumber[msg.sender]) lengthCurrentNumber[msg.sender] = lengthNumber;
uint256 winner;
uint256 result;
if (votesTotalLength * 1000 >= ISettings(settingsContract).minLengthVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedLength.length; i++) {
if (votesLength[votedLength[i]] > result) {
result = votesLength[votedLength[i]];
winner = votedLength[i];
}
votesLength[votedLength[i]] = 0;
}
auctionLength = winner;
delete votedLength;
emit UpdateAuctionLength(auctionLength);
lengthNumber++;
votesTotalLength = 0;
}
}
/// @notice allow the FrAactionHub owners to change the player fee
/// @param _fee the new fee
function updatePlayerFee(uint256 _playerFee) external {
require(
gameType == 0,
"updatePlayerFee: this FrAactionHub was set as Collective by its creator"
);
require(
_playerFee <= ISettings(settingsContract).maxPlayerFee(),
"updatePlayerFee: cannot increase fee this high"
);
require(
initialized == true,
"updatePlayerFee: FrAactionHub not initialized yet"
);
require(
balanceOf(msg.sender) > 0,
"updatePlayerFee: user not an owner of the FrAactionHub"
);
if (feeNumber != feeCurrentNumber[msg.sender]) {
votersFee[msg.sender] = 0;
currentFeeVote[msg.sender] = 0;
currentFeeBalance[msg.sender] = 0;
}
if (votersFee[msg.sender] == true) {
votesFee[currentFeeVote[msg.sender]] -= currentFeeBalance[msg.sender];
votesTotalFee -= currentFeeBalance[msg.sender];
} else {
votersFee[msg.sender] = true;
}
if (votesFee[_playerFee] == 0) votedFee.push(_playerFee);
votesFee[_playerFee] += balanceOf(msg.sender);
votesTotalFee += balanceOf(msg.sender);
currentFeeVote[msg.sender] = _playerFee;
currentFeeBalance[msg.sender] = balanceOf(msg.sender);
if (feeNumber != feeCurrentNumber[msg.sender]) feeCurrentNumber[msg.sender] = feeNumber;
if (votesTotalFee * 1000 >= ISettings(settingsContract).minPlayerFeeVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedFee.length; i++) {
if (votesFee[votedFee[i]] > result) {
result = votesFee[votedFee[i]];
winner = votedFee[i];
}
votesFee[votedFee[i]] = 0;
}
playerFee = winner;
delete votedFee;
emit UpdatePlayerFee(playerFee);
feeNumber++;
votesTotalFee = 0;
}
}
// ========= CORE FUNCTIONS ============
function voteForTransfer(
uint256[] calldata _nftsId,
uint256[] calldata _extNftsId,
uint256[] calldata _ext1155Id,
uint256[] calldata _realmsId,
uint256[] calldata _itemsId,
uint256[] calldata _itemsQuantity,
uint256[] calldata _extErc20Value,
uint256[] calldata _ext1155Quantity,
uint256[7] calldata _ticketsQuantity,
address[] calldata _extErc20Address,
address[] calldata _extNftsAddress,
address[] calldata _ext1155Address,
uint256 _idToVoteFor,
address _transferTo
) external nonReentrant {
require(
demergerStatus == DemergerStatus.INACTIVE,
"voteForTransfer: transfer already active"
);
require(
balanceOf(msg.sender) > 0,
"voteForTransfer: caller not an owner of the FrAactionHub"
);
require(
_itemsId.length == _itemsQuantity.length &&
_extNftsId.length == _extNftsAddress.length &&
_ext1155Id.length == _ext1155Address.length &&
_ext1155Address.length == _ext1155Quantity.length &&,
"voteForTransfer: input arrays lengths are not matching"
);
require(
_nftsId.length +
_realmsId.length +
_itemsId.length +
_itemsQuantity.length +
_ticketsQuantity.length +
_extNftsId.length +
_extNftsAddress.length +
_ext1155Id.length +
_ext1155Quantity.length +
_ext1155Address.length +
=< ISettings(settingsContract).MaxTransferLimit(),
"voteForTransfer: cannot transfer more than the GovSettings allowed limit"
);
if (_nftsId.length > 0 ||
_realmsId.length > 0 ||
_itemsId.length > 0 ||
_ticketsId.length > 0 ||
_extNftsId.length > 0 ||
_ext1155Id.length > 0
) {
require(
_idToVoteFor == votedIndex,
"voteForTransfer: user submitting a new demerger has to vote for it"
);
require(
_transferTo != address(0),
"voteForTransfer: address to transfer to cannot be zero"
);
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
votedIndex++;
transferTo[_idToVoteFor] = _transferTo;
}
if (votersTransfer[msg.sender][_idToVoteFor] == true) {
if (balanceOf(msg.sender) != currentTransferBalance[msg.sender][_idToVoteFor])
votesTotalTransfer[_idToVoteFor] -= currentTransferBalance[msg.sender][_idToVoteFor];
} else {
votersTransfer[msg.sender][_idToVoteFor] = true;
}
if (balanceOf(msg.sender) != currentTransferBalance[msg.sender][_idToVoteFor]) {
votesTotalTransfer[_idToVoteFor] += balanceOf(msg.sender);
currentTransferBalance[msg.sender][_idToVoteFor] = balanceOf(msg.sender);
}
if (votesTotalTransfer[_idToVoteFor] * 1000 >= ISettings(settingsContract).minTransferVotePercentage() * totalSupply()) {
if (demergerStatus != DemergerStatus.ACTIVE) {
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
demergerStatus = DemergerStatus.ACTIVE;
votedIndex = _idToVoteFor;
target = transferTo[_idToVoteFor];
emit TransferActive(target);
}
if (!realmsTransferred || split = 1) {
transferRealms();
if (split == 0) realmsTransferred = true;
} else if (!nftsTransferred || split = 2) {
transferNfts();
if (split == 0) nftsTransferred = true;
} else if (!itemsTransferred || split = 3) {
transferItems();
if (split == 0) itemsTransferred = true;
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
demergerStatus = DemergerStatus.INACTIVE;
realmsTransferred = false;
nftsTransferred = false;
itemsTransferred = false;
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
DemergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
}
}
function confirmFinalizedMerger() external {
require(
msg.sender == target,
"confirmFinalizedMerger: sender is not the merger target"
);
require(
mergerStatus == MergerStatus.ACTIVE,
"confirmFinalizedMerger: merger not active"
);
delete initiatedMergerFrom[target];
delete votesTotalMerger[target];
delete targetReserveTotal[target];
delete proposedMergerTo[target];
delete proposedValuation;
delete proposedValuationFrom;
if (!takeover) {
if (erc20Tokens.length + nfts.length + erc1155Tokens.length > maxExtTokensLength) {
mergerStatus = MergerStatus.DELETINGTOKENS;
} else {
delete erc20Tokens;
delete nfts;
delete erc1155Tokens;
mergerStatus = MergerStatus.ENDED;
}
}
}
function initiateMergerFrom(uint256 _proposedValuation, bool _proposedTakeover) external {
require(
ISettings(settingsContract).fraactionHubRegistry(msg.sender) > 0,
"initiateMergerFrom: not a registered FrAactionHub contract"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"initiateMergerFrom: caller not an owner of the FrAactionHub"
);
initiatedMergerFrom[msg.sender] = true;
proposedValuationFrom[msg.sender] = _proposedValuation;
proposedTakeoverFrom[msg.sender] = _proposedTakeover;
timeMerger[msg.sender] = block.timestamp;
endMerger[msg.sender] = timeMerger[msg.sender] + ISettings(settingsContract).minMergerTime();
emit MergerProposed(msg.sender, _proposedValuation, _proposedTakeover);
}
function confirmMerger() external {
require(
msg.sender == target,
"confirmMerger: caller not the merger target"
);
merging = true;
emit confirmedMerger(msg.sender);
}
function confirmAssetsTransferred() external {
require(
msg.sender == target,
"confirmAssetsTransferred caller not the merger target"
);
mergerStatus = MergerStatus.ASSETSTRANSFERRED;
emit MergerAssetsTransferred(msg.sender);
}
function initiateMergerTo(uint256 _proposedValuation, bool _proposedTakeover) external {
require(
ISettings(settingsContract).fraactionHubRegistry(msg.sender) > 0,
"initiateMergerTo: not a registered FrAactionHub contract"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"initiateMergerTo: caller not an owner of the FrAactionHub"
);
proposedMergerFrom[msg.sender] = true;
proposedValuationFrom[msg.sender] = _proposedValuation;
proposedTakeoverFrom[msg.sender] = _proposedTakeover;
timeMerger[msg.sender] = block.timestamp;
endMerger[msg.sender] = timeMerger[msg.sender] + ISettings(settingsContract).minMergerTime();
emit MergerProposedTo(msg.sender, _proposedValuation, _proposedTakeover);
}
function voteForMerger(
bool _proposeMergerTo,
bool _proposeTakeover,
uint256 _proposeValuation,
address _mergerTarget
) external nonReentrant {
require(
fundingStatus == FundingStatus.INACTIVE,
"voteForMerger: FrAactionHub not fractionalized yet"
);
require(
ISettings(settingsContract).fraactionHubRegistry(_mergerTarget) > 0,
"voteForMerger: not a registered FrAactionHub contract"
);
require(
balanceOf(msg.sender) > 0 ||
FraactionInterface(target).balanceOf(msg.sender) > 0,
"voteForMerger: user not an owner of the FrAactionHub"
);
require(
_extNftsId.length == _extNftsAddress.length &&
_extErc20Address.length == _extErc20Value.length &&
_ext1155Id.length == _ext1155Quantity.length &&
_ext1155Quantity.length == _ext1155Address.length,
"voteForMerger: each token ID or value needs a corresponding token address"
);
if (merging == false) {
if (timeMerger[_mergerTarget] > mergerEnd[_mergerTarget]) {
timeMerger[_mergerTarget] = 0;
mergerEnd[_mergerTarget] = 0;
if (initiatedMergerFrom[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
delete initiatiedMergerFrom[_mergerTarget];
} else if (proposedMergerTo[_mergerTarget] && mergerStatus == MergerStatus.ACTIVE) {
mergerStatus = MergerStatus.INACTIVE;
delete proposedMergerTo[_mergerTarget];
} else if (proposedMergerFrom[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
delete proposedMergerFrom[_mergerTarget];
} else {
delete initiatedMergerTo[_mergerTarget];
mergerStatus = MergerStatus.INACTIVE;
}
delete targetReserveTotal[_mergerTarget];
delete votesTotalMerger[_mergerTarget];
return;
}
if (_proposeMergerTo) proposedMergerTo[_mergerTarget] = true;
if (targetReserveTotal[_mergerTarget] == 0) {
require(
FraactionInterface(_mergerTarget).openForBidOrMerger(),
"voteForMerger: FrAactionHub not open for Merger or Bid"
);
if (!proposedMergerFrom[_mergetTarget] && !initiatedMergerFrom[_mergetTarget]) proposedTakeover[_mergerTarget] = _proposeTakeover;
if (_proposeValuation == 0 && !proposedValuationFrom[_mergerTarget]
|| proposedValuationFrom[_mergerTarget]
) {
targetReserveTotal[_mergerTarget] = FraactionInterface(_mergerTarget).reserveTotal();
} else {
targetReserveTotal[_mergerTarget] = _proposeValuation;
proposedValuation[_mergerTarget] = true;
}
bool checkType = FraactionInterface(_mergerTarget).checkExitTokenType();
if (exitInGhst == checkType) sameReserveCurrency[_mergerTarget] = checkType;
}
if (votersMerger[msg.sender][_mergerTarget] == true) {
if (balanceOf(msg.sender) != currentMergerBalance[msg.sender][_mergerTarget])
votesTotalMerger[_mergerTarget] -= currentMergerBalance[msg.sender][_mergerTarget];
} else {
votersMerger[msg.sender][_mergerTarget] = true;
}
if (balanceOf(msg.sender) != currentMergerBalance[msg.sender][_mergerTarget]) {
votesTotalMerger[_mergerTarget] += balanceOf(msg.sender);
currentMergerBalance[msg.sender][_mergerTarget] = balanceOf(msg.sender);
}
}
if (votesTotalMerger[_mergerTarget] * 1000 >= ISettings(settingsContract).minMergerVotePercentage() * totalSupply()) {
if (initiatedMergerFrom[_mergerTarget] == true) {
if (!proposedMergerTo[_mergerTarget] && mergerStatus == MergerStatus.INACTIVE) {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
merging = true;
FraactionInterface(target).confirmMerger();
emit MergerInitiated(_mergerTarget);
}
uint256[] memory realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
uint32[] memory nftsId = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
ItemIdIO[] memory itemsDiamond = DiamondInterface(diamondContract).itemBalances(address(this));
uint256[] memory itemsStaking = DiamondInterface(stakingContract).balanceOfAll(address(this));
bool checkTickets;
for (uint i = 0; i < itemsStaking.length; i++) {
if (itemsStaking[i] != 0) {
checkTickets = true;
break;
}
}
if (realmsId.length > 0 && split == 0 || split == 1) {
transferRealms();
} else if (nftsId.length > 0 && split == 0 || split == 2) {
transferNfts();
} else if (
itemsDiamond.length > 0 && split == 0 ||
split == 3 ||
checkTickets == true
)
{
transferItems();
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
if (totalTreasuryInGhst > 0) ERC20lib.transferFrom(ghstContract, address(this), target, totalTreasuryInGhst);
if (totalTreasuryInMatic > 0) transferMaticOrWmatic(target, totalTreasuryInMatic);
totalTreasuryInGhst = 0;
totalTreasuryInMatic = 0;
uint256 bal = ERC20Upgradeable(ghstContract).balanceOf(address(this));
residualGhst = bal - currentBalanceInGhst;
residualMatic = address(this).balance - currentBalanceInMatic;
if (exitInGhst) {
redeemedCollateral[ghstContract].push(residualGhst);
if (collateralToRedeem[ghstContract] == 0) {
collateralToRedeem[ghstContract] = true;
collateralAvailable.push(ghstContract);
}
} else {
redeemedCollateral[thisContract].push(residualMatic);
if (collateralToRedeem[thisContract] == 0) {
collateralToRedeem[thisContract] = true;
collateralAvailable.push(thisContract);
}
}
mergerStatus == MergerStatus.ASSETSTRANSFERRED;
totalNumberExtAssets = nonTransferredAssets;
nonTransferredAssets = 0;
FraactionInterface(target).confirmAssetsTransferred();
emit MergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
} else if (proposedMergerTo[_mergerTarget]) {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
timeMerger[target] = block.timestamp;
endMerger[target] = timeMerger[target] + ISettings(settingsContract).minMergerTime();
merging = true;
if (proposedValuation[target]) {
FraactionInterface(target).initiateMergerTo(targetReserveTotal[target], proposedTakeover[target]);
} else {
FraactionInterface(target).initiateMergerTo(, proposedTakeover[target]);
}
emit MergerInitiatedTo(target);
} else {
target = _mergerTarget;
mergerStatus = MergerStatus.ACTIVE;
uint256 takeover = proposedTakeover[target] ? true : proposedTakeoverFrom[target];
if (proposedValuation[target]) {
FraactionInterface(target).initiateMergerFrom(targetReserveTotal[target], takeover);
} else {
FraactionInterface(target).initiateMergerFrom(, takeover);
}
timeMerger[target] = block.timestamp;
endMerger[target] = timeMerger[target] + ISettings(settingsContract).minMergerTime();
delete votesTotalMerger[_mergerTarget];
emit MergerInitiated(target);
}
}
}
function finalizeMerger() external nonReentrant {
require(
mergerStatus == MergerStatus.ASSETSTRANSFERRED,
"finalizeMerger: items not transferred yet"
);
require(
balanceOf(msg.sender) > 0 ||
FraactionInterface(target).balanceOf(msg.sender) > 0,
"finalizeMerger: user not an owner of the FrAactionHub"
);
address[] memory ownersFrom = FraactionInterface(target).getOwners();
uint256 startIndex = 0;
uint256 endIndex = ownersFrom.length;
if (split == 0) {
maxOwnersArrayLength = ISettings(settingsContract).maxOwnersArrayLength();
uint256 agreedReserveTotal;
uint256 agreedReserveTotalFrom;
if (proposedValuationFrom[target]) {
agreedReserveTotalFrom = targetReserveTotal[target];
agreedReserveTotal = proposedValuationFrom[target];
} else {
agreedReserveTotalFrom = targetReserveTotal[target];
agreedReserveTotal = FraactionInterface(target).targetReserveTotal(address(this));
}
if (sameReserveCurrency[target]) {
newShareFrom = totalSupply() * agreedReserveTotalFrom / agreedReserveTotal;
} else {
if (exitInGhst) {
newShareFrom = totalSupply() * (agreedReserveTotalFrom * (ISettings(settingsContract).convertFundingPrice(1) / 10**8)) / agreedReserveTotal;
} else {
newShareFrom = totalSupply() * (agreedReserveTotalFrom * (ISettings(settingsContract).convertFundingPrice(0) / 10**8)) / agreedReserveTotal;
}
}
if (ownersFrom.length > maxOwnersArrayLength) {
if (ownersFrom.length % maxOwnersArrayLength > 0) {
multiple = ownersFrom.length / maxOwnersArrayLength + 1;
} else {
multiple = ownersFrom.length / maxOwnersArrayLength;
}
split = 7;
splitCounter++;
}
endIndex = maxOwnersArrayLength;
} else {
if (ownersFrom.length % maxOwnersArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = ownersFrom.length;
} else {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = (splitCounter + 1) * maxOwnersArrayLength;
}
splitCounter++;
}
bool existing;
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
merging = false;
totalTreasuryInGhst += FraactionInterface(target).totalTreasuryInGhst();
totalTreasuryInMatic += FraactionInterface(target).totalTreasuryInMatic();
FraactionInterface(target).confirmFinalizedMerger();
delete initiatedMergerTo[target];
delete proposedMergerFrom[target];
delete targetReserveTotal[target];
delete proposedTakeoverFrom;
delete proposedValuation;
delete proposedValuationFrom;
mergerStatus = MergerStatus.INACTIVE;
emit MergerFinalized(target);
}
if (endIndex > ownersFrom.length) endIndex = ownersFrom.length;
if (startIndex > ownersFrom.length) return;
uint256 tokenSupplyFrom = FraactionInterface(target).totalSupply();
for (uint i = startIndex; i < endIndex; i++) {
for (uint j = 0; j < ownersAddress.length; j++) {
if (ownersFrom[i] == ownersAddress[j]) {
existing = true;
}
}
if (existing == false) ownersAddress.push(ownersFrom[i]);
mint(
ownersFrom[i],
newShareFrom * FraactionInterface(target).balanceOf(ownersFrom[i]) / tokenSupplyFrom
);
}
claimReward(msg.sender);
}
function transferRealms() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedRealms[votedIndexRealms[votedIndex].length;
} else {
arrayLength = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this)).length;
}
uint256[] memory realmsId = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
realmsId = votedRealms[votedIndexRealms[votedIndex]];
} else {
realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
}
uint256 startIndex;
uint256 endIndex = realmsId.length;
if (split == 0) {
maxRealmsArrayLength = ISettings(settingsContract).maxRealmsArrayLength();
if (realmsId.length > maxRealmsArrayLength) {
endIndex = maxRealmsArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (realmsId.length % maxRealmsArrayLength > 0) {
multiple = realmsId.length / maxRealmsArrayLength + 1;
} else {
multiple = realmsId.length / maxRealmsArrayLength;
}
split = 1;
splitCounter++;
}
}
} else {
if (realmsId.length % maxRealmsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxRealmsArrayLength + 1;
endIndex = realmsId.length;
} else {
startIndex = splitCounter * maxRealmsArrayLength + 1;
endIndex = (splitCounter + 1) * maxRealmsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredRealms(transferTo);
}
if (_endIndex > realmsId.length) _endIndex = realmsId.length;
if (_startIndex > realmsId.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
for (uint i = _startIndex; i < _endIndex; i++) {
batchIds[i] = realmsId[i];
}
RealmsInterface(realmsContract).safeBatchTransfer(address(this), target, batchIds, new bytes(0));
}
function transferNfts() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedNfts[votedIndexNfts[votedIndex].length;
} else {
arrayLength = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this)).length;
}
uint256[] memory nftsIds = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
nftIds = votedNfts[votedIndexNfts[votedIndex]];
} else {
nftIds = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
}
uint256 startIndex;
uint256 endIndex = nftsIds.length;
if (split == 0) {
maxNftArrayLength = ISettings(settingsContract).maxNftArrayLength();
if (nftIds.length > maxNftArrayLength) {
endIndex = maxNftArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (nftIds.length % maxNftArrayLength > 0) {
multiple = nftIds.length / maxNftArrayLength + 1;
} else {
multiple = nftIds.length / maxNftArrayLength;
}
split = 2;
splitCounter++;
}
}
} else {
if (nftIds.length % maxNftArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxNftArrayLength + 1;
endIndex = nftIds.length;
} else {
startIndex = splitCounter * maxNftArrayLength + 1;
endIndex = (splitCounter + 1) * maxNftArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredNfts(target);
}
if (endIndex > nftIds.length) endIndex = nftIds.length;
if (startIndex > nftIds.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
for (uint i = startIndex; i < endIndex; i++) {
batchIds[i] = nftIds[i];
}
DiamondInterface(diamondContract).safeBatchTransferFrom(address(this), target, batchIds, new bytes(0));
}
function transferItems() internal {
require(
msg.sender == target,
"transferItems: caller not approved"
);
require(
mergerStatus == MergerStatus.ACTIVE ||
demergerStatus == DemergerStatus.ACTIVE,
"transferItems: merger, transfer or demerger not active"
);
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedItemsDemerger[votedIndexItems[votedIndex]].length;
} else {
ItemIdIO[] memory items = DiamondInterface(diamondContract).itemBalances(this.address);
arrayLength = items.length;
}
ItemIdIO[] memory items = new ItemIdIO[](arrayLength);
uint256[] memory ids = new uint256[](arrayLength);
uint256[] memory quantities = new uint256[](arrayLength);
uint256 startIndex;
uint256 endIndex = arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
ids = votedItems[votedIndexItems[votedIndex]];
quantities = votedItemsQuantity[votedIndexItemsQuantity[votedIndex]];
endIndex = ids.length;
} else {
items = DiamondInterface(diamondContract).itemBalances(this.address);
endIndex = items.length;
}
if (split == 0) {
maxItemsArrayLength = ISettings(settingsContract).maxItemsArrayLength();
if (arrayLength > maxItemsArrayLength) {
endIndex = maxItemsArrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
if (arrayLength % maxItemsArrayLength > 0) {
multiple = arrayLength / maxItemsArrayLength + 1;
} else {
multiple = arrayLength / maxItemsArrayLength;
}
split = 3;
splitCounter++;
}
}
{
bool exist;
uint256[] memory idsTickets = new uint256[](7);
uint256[] memory quantityTickets = new uint256[](7);
if (demergerStatus == DemergerStatus.ACTIVE) {
quantityTickets = votedTicketsQuantity[votedIndexTicketsQuantity[votedIndex]];
} else {
quantityTickets = DiamondInterface(stakingContract).balanceOfAll(this.address);
}
for (uint i = 0; i < idsTickets.length; i++) {
idsTickets[i] = i;
if (exist == false) {
if (quantityTickets[i] > 0) exist = true;
}
}
if (exist == true) {
IERC1155Upgradeable(stakingContract).safeBatchTransferFrom(address(this), target, idsTickets, quantityTickets, new bytes(0));
}
}
} else {
if (ids.length % maxItemsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxItemsArrayLength + 1;
endIndex = ids.length;
} else {
startIndex = splitCounter * maxItemsArrayLength + 1;
endIndex = (splitCounter + 1) * maxItemsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredItems(target);
}
if (endIndex > ids.length) endIndex = ids.length;
if (startIndex > ids.length) return;
uint256[] memory batchIds = new uint256[](endIndex - startIndex + 1);
uint256[] memory batchQuantities = new uint256[](endIndex - startIndex + 1);
for (uint i = startIndex; i < endIndex; i++) {
if (mergerStatus = MergerStatus.ACTIVE) {
batchIds[i] = items[i].itemId;
batchQuantities[i] = items[i].balance;
} else {
batchIds[i] = ids[i];
batchQuantities[i] = quantities[i];
}
}
IERC1155Upgradeable(stakingContract).safeBatchTransferFrom(address(this), target, batchIds, batchQuantities, new bytes(0));
}
function transferExternalErc20() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExtErc20[votedIndexExtErc20[votedIndex]].length;
} else {
arrayLength = erc20Tokens.length;
}
uint256[] memory erc20Address = new uint256[](arrayLength);
uint256[] memory erc20Value = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
erc20Value = votedExtErc20Value[votedIndexExtErc20[votedIndex]];
erc20Address = votedExtErc20Address[votedIndexExtErc20Address[votedIndex]];
} else {
for (uint i = 0; i < erc20Tokens.length; i++) {
erc20Value = ownedErc20[erc20Tokens[i]];
}
erc20Address = erc20Tokens;
}
uint256 startIndex;
uint256 endIndex = erc20Value.length;
if (split == 0) {
maxExtErc20ArrayLength = ISettings(settingsContract).maxExtErc20ArrayLength();
if (erc20Value.length > maxExtErc20ArrayLength) {
endIndex = maxExtErc20ArrayLength;
if (erc20Value.length % maxExtErc20ArrayLength > 0) {
multiple = erc20Value.length / maxExtErc20ArrayLength + 1;
} else {
multiple = erc20Value.length / maxExtErc20ArrayLength;
}
split = 6;
splitCounter++;
}
} else {
if (erc20Value.length % maxExtErc20ArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtErc20ArrayLength + 1;
endIndex = erc20Value.length;
} else {
startIndex = splitCounter * maxExtErc20ArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtErc20ArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExtErc20(target);
}
if (endIndex > erc20Value.length) endIndex = erc20Value.length;
if (startIndex > erc20Value.length) return;
uint256 assetCounter;
address replace;
for (uint i = startIndex; i < endIndex; i++) {
try LibERC20.transferFrom(erc20Address[i], addresse(this), target, erc20Value[i]) {
ownedErc20[erc20Address[i]] -= erc20Value[i];
if (ownedErc20[erc20Address[i]] == 0 && demergerStatus == DemergerStatus.ACTIVE) {
replace = erc20Tokens[erc20Tokens.length - 1];
erc20Tokens[erc20Index[erc20Address[i]]] = replace;
erc20Index[replace] = erc20Index[erc20Address[i]];
delete erc20Index[erc20Address[i]];
erc20Tokens.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete erc20Index[erc20Address[i]];
} catch {
nonTransferredAssets++;
emit NonTransferredErc20(erc20Address[i], erc20Value[i]);
}
}
if (mergerStatus == MergerStatus.ACTIVE) extAssetsTansferred += assetCounter;
}
function transferExternalNfts() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExtNfts[votedIndexExtNfts[votedIndex].length;
} else {
arrayLength = nfts.length;
}
uint256[] memory nftsAddress = new uint256[](arrayLength);
uint256[] memory nftsId = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
nftsId = votedExtNfts[votedIndexExtNfts[votedIndex]];
nftsAddress = votedExtNftsAddress[votedIndexExtAddress[votedIndex]];
} else {
for (uint i = 0; i < nfts.length; i++) {
nftsId = nfts[i].id;
}
nftsAddress = nfts;
}
uint256 startIndex;
uint256 endIndex = nftsId.length;
if (split == 0) {
maxExtNftArrayLength = ISettings(settingsContract).maxExtNftArrayLength();
if (nftsId.length > maxExtNftArrayLength) {
endIndex = maxExtNftArrayLength;
if (nftsId.length % maxExtNftArrayLength > 0) {
multiple = nftsId.length / maxExtNftArrayLength + 1;
} else {
multiple = nftsId.length / maxExtNftArrayLength;
}
split = 4;
splitCounter++;
}
} else {
if (nftsId.length % maxExtNftArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtNftArrayLength + 1;
endIndex = nftsId.length;
} else {
startIndex = splitCounter * maxExtNftArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtNftArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExtNfts(target);
}
if (endIndex > nftsId.length) endIndex = nftsId.length;
if (startIndex > nftsId.length) return;
uint256 assetCounter;
address replace;
for (uint i = startIndex; i < endIndex; i++) {
try IERC721Upgradeable(nftsAddress[i]).safeTransferFrom(address(this), target, nftsId[i]) {
delete ownedNfts[nftAddress[i]][nftsId[i]];
if (demergerStatus == DemergerStatus.ACTIVE) {
replace = nfts[nfts.length - 1];
nfts[nftsIndex[nftsAddress[i]]] = replace;
nftsIndex[replace] = nftsIndex[nftsAddress[i]];
delete nftsIndex[nftsAddress[i]];
nfts.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete nftsIndex[nftsAddress[i]];
} catch {
nonTransferredAssets++;
emit NonTransferredNfts(nftsAddress[i], nftsId[i]);
}
}
}
function transferExternal1155() internal {
uint256 arrayLength;
if (demergerStatus == DemergerStatus.ACTIVE) {
arrayLength = votedExt1155Transfer[votedIndexExt1155[votedIndex]].length;
} else {
arrayLength = erc1155Tokens.length;
}
uint256[] memory ids1155 = new uint256[](arrayLength);
uint256[] memory quantity1155 = new uint256[](arrayLength);
address[] memory address1155 = new uint256[](arrayLength);
if (demergerStatus == DemergerStatus.ACTIVE) {
ids1155 = votedExt1155[votedIndexExt1155[votedIndex]];
quantity1155 = votedExt1155Quantity[votedIndexExt1155Quantity[votedIndex]];
address1155 = votedExt1155Address[votedIndexExt1155Address[votedIndex]];
} else {
for (uint i = 0; i < erc1155Tokens.length; i++) {
ids1155 = erc1155Tokens[i].id;
quantity1155 = erc1155Tokens[i].quantity;
}
address1155 = erc1155Tokens;
}
uint256 startIndex;
uint256 endIndex = ids1155.length;
if (split == 0) {
maxExt1155ArrayLength = ISettings(settingsContract).maxExt1155ArrayLength();
if (ids1155.length > maxExtItemsArrayLength) {
endIndex = maxExtItemsArrayLength;
if (ids1155.length % maxExtItemsArrayLength > 0) {
multiple = ids1155.length / maxExtItemsArrayLength + 1;
} else {
multiple = ids1155.length / maxExtItemsArrayLength;
}
split = 5;
splitCounter++;
}
} else {
if (ids1155.length % maxExtItemsArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxExtItemsArrayLength + 1;
endIndex = ids1155.length;
} else {
startIndex = splitCounter * maxExtItemsArrayLength + 1;
endIndex = (splitCounter + 1) * maxExtItemsArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
emit TransferredExt1155(target);
}
if (endIndex > ids1155.length) endIndex = ids1155.length;
if (startIndex > ids1155.length) return;
uint256 assetCounter;
for (uint i = startIndex; i < endIndex; i++) {
if (address1155[i] == address(0)) continue;
uint256 redundancyCounter;
redundancyCounter++;
address replace;
uint256[] memory indexRedundancy = new indexRedundancy[](endIndex - startIndex + 1);
for (uint j = i + 1; j < endIndex; j++) {
if (address1155[j] == address(0)) continue;
if (address1155[i] == address1155[j]) {
ownedErc1155[address1155[j]][ids1155[j]] -= quantity1155[j];
if (demergerStatus == DemergerStatus.ACTIVE && ownedErc1155[address1155[j]][ids1155[j]] == 0) {
erc1155Tokens[j] = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens.pop();
replace = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens[erc1155Index[address1155[i]]] = replace;
erc1155Index[replace] = erc1155Index[address1155[j]];
delete nftsIndex[address1155[j]];
erc1155Tokens.pop();
}
if (mergerStatus == MergerStatus.ACTIVE) delete erc1155Index[address1155[i]];
indexRedundancy[redundancyCounter] = j;
delete address1155[j];
redundancyCounter++;
}
uint256 indexCounter;
uint256[] memory batchIds = new uint256[](redundancyCounter);
uint256[] memory batchQuantity = new uint256[](redundancyCounter);
batchIds[indexCounter] = ids1155[i];
batchQuantity[indexCounter] = quantity1155[i];
indexCounter++;
for (uint k = 1; k < redundancyCounter; k++) {
batchIds[indexCounter] = ids1155[indexRedundancy[k]];
batchQuantity[indexCounter] = quantity1155[indexRedundancy[k]];
indexCounter++;
}
try IERC1155Upgradeable(address1155[i]).safeBatchTransferFrom(address(this), target, batchIds, batchQuantity, new bytes(0)) {
ownedErc1155[address1155[i]][ids1155[i]] -= quantity1155[i];
if (demergerStatus == DemergerStatus.ACTIVE && ownedErc1155[address1155[i]][ids1155[i]] == 0) {
erc1155Tokens[i] = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens.pop();
replace = erc1155Tokens[erc1155Tokens.length - 1];
erc1155Tokens[erc1155Index[address1155[i]]] = replace;
erc1155Index[replace] = erc1155Index[address1155[i]];
delete nftsIndex[address1155[i]];
erc1155Tokens.pop();
}
} catch {
nonTransferredAssets += redundancyCounter;
emit NonTransferredErc1155(address1155[i], batchIds, batchQuantity);
}
redundancyCounter = 0;
}
}
}
function voteForDemerger(
uint256[] calldata _nftsId,
uint256[] calldata _extNftsId,
uint256[] calldata _ext1155Id,
uint256[] calldata _realmsId,
uint256[] calldata _itemsId,
uint256[] calldata _itemsQuantity,
uint256[] calldata _extErc20Value,
uint256[] calldata _ext1155Quantity,
uint256[7] calldata _ticketsQuantity,
address[] calldata _extErc20Address,
address[] calldata _extNftsAddress,
address[] calldata _ext1155Address,
uint256 _idToVoteFor,
string calldata _name,
string calldata _symbol
) external nonReentrant {
require(
fundingStatus == FundingStatus.INACTIVE,
"voteForDemerger: FrAactionHub not fractionalized yet"
);
require(
balanceOf(msg.sender) > 0,
"voteForDemerger: user not an owner of the FrAactionHub"
);
require(
demergerStatus == DemergerStatus.INACTIVE,
"voteForDemerger: user not an owner of the FrAactionHub"
);
require(
mergerStatus == MergerStatus.INACTIVE,
"voteForDemerger: active merger"
);
require(
_itemsId.length == _itemsQuantity.length &&
_extNftsId.length == _extNftsAddress.length &&
_ext1155Id.length == _ext1155Address.length &&
_ext1155Address.length == _ext1155Quantity.length &&,
"voteForDemerger: input arrays lengths are not matching"
);
require(
_nftsId.length +
_realmsId.length +
_itemsId.length +
_itemsQuantity.length +
_ticketsQuantity.length +
_extNftsId.length +
_extNftsAddress.length +
_ext1155Id.length +
_ext1155Quantity.length +
_ext1155Address.length +
=< ISettings(settingsContract).MaxTransferLimit(),
"voteForDemerger: cannot transfer more than the GovSettings allowed limit"
);
if (_nftsId.length > 0 ||
_realmsId.length > 0 ||
_itemsId.length > 0 ||
_ticketsId.length > 0 ||
_extNftsId.length > 0 ||
_ext1155Id.length > 0
) {
require(
_idToVoteFor == votedIndex,
"voteFordemerger: user submitting a new demerger has to vote for it"
);
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
true
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
true
);
votedIndex++;
}
if (votersDemerger[msg.sender][_idToVoteFor] == true) {
if (balanceOf(msg.sender) != currentDemergerBalance[msg.sender][_idToVoteFor])
votesTotalDemerger[_idToVoteFor] -= currentDemergerBalance[msg.sender][_idToVoteFor];
} else {
votersDemerger[msg.sender][_idToVoteFor] = true;
}
if (_name != "" && _symbol != "") {
if (demergerName[_idToVoteFor] == "" && demergerSymbol[_idToVoteFor] == "") {
demergerName[_idToVoteFor] = _name;
demergerSymbol[_idToVoteFor] = _symbol;
}
}
if (balanceOf(msg.sender) != currentDemergerBalance[msg.sender][_idToVoteFor]) {
votesTotalDemerger[_idToVoteFor] += balanceOf(msg.sender);
currentDemergerBalance[msg.sender][_idToVoteFor] = balanceOf(msg.sender);
}
if (votesTotalDemerger[_idToVoteFor] * 1000 >= ISettings(settingsContract).minDemergerVotePercentage() * totalSupply()) {
ownershipCheck(
_nftsId,
_realmsId,
_itemsId,
_itemsQuantity,
_ticketsQuantity,
false
);
ownershipCheckExt(
_extNftsId,
_ext1155Id,
_extErc20Value,
_ext1155Quantity,
_extErc20Address,
_extNftsAddress,
_ext1155Address,
false
);
address fraactionFactoryContract = ISettings(settingsContract).fraactionFactoryContract();
(bool success, bytes memory returnData) =
fraactionFactoryContract.call(
abi.encodeWithSignature(
"startFraactionHub(
string,
string,
address
)",
demergerName[_idToVoteFor],
demergerSymbol[_idToVoteFor],
address(this)
)
);
require(
success,
string(
abi.encodePacked(
"voteForDemerger: mergerFrom order failed: ",
returnData
)
)
);
target = abi.decode(returnData, (address));
votedIndex = _idToVoteFor;
demergerStatus = DemergerStatus.ACTIVE;
emit DemergerActive(target, demergerName[_idToVoteFor], demergerSymbol[_idToVoteFor]);
claimReward(msg.sender);
}
}
function demergeTo() external nonReentrant {
require(
demergerStatus == DemergerStatus.ACTIVE,
"demergeTo: demerger not active"
);
if (!realmsTransferred || split = 1) {
transferRealms();
if (split == 0) realmsTransferred = true;
} else if (!nftsTransferred || split = 2) {
transferNfts();
if (split == 0) nftsTransferred = true;
} else if (!itemsTransferred || split = 3) {
transferItems();
if (split == 0) itemsTransferred = true;
} else if (!extNftsTransferred || split = 4) {
transferExternalNfts();
if (split == 0) extNftsTransferred = true;
} else if (!ext1155Transferred || split = 5) {
transferExternal1155();
if (split == 0) ext1155Transferred = true;
} else if (!extErc20Transferred || split = 6) {
transferExternalErc20();
if (split == 0) extErc20Transferred = true;
} else {
demergerStatus = DemergerStatus.INACTIVE;
FraactionInterface(target).confirmDemerger();
realmsTransferred = false;
nftsTransferred = false;
itemsTransferred = false;
extNftsTransferred = false;
ext1155Transferred = false;
extErc20Transferred = false;
DemergerAssetsTransferred(address(this));
}
claimReward(msg.sender);
}
function finalizeDemerger() external nonReentrant {
require(
demergerStatus == DemergerStatus.ASSETSTRANSFERRED,
"finalizeDemerger: demerger assets not transferred yet"
);
address[] memory ownersFrom = FraactionInterface(target).getOwners();
uint256 startIndex = 0;
uint256 endIndex = ownersFrom.length;
if (split == 0) {
maxOwnersArrayLength = ISettings(settingsContract).maxOwnersArrayLength();
if (ownersFrom.length > maxOwnersArrayLength) {
if (ownersFrom.length % maxOwnersArrayLength > 0) {
multiple = ownersFrom.length / maxOwnersArrayLength + 1;
} else {
multiple = ownersFrom.length / maxOwnersArrayLength;
}
split = 7;
splitCounter++;
}
endIndex = maxOwnersArrayLength;
} else {
if (ownersFrom.length % maxOwnersArrayLength > 0 && splitCounter == multiple - 1) {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = ownersFrom.length;
} else {
startIndex = splitCounter * maxOwnersArrayLength + 1;
endIndex = (splitCounter + 1) * maxOwnersArrayLength;
}
splitCounter++;
}
if (splitCounter == multiple) {
if (split > 0) {
split = 0;
splitCounter = 0;
multiple = 0;
}
demergerStatus = DemergerStatus.INACTIVE;
target = address(0);
emit DemergerFinalized(target);
}
if (endIndex > ownersFrom.length) endIndex = ownersFrom.length;
if (startIndex > ownersFrom.length) return;
bool existing;
for (uint i = startIndex; i < endIndex; i++) {
ownersAddress.push(ownersFrom[i]);
mint(
ownersFrom[i],
FraactionInterface(target).balanceOf(ownersFrom[i])
);
}
claimReward(msg.sender);
}
function confirmDemerger() external {
require(
msg.sender == target,
"confirmDemerger: caller is not the demerger parent contract"
);
require(
demergerStatus == DemergerStatus.ACTIVE,
"confirmDemerger: demerger is not active
);
demergerStatus = DemergerStatus.ASSETSTRANSFERRED;
DemergerAssetsTransferred(address(this));
}
function ownershipCheck(
uint256[] memory _nftsId,
uint256[] memory _realmsId,
uint256[] memory _itemsId,
uint256[] memory _itemsQuantity,
uint256[7] memory _ticketsQuantity,
bool _saveParams
) internal {
uint256 counterOwned;
if (_nftsId.length > 0) {
uint32[] memory nftsId = DiamondInterface(diamondContract).tokenIdsOfOwner(address(this));
for (uint i = 0; i < _nftsId.length; i++) {
for (uint j = 0; j < nftsId.length; j++) {
if (_nftsId[i] == nftsId[j]) {
counterOwned++;
break;
}
}
}
}
if (_realmsId.length > 0) {
uint32[] memory realmsId = DiamondInterface(realmsContract).tokenIdsOfOwner(address(this));
for (uint i = 0; i < _realmsId.length; i++) {
for (uint j = 0; j < realmsId.length; j++) {
if (_realmsId[i] == realmsId[j]) {
counterOwned++;
break;
}
}
}
}
if (_itemsId.length > 0) {
ItemIdIO[] memory balance = DiamondInterface(diamondContract).itemBalances(address(this));
for (uint i = 0; i < _itemsId.length; i++) {
require(
_itemsQuantity[i] > 0,
"ownershipCheck: invalid item quantity"
);
for (uint j = 0; j < balance.length; j++) {
if (_itemsId[i] == balance[j].itemId) {
require(
_itemsQuantity[i] <= balance[j].balance,
"ownershipCheck: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
break;
}
}
}
}
if (_ticketsQuantity.length > 0) {
bool check;
uint256[] memory ticketsCurrentQuantity = DiamondInterface(stakingContract).balanceOfAll(address(this));
for (uint i = 0; i < _ticketsQuantity.length; i++) {
if (_ticketsQuantity[i] == 0) check = true;
require(
_ticketsQuantity[i] <= ticketsCurrentQuantity[i],
"ownershipCheck: proposed tickets quantities have to be equal or inferior to the owned tickets quantities"
);
counterOwned++;
}
require(
!check,
"ownershipCheck: a ticket quantity has to be provided"
);
}
require(
counterOwned == _nftsId.length + _realmsId.length + _itemsId.length + _ticketsQuantity.length,
"ownershipCheck: one token or more is not owned by the FrAactionHub"
);
if (_saveParams) {
if (_nftsId.length > 0) {
votedIndexNfts[votedIndex] = votedNfts.length;
votedNfts.push(_nftsId);
}
if (_realmsId.length > 0) {
votedIndexRealms[votedIndex] = votedRealms.length;
votedRealms.push(_realmsId);
}
if (_itemsId.length > 0) {
votedIndexItems[votedIndex] = votedItems.length;
votedItems.push(_itemsId);
votedIndexItemsQuantity[votedIndex] = votedItemsQuantity.length;
votedItemsQuantity.push(_itemsQuantity);
}
if (_ticketsQuantity.length > 0) {
votedIndexTicketsQuantity[votedIndex] = votedTicketsQuantity.length;
votedTicketsQuantity.push(_ticketsQuantity);
}
}
}
function ownershipCheckExt(
uint256[] memory _extNftsId,
uint256[] memory _ext1155Id,
uint256[] memory _extErc20Value,
uint256[] memory _ext1155Quantity,
address[] memory _extErc20Address,
address[] memory _extNftsAddress,
address[] memory _ext1155Address,
bool _saveParams
) internal {
uint256 counterOwned;
if (_extNftsId.length > 0) {
for (uint i = 0; i < _extNftsId.length; i++) {
require(
_extNftsAddress[i] != address(0),
"ownershipCheckExt: invalid NFT address"
);
if (ownedNfts[_extNftsAddress[i]][_extNftsId[i]] == true) counterOwned++;
}
}
if (_extErc20Value.length > 0) {
for (uint i = 0; i < _extErc20Value.length; i++) {
require(
_extErc20Value[i] > 0 && _extErc20Address[i] != address(0),
"ownershipCheckExt: invalid item quantity or address"
);
require(
ownedErc20[_extErc20Address[i]] <= _extErc20Value[i],
"ownershipCheckExt: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
}
}
if (_ext1155Id.length > 0) {
for (uint i = 0; i < _ext1155Id.length; i++) {
require(
_ext1155Quantity[i] > 0 && _ext1155Address[i] != address(0),
"ownershipCheckExt: invalid item quantity or address"
);
require(
ownedErc1155[_ext1155Address[i]][_ext1155Id[i]] <= _ext1155Quantity[i],
"ownershipCheckExt: proposed item quantities have to be equal or inferior to the owned items quantities"
);
counterOwned++;
}
}
require(
counterOwned == _extErc20Value.length + _extNftsId.length + _ext1155Id.length,
"ownershipCheckExt: one token or more is not owned by the FrAactionHub"
);
}
if (_saveParams) {
if (_extErc20Value.length > 0) {
votedIndexExtErc20Value[votedIndex] = votedExtErc20Value.length;
votedExtErc20Value.push(_extErc20Value);
votedIndexExtErc20Address[votedIndex] = votedExtErc20Address.length;
votedExtErc20Address.push(_extErc20Address);
}
if (_extNftsId.length > 0) {
votedIndexExtNfts[votedIndex] = votedExtNfts.length;
votedExtNfts.push(_extNftsId);
votedIndexExtAddress[votedIndex] = votedExtAddress.length;
votedExtAddress.push(_extNftsAddress);
}
if (_ext1155Id.length > 0) {
votedIndexExt1155[votedIndex] = votedExt1155.length;
votedExt1155.push(_ext1155Id);
votedIndexExt1155Quantity[votedIndex] = votedExt1155Quantity.length;
votedExt1155Quantity.push(_ext1155Quantity);
votedIndexExt1155Address[votedIndex] = votedExt1155Address.length;
votedExt1155Address.push(_ext1155Address);
}
}
}
/// @notice a function for an end user to update their desired sale price
/// @param _new the desired price in GHST
function updateUserPrice(uint256 _new) external {
require(
balanceOf(msg.sender) > 0,
"updateUserPrice: user not an owner of the FrAactionHub"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"updatePrice: auction live cannot update price"
);
require(
initialized == true,
"updatePrice: FrAactionHub not fractionalized yet"
);
uint256 old = userPrices[msg.sender];
require(
_new != old,
"updatePrice:not an update"
);
uint256 weight = balanceOf(msg.sender);
if (votingTokens == 0) {
votingTokens = weight;
reserveTotal = weight * _new;
}
// they are the only one voting
else if (weight == votingTokens && old != 0) {
reserveTotal = weight * _new;
}
// previously they were not voting
else if (old == 0) {
uint256 averageReserve = reserveTotal / votingTokens;
uint256 reservePriceMin = averageReserve * ISettings(settingsContract).minReserveFactor() / 1000;
require(
_new >= reservePriceMin,
"updatePrice:reserve price too low"
);
uint256 reservePriceMax = averageReserve * ISettings(settingsContract).maxReserveFactor() / 1000;
require(
_new <= reservePriceMax,
"update:reserve price too high"
);
votingTokens += weight;
reserveTotal += weight * _new;
}
// they no longer want to vote
else if (_new == 0) {
votingTokens -= weight;
reserveTotal -= weight * old;
}
// they are updating their vote
else {
uint256 averageReserve = (reserveTotal - (old * weight)) / (votingTokens - weight);
uint256 reservePriceMin = averageReserve * ISettings(settingsContract).minReserveFactor() / 1000;
require(
_new >= reservePriceMin,
"updatePrice:reserve price too low"
);
uint256 reservePriceMax = averageReserve * ISettings(settingsContract).maxReserveFactor() / 1000;
require(
_new <= reservePriceMax,
"updatePrice:reserve price too high"
);
reserveTotal = reserveTotal + (weight * _new) - (weight * old);
}
userPrices[msg.sender] = _new;
emit PriceUpdate(msg.sender, _new);
}
/// @notice an external function to decrease an Aavegotchi staked collateral amount
function voteForStakeDecrease(uint256 _tokenId, uint256 _stakeAmount) external nonReentrant {
require(
balanceOf(msg.sender) > 0,
"VoteForStakeDecrease: user not an owner of the FrAactionHub"
);
require(
_stakeAmount < DiamondInterface(diamondContract).collateralBalance(_tokenId).balance_,
"VoteForStakeDecrease: stake amount greater than the total contributed amount"
);
require(
_stakeAmount > 0,
"VoteForStakeDecrease: staked amount must be greater than 0"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"VoteForStakeDecrease: an auction is live"
);
require(
_stakeAmount < DiamondInterface(diamondContract).getAavegotchi(_tokenId).minimumStake,
"VoteForStakeDecrease: amount has to be lower than the minimum stake"
);
if (decreaseNumber[_tokenId][_stakeAmount] != decreaseCurrentNumber[msg.sender][_tokenId][_stakeAmount]) {
votersDecrease[msg.sender][_tokenId][_stakeAmount] = 0;
currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount] = 0;
}
votesTotalDecrease[_tokenId][_stakeAmount] += balanceOf(msg.sender) - currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount];
currentDecreaseBalance[msg.sender][_tokenId][_stakeAmount] = balanceOf(msg.sender);
if (decreaseStaking[_tokenId][_stakeAmount] == 0) decreaseStaking[_tokenId][_stakeAmount] = _stakeAmount;
if (decreaseNumber != decreaseCurrentNumber[msg.sender]) decreaseCurrentNumber[msg.sender][_tokenId][_stakeAmount] = decreaseNumber;
if (votesTotalDecrease[_tokenId][_stakeAmount] * 1000 >= ISettings(settingsContract).minDecreaseVotePercentage() * totalSupply()) {
address collateral = DiamondInterface(diamondContract).collateralBalance(_tokenId).collateralType_;
(bool success, bytes memory returnData) =
diamondContract.call(
abi.encodeWithSignature("decreaseStake(uint256,uint256)",
_tokenId,
decreaseStaking[_tokenId]
)
);
require(
success,
string(
abi.encodePacked(
"VoteForStakeDecrease: staking order failed: ",
returnData
)
)
);
redeemedCollateral[collateral].push(decreaseStaking[_tokenId][_stakeAmount]);
if (collateralToRedeem[collateral] == 0) {
collateralToRedeem[collateral] = true;
collateralAvailable.push(collateral);
}
decreaseStaking[_tokenId][_stakeAmount] = 0;
emit StakeDecreased(
_tokenId,
decreaseStaking[_tokenId][_stakeAmount]
);
claimed[_contributor] = false;
if (allClaimed == true) allClaimed = false;
}
}
/// @notice a function to vote for opening an already purchased and closed portal
function voteForOpenPortal(uint256 _tokenId) external {
require(
initialized == true,
"voteForOpenPortal: cannot vote if an auction is ended"
);
require(
balanceOf(msg.sender) > 0,
"voteForOpenPortal: user not an owner of the NFT"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForOpenPortal: auction live cannot update price"
);
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 0,
"voteForOpenPortal: portal already open"
);
if (votersOpen[msg.sender][_tokenId] == true) {
votesTotalOpen[_tokenId] -= currentOpenBalance[msg.sender][_tokenId];
} else {
votersOpen[msg.sender][_tokenId] = true;
}
votesTotalOpen[_tokenId] += balanceOf(msg.sender);
currentOpenBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (votesTotalOpen[_tokenId] * 1000 >= ISettings(settingsContract).minOpenVotePercentage() * totalSupply()) {
DiamondInterface(diamondContract).openPortals(_tokenId);
emit OpenPortal(_tokenId);
assets[tokenIdToAssetIndex[_tokenId]].category = 1;
votesTotalOpen[_tokenId] = 0;
}
}
/// @notice vote for an Aavegotchi to be summoned
function voteForAavegotchi(uint256 _tokenId, uint256 _option) external {
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 2,
"voteForAavegotchi: portal not open yet or Aavegotchi already summoned"
);
require(_option < 10,
"voteForAavegotchi: only 10 options available"
);
require(balanceOf(msg.sender) > 0,
"voteForAavegotchi: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForAavegotchi: auction live cannot update price"
);
if (votersAavegotchi[msg.sender][_tokenId] == true) {
votesAavegotchi[_tokenId][currentAavegotchiVote[msg.sender][_tokenId]] -= currentAavegotchiBalance[msg.sender][_tokenId];
votesTotalAavegotchi -= currentAavegotchiBalance[msg.sender][_tokenId];
} else {
votersAavegotchi[msg.sender][_tokenId] = true;
}
if (votesAavegotchi[_tokenId][_option] == 0) votedAavegotchi[_tokenId].push(_option);
votesAavegotchi[_tokenId][_option] += balanceOf(msg.sender);
votesTotalAavegotchi[_tokenId] += balanceOf(msg.sender);
currentAavegotchiVote[msg.sender][_tokenId] = _option;
currentAavegotchiBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
uint256 winner;
uint256 result;
if (votesTotalAavegotchi[_tokenId] * 1000 >= ISettings(settingsContract).minAavegotchiVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedAavegotchi[_tokenId].length; i++) {
if (votesAavegotchi[_tokenId][votedAavegotchi[_tokenId][i]] > result) {
result = votesAavegotchi[_tokenId][votedAavegotchi[i]];
winner = votedAavegotchi[_tokenId][i];
}
votesAavegotchi[_tokenId][votedAavegotchi[_tokenId][i]] = 0;
}
aavegotchi[_tokenId] = winner;
PortalAavegotchiTraitsIO[] memory portalInfo = DiamondInterface(diamondContract).portalAavegotchiTraits(_tokenId);
address collateral = portalInfo[_option].collateral;
DiamondInterface(collateral).approve(diamondContract, MAX_INT);
emit AppointedAavegotchi(_tokenId, aavegotchi[_tokenId]);
delete votedAavegotchi[_tokenId];
votesTotalAavegotchi[_tokenId] = 0;
}
}
/// @notice vote for naming an Aavegotchi
function voteForName(uint256 _tokenId, string calldata _name) external {
require(balanceOf(msg.sender) > 0,
"voteForName: only owners can vote"
);
AavegotchiInfo memory gotchi = getAavegotchi(_tokenId);
require(
gotchi.status == 3,
"voteForName: Aavegotchi not summoned yet"
);
require(DiamondInterface(diamondContract).aavegotchiNameAvailable(_name),
"voteForName: Aavegotchi name not available"
);
if (nameNumber[_tokenId] != nameCurrentNumber[msg.sender][_tokenId]) {
votersName[msg.sender][_tokenId] = 0;
currentNameVote[msg.sender][_tokenId] = 0;
currentNameBalance[msg.sender][_tokenId] = 0;
}
if (votersName[msg.sender][_tokenId] == true) {
votesName[_tokenId][currentNameVote[msg.sender][_tokenId]] -= currentNameBalance[msg.sender][_tokenId];
votesTotalName -= currentNameBalance[msg.sender][_tokenId];
} else {
votersName[msg.sender][_tokenId] = true;
}
if (votesName[_tokenId][_name] == 0) votedName[_tokenId].push(_name);
votesName[_tokenId][_name] += balanceOf(msg.sender);
votesTotalName[_tokenId] += balanceOf(msg.sender);
currentNameVote[msg.sender][_tokenId] = _name;
currentNameBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (nameNumber[_tokenId] != nameCurrentNumber[msg.sender][_tokenId])
nameCurrentNumber[msg.sender][_tokenId] = nameNumber[_tokenId];
string memory winner;
uint256 result;
if (votesTotalName[_tokenId] * 1000 >= ISettings(settingsContract).minNameVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedName[_tokenId].length; i++) {
if (votesName[_tokenId][votedName[_tokenId][i]] > result) {
result = votesName[_tokenId][votedName[i]];
winner = votedName[_tokenId][i];
}
votesName[_tokenId][votedName[_tokenId][i]] = 0;
votedName[_tokenId][i] = 0;
}
name[_tokenId] = winner;
DiamondInterface(diamondContract).setAavegotchiName(_tokenId, name[_tokenId]);
emit Named(_tokenId, name[_tokenId]);
votesTotalName[_tokenId] = 0;
nameNumber[_tokenId]++:
}
}
/// @notice vote for spending available skill points on an Aavegotchi
function voteForSkills(uint256 _tokenId, int16[4] calldata _values) external {
require(balanceOf(msg.sender) > 0,
"voteForSkills: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForSkills: auction live cannot update price"
);
uint256 total;
for (uint i = 0; i < _values.length; i++) {
if (_values[i] < 0) {
total += -(_values[i]);
} else {
total += _values[i];
}
}
require(total > 0,
"voteForSkills: must allocate at least 1 skill point"
);
require(DiamondInterface(diamondContract).availableSkillPoints(_tokenId) > total,
"voteForSkills: not enough available skill points"
);
if (skillNumber[_tokenId] != skillCurrentNumber[msg.sender][_tokenId]) {
votersSkill[msg.sender][_tokenId] = 0;
currentSkillBalance[msg.sender][_tokenId] = 0;
}
if (votersSkill[msg.sender][_tokenId] == true) {
votesSkill[_tokenId][currentSkillVote[msg.sender][_tokenId]] -= currentSkillBalance[msg.sender][_tokenId];
votesTotalSkill -= currentSkillBalance[msg.sender][_tokenId];
} else {
votersSkill[msg.sender][_tokenId] = true;
}
uint256 counter;
if (skillVoting[_tokenId] == false) {
votedSkill[_tokenId].push(_values);
votesSkill[_tokenId][0] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = 0;
skillVoting[_tokenId] = true;
} else if (skillVoting == true) {
for (uint i = 0; i < votedSkill.length; i++) {
for (uint j = 0; j < _values.length; j++) {
if (votedSkill[i][j] == _values[j]) counter++;
}
if (counter == 4) {
votesSkill[_tokenId][i] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = i;
break;
}
}
} else if (counter != 4) {
votedSkill[_tokenId].push(_values);
skillIndex++;
votesSkill[_tokenId][skillIndex] += balanceOf(msg.sender);
currentSkillVote[msg.sender][_tokenId] = skillIndex;
}
votesTotalSkill[_tokenId] += balanceOf(msg.sender);
currentSkillBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (skillNumber[_tokenId] != skillCurrentNumber[msg.sender][_tokenId])
skillCurrentNumber[msg.sender][_tokenId] = skillNumber[_tokenId];
uint256 winner;
uint256 result;
if (votesTotalSkill[_tokenId] * 1000 >= ISettings(settingsContract).minSkillVotePercentage() * totalSupply()) {
for (uint i = 0; i < votedSkill[_tokenId].length; i++) {
if (votesSkill[_tokenId][i] > result) {
result = votesSkill[_tokenId][i];
winner = i;
}
votesSkill[_tokenId][i] = 0;
}
DiamondInterface(diamondContract).spendSkillPoints(_tokenId, votedSkill[_tokenId][winner]);
emit SkilledUp(_tokenId, votedSkill[_tokenId][winner]);
delete votedSkill[_tokenId];
skillNumber[_tokenId]++;
votesTotalSkill[_tokenId] = 0;
}
}
/// @notice vote for equipping an Aavegotchi with the selected items in the parameter _wearablesToEquip
function equipWearables(uint256 _tokenId, int16[16] calldata _wearablesToEquip) external {
require(balanceOf(msg.sender) > 0,
"equipWearables: only owners can use this function"
);
require(
auctionStatus == AuctionStatus.INACTIVE,
"equipWearables: auction live cannot equipe wearables"
);
if (fundingStatus = FundingStatus.SUBMITTED) {
require(
_tokenId != listingId,
"equipWearables: cannot equip a type of item being purchased"
);
}
DiamondInterface(diamondContract).equipWearables(_tokenId, _wearablesToEquip);
emit Equipped(_tokenId, _values);
}
/// @notice vote for using consumables on one or several Aavegotchis
function useConsumables(
uint256 _tokenId,
uint256[] calldata _itemIds,
uint256[] calldata _quantities
) external {
require(balanceOf(msg.sender) > 0,
"useConsumables: only owners can use this function"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"useConsumables: auction live cannot use consumables"
);
DiamondInterface(diamondContract).useConsumables(_tokenId, _itemIds, _quantities);
emit ConsumablesUsed(_tokenId, _itemIds, _quantities);
}
/// @notice vote for and appoint a new Player to play with the FrAactionHub's Aavegotchi(s) on behalf of the other owners
function voteForPlayer(address _player) external {
require(
balanceOf(_player) > 0,
"voteForPlayer: player not an owner of the FrAactionHub"
);
require(
finalAuctionStatus != FinalAuctionStatus.ENDED,
"voteForPlayer: cannot vote if an auction is ended"
);
require(
initialized == true,
"voteForPlayer: FrAactionHub not fractionalized yet"
);
require(
balanceOf(msg.sender) > 0,
"voteForPlayer: user not an owner of the NFT"
);
require(
gameType == 0, // 0 is for Delegated FrAactionHub, 1 for Collective FrAactionHub
"voteForPlayer: this FrAactionHub was set as Collective by its creator"
);
if (playerNumber != playerCurrentNumber[msg.sender]) {
votersPlayer[msg.sender] = 0;
currentPlayerVote[msg.sender] = 0;
currentPlayerBalance[msg.sender] = 0;
}
if (votersPlayer[msg.sender] == true) {
votesPlayer[currentPlayerVote[msg.sender]] -= currentPlayerBalance[msg.sender];
votesTotalPlayer -= currentPlayerBalance[msg.sender];
} else {
votersPlayer[msg.sender] = true;
}
votesPlayer[_player] += balanceOf(msg.sender);
votesTotalPlayer += balanceOf(msg.sender);
currentPlayerVote[msg.sender] = _player;
currentPlayerBalance[msg.sender] = balanceOf(msg.sender);
if (playerNumber != playerCurrentNumber[msg.sender]) playerCurrentNumber[msg.sender] = playerNumber;
address winner;
uint256 result;
if (votesTotalPlayer * 1000 >= ISettings(settingsContract).minPlayerVotePercentage() * totalSupply()) {
for (uint i = 0; i < ownersAddress.length; i++) {
if (votesPlayer[ownersAddress[i]] > result) {
result = votesPlayer[ownersAddress[i]];
winner = ownersAddress[i];
}
if (votesPlayer[ownersAddress[i]] != 0) votesPlayer[ownersAddress[i]] = 0;
}
player = winner;
playerNumber++;
votesTotalPlayer = 0;
DiamondInterface(diamondContract).setApprovalForAll(player, true);
emit AppointedPlayer(player);
}
}
function voteForDestruction(uint256 _tokenId, uint256 _xpToId) external {
require(balanceOf(msg.sender) > 0,
"voteForDestruction: only owners can vote"
);
require(
finalAuctionStatus == FinalAuctionStatus.INACTIVE,
"voteForDestruction: auction live cannot update price"
);
if (destroyNumber[_tokenId] != destroyCurrentNumber[msg.sender][_tokenId]) {
votersDestroy[msg.sender][_tokenId] = 0;
currentDestroyBalance[msg.sender][_tokenId] = 0;
}
if (votersDestroy[msg.sender][_tokenId] == true) {
votesTotalDestroy[_tokenId] -= currentDestroyBalance[msg.sender][_tokenId];
} else {
votersDestroy[msg.sender][_tokenId] = true;
}
votesTotalDestroy[_tokenId] += balanceOf(msg.sender);
currentDestroyBalance[msg.sender][_tokenId] = balanceOf(msg.sender);
if (xpToId[_tokenId] == 0) xpToId[tokenId] = _xpToId;
if (destroyNumber[_tokenId] != destroyCurrentNumber[msg.sender][_tokenId])
destroyCurrentNumber[msg.sender][_tokenId] = destroyNumber[_tokenId];
if (votesTotalDestroy[_tokenId] * 1000 >= ISettings(settingsContract).minDestroyVotePercentage() * totalSupply()) {
address collateral = DiamondInterface(diamondContract).collateralBalance(_tokenId).collateralType_;
uint256 balance = DiamondInterface(diamondContract).collateralBalance(_tokenId).balance_;
(bool success, bytes memory returnData) =
diamondContract.call(
abi.encodeWithSignature("decreaseAndDestroy(uint256,uint256)",
_tokenId,
xpToId
)
);
require(
success,
string(
abi.encodePacked(
"voteForDestruction: staking order failed: ",
returnData
)
)
);
redeemedCollateral[collateral].push(balance);
if (collateralToRedeem[collateral] == 0) {
collateralToRedeem[collateral] = true;
collateralAvailable.push(collateral);
}
emit Destroy(_tokenId);
destroyNumber[_tokenId]++;
votesTotalDestroy[_tokenId] = 0;
}
}
/// @notice an internal function used to register receiver previous FractionHub token balance, to be used in the _afterTokenTransfer function
/// @param _from the ERC20 token sender
/// @param _to the ERC20 token receiver
/// @param _amount the ERC20 token amount
function _beforeTokenTransfer(address _from, address _to, uint256 _amount) internal virtual override {
require (split != 7 && split != 8,
"beforeTokenTransfer: cannot transfer because ownership transfer or claimAll ongoing"
);
beforeTransferToBalance = balanceOf(_to);
}
/// @notice an internal function used to update the ownership register and update sender and receivers price after each FractionHub token transfer
/// @param _from the ERC20 token sender
/// @param _to the ERC20 token receiver
/// @param _amount the ERC20 token amount
function _afterTokenTransfer(address _from, address _to, uint256 _amount) internal virtual override {
address replace;
if (balanceOf(_from) == 0) {
if (beforeTransferToBalance == 0) {
replace = ownersAddress[ownersAddress.length - 1];
ownersAddress[ownerAddressIndex[_from]] = replace;
ownersAddress.pop();
ownerAddressIndex[replace] = ownerAddressIndex[_from];
delete ownerAddressIndex[_from];
} else {
ownersAddress[ownerAddressIndex[_from]] = _to;
ownerAddressIndex[_to] = ownerAddressIndex[_from];
delete ownerAddressIndex[_from];
}
}
if (balanceOf(_from) != 0 && beforeTransferToBalance == 0) {
ownersAddress.push(_to);
}
if (_from != address(0)) {
uint256 fromPrice = userPrices[_from];
uint256 toPrice = userPrices[_to];
// only do something if users have different reserve price
if (toPrice != fromPrice) {
// new holder is not a voter
if (toPrice == 0) {
// removing old holder's reserve price
votingTokens -= _amount;
reserveTotal -= _amount * fromPrice;
}
// old holder is not a voter
else if (fromPrice == 0) {
votingTokens += _amount;
reserveTotal += _amount * toPrice;
}
// both holders are voters
else {
reserveTotal = reserveTotal + (_amount * toPrice) - (_amount * fromPrice);
}
}
}
}
}
|
tokenId => each portal option already voted by at least one owner
|
mapping(uint256 => uint256[]) internal votedAavegotchi;
| 5,359,587 |
[
1,
2316,
548,
516,
1517,
11899,
1456,
1818,
331,
16474,
635,
622,
4520,
1245,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
63,
5717,
2713,
331,
16474,
37,
836,
13212,
24010,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0xF506462B46EbbF57548424C21CaeFB1B6E926270/sources/contracts/avaxCertificate.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);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
| 4,566,239 |
[
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
17801,
6835,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
565,
3885,
1832,
225,
288,
203,
3639,
1758,
1234,
12021,
273,
389,
3576,
12021,
5621,
203,
3639,
389,
8443,
273,
1234,
12021,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
1234,
12021,
1769,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
24899,
8443,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
10019,
203,
3639,
389,
8443,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
8863,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
394,
5541,
1769,
203,
3639,
389,
8443,
273,
394,
5541,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x9e2b1cb2a7c8C11ce4C2f9d86b7A34A2beC75632/sources/deploy/Contract.sol
|
* @dev Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`./
|
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
worse(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
| 16,454,343 |
[
1,
3641,
6478,
23850,
3304,
326,
1699,
1359,
17578,
358,
1375,
87,
1302,
264,
68,
635,
326,
4894,
18,
1220,
353,
392,
10355,
358,
288,
12908,
537,
97,
716,
848,
506,
1399,
487,
279,
20310,
360,
367,
364,
9688,
11893,
316,
288,
45,
654,
39,
3462,
17,
12908,
537,
5496,
7377,
1282,
392,
288,
23461,
97,
871,
11193,
326,
3526,
1699,
1359,
18,
29076,
30,
300,
1375,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
87,
1302,
264,
68,
1297,
1240,
1699,
1359,
364,
326,
4894,
434,
622,
4520,
1375,
1717,
1575,
329,
620,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
20467,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
10418,
329,
620,
13,
1071,
5024,
1135,
261,
6430,
13,
288,
203,
3639,
1758,
3410,
273,
389,
3576,
12021,
5621,
203,
3639,
2254,
5034,
783,
7009,
1359,
273,
1699,
1359,
12,
8443,
16,
17571,
264,
1769,
203,
3639,
2583,
12,
2972,
7009,
1359,
1545,
10418,
329,
620,
16,
315,
654,
39,
3462,
30,
23850,
8905,
1699,
1359,
5712,
3634,
8863,
203,
3639,
22893,
288,
203,
5411,
14591,
307,
12,
8443,
16,
17571,
264,
16,
783,
7009,
1359,
300,
10418,
329,
620,
1769,
203,
3639,
289,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Sources flattened with hardhat v2.1.1 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library 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);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/[email protected]
// License: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
_initializing || _isConstructor() || !_initialized,
"Initializable: contract is already initialized"
);
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// License: 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 ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
// License: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// License: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File @openzeppelin/contracts/math/[email protected]
// License: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File @openzeppelin/contracts/utils/[email protected]
// License: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// License: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transfer.selector, to, value)
);
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(
token,
abi.encodeWithSelector(token.transferFrom.selector, from, to, value)
);
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(token.approve.selector, spender, value)
);
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(
value
);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(
value,
"SafeERC20: decreased allowance below zero"
);
_callOptionalReturn(
token,
abi.encodeWithSelector(
token.approve.selector,
spender,
newAllowance
)
);
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(
data,
"SafeERC20: low-level call failed"
);
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
}
}
}
// File contracts/lib/EIP712MetaTransactionUpgradeable/EIP712BaseUpgradeable.sol
//License: MIT
pragma solidity ^0.7.4;
contract EIP712BaseUpgradeable is Initializable {
struct EIP712Domain {
string name;
string version;
uint256 salt;
address verifyingContract;
}
bytes32 internal constant EIP712_DOMAIN_TYPEHASH =
keccak256(
bytes(
"EIP712Domain(string name,string version,uint256 salt,address verifyingContract)"
)
);
bytes32 internal domainSeperator;
function _initialize(string memory name, string memory version)
public
virtual
initializer
{
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(version)),
getChainID(),
address(this)
)
);
}
function getChainID() internal pure returns (uint256 id) {
assembly {
id := chainid()
}
}
function getDomainSeperator() private view returns (bytes32) {
return domainSeperator;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// File contracts/lib/EIP712MetaTransactionUpgradeable/EIP712MetaTransactionUpgradeable.sol
//License: MIT
pragma solidity ^0.7.4;
contract EIP712MetaTransactionUpgradeable is
Initializable,
EIP712BaseUpgradeable
{
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH =
keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) private nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function _initialize(string memory _name, string memory _version)
public
override
initializer
{
EIP712BaseUpgradeable._initialize(_name, _version);
}
function convertBytesToBytes4(bytes memory inBytes)
internal
pure
returns (bytes4 outBytes4)
{
if (inBytes.length == 0) {
return 0x0;
}
assembly {
outBytes4 := mload(add(inBytes, 32))
}
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable virtual returns (bytes memory) {
bytes4 destinationFunctionSig = convertBytesToBytes4(functionSignature);
require(
destinationFunctionSig != msg.sig,
"functionSignature can not be of executeMetaTransaction method"
);
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
nonces[userAddress] = nonces[userAddress].add(1);
// Append userAddress at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
emit MetaTransactionExecuted(
userAddress,
msg.sender,
functionSignature
);
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) external view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address user,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
address signer = ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
require(signer != address(0), "Invalid signature");
return signer == user;
}
function msgSender() internal view returns (address sender) {
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = msg.sender;
}
return sender;
}
}
// File contracts/Coinvise.sol
//License: Unlicensed
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
interface IERC20Extended is IERC20 {
function decimals() external view returns (uint8);
}
contract Coinvise is
Initializable,
OwnableUpgradeable,
EIP712MetaTransactionUpgradeable
{
using SafeMath for uint256;
using SafeERC20 for IERC20Extended;
using SafeERC20 for IERC20;
event CampaignCreated(uint256 indexed campaignId);
event UserRewarded(
address indexed managerAddress,
uint256 indexed campaignId,
address indexed userAddress,
address tokenAddress,
uint256 amount
);
event Multisent(
address indexed tokenAddress,
uint256 recipientsAmount,
uint256 amount
);
event Withdrawn(address indexed recipient, uint256 amount);
event Deposited(
uint256 depositId,
address indexed depositor,
address token,
uint256 amount,
uint256 price
);
event Bought(
address user,
uint256 depositId,
address owner,
address token,
uint256 amount,
uint256 price
);
event WithdrawnDepositOwnerBalance(address user, uint256 amount);
struct Campaign {
uint256 campaignId;
address manager;
address tokenAddress;
uint256 initialBalance;
uint256 remainingBalance;
uint256 linksAmount;
uint256 amountPerLink;
uint256 linksRewardedCount;
}
struct Deposit {
uint256 depositId;
address owner;
address token;
uint256 initialBalance;
uint256 remainingBalance;
uint256 price;
}
/**
* @dev Following are the state variables for this contract
* Due to resrictions of the proxy pattern, do not change the type or order
* of the state variables.
* https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable
*/
uint256 totalDepositOwnersBalanceInWei;
// Next campaign ID by manager
mapping(address => uint256) internal nextCampaignId;
// All campaigns (userAddress => campaignId => Campaign)
mapping(address => mapping(uint256 => Campaign)) internal campaigns;
// All campaign IDs of a user (userAddress => campaignIds[])
mapping(address => uint256[]) internal campaignIds;
// Rewarded addresses by a campaign (campaignId => userAddress[])
mapping(address => mapping(uint256 => mapping(address => bool)))
internal addressRewarded;
// Rewarded links by a campaign (campaignId => slug[])
mapping(uint256 => mapping(string => bool)) internal linksRewarded;
// Next deposit ID by owner
mapping(address => uint256) internal nextDepositId;
// Deposits by user (userAddress => (depositId => deposit)
mapping(address => mapping(uint256 => Deposit)) internal deposits;
// All deposits IDs of a user (userAddress => depositIds[])
mapping(address => uint256[]) internal depositIds;
// Balances by owner
mapping(address => uint256) internal depositOwnersBalancesInWei;
// This is an address whose private key lives in the coinvise backend
// Used for signature verification
address private trustedAddress;
// Premiums Charged on Various Services
uint256 public airdropPerLinkWeiCharged;
uint256 public multisendPerLinkWeiCharged;
uint256 public depositPercentageCharged;
uint256 public depositPercentageChargedDecimals;
// Add any new state variables here
// ETH pseudo-address
address private constant ETHAddress =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// End of state variables
/**
* @dev We cannot have constructors in upgradeable contracts,
* therefore we define an initialize function which we call
* manually once the contract is deployed.
* the initializer modififer ensures that this can only be called once.
* in practice, the openzeppelin library automatically calls the intitazie
* function once deployed.
*/
function initialize(
address _trustedAddress,
uint256 _airdropPerLinkWeiCharged,
uint256 _multisendPerLinkWeiCharged,
uint256 _depositPercentageCharged,
uint256 _depositPercentageChargedDecimals
) public initializer {
require(
_trustedAddress != address(0),
"ERR__INVALID_TRUSTEDADDRESS_0x0"
);
// Call intialize of Base Contracts
require(_trustedAddress != address(0), "ERR__0x0_TRUSTEDADDRESS");
OwnableUpgradeable.__Ownable_init();
EIP712MetaTransactionUpgradeable._initialize("Coinvise", "1");
trustedAddress = _trustedAddress;
// Set premiums
require(_depositPercentageCharged < 30, "ERR_DEPOSIT_FEE_TOO_HIGH");
airdropPerLinkWeiCharged = _airdropPerLinkWeiCharged;
multisendPerLinkWeiCharged = _multisendPerLinkWeiCharged;
depositPercentageCharged = _depositPercentageCharged;
depositPercentageChargedDecimals = _depositPercentageChargedDecimals;
}
function setAirdropPremiums(uint256 _airdropPerLinkWeiCharged)
external
onlyOwner
{
airdropPerLinkWeiCharged = _airdropPerLinkWeiCharged;
}
function setMultisendPremiums(uint256 _mulisendPerLinkWeiCharged)
external
onlyOwner
{
multisendPerLinkWeiCharged = _mulisendPerLinkWeiCharged;
}
function setDepositPremiums(
uint256 _depositPercentageCharged,
uint256 _depositPercentageChargedDecimals
) external onlyOwner {
require(_depositPercentageCharged < 30, "ERR_DEPOSIT_FEE_TOO_HIGH");
depositPercentageCharged = _depositPercentageCharged;
depositPercentageChargedDecimals = _depositPercentageChargedDecimals;
}
function setTrustedAddress(address _trustedAddress) external onlyOwner {
require(_trustedAddress != address(0), "ERR__0x0_TRUSTEDADDRESS");
trustedAddress = _trustedAddress;
}
function withdraw() external onlyOwner {
uint256 totalBalance = address(this).balance;
uint256 balance = totalBalance.sub(totalDepositOwnersBalanceInWei);
msg.sender.transfer(balance);
emit Withdrawn(msg.sender, balance);
}
// Generate Links
function _createCampaign(
address _tokenAddress,
uint256 _linksAmount,
uint256 _amountPerLink
) internal returns (uint256 _campaignId) {
require(
_linksAmount > 0,
"ERR__LINKS_AMOUNT_MUST_BE_GREATHER_THAN_ZERO"
);
require(
_amountPerLink > 0,
"ERR__AMOUNT_PER_LINK_MUST_BE_GREATHER_THAN_ZERO"
);
uint256 _initialBalance = _linksAmount.mul(_amountPerLink);
address _sender = msgSender();
if (_tokenAddress != ETHAddress)
IERC20(_tokenAddress).safeTransferFrom(
_sender,
address(this),
_initialBalance
);
_campaignId = getCampaignId();
Campaign memory _campaign = Campaign({
campaignId: _campaignId,
manager: _sender,
tokenAddress: _tokenAddress,
initialBalance: _initialBalance,
remainingBalance: _initialBalance,
linksAmount: _linksAmount,
amountPerLink: _amountPerLink,
linksRewardedCount: 0
});
campaigns[_sender][_campaignId] = _campaign;
campaignIds[_sender].push(_campaignId);
emit CampaignCreated(_campaignId);
return _campaignId;
}
function createCampaign(
address _tokenAddress,
uint256 _linksAmount,
uint256 _amountPerLink
) external payable returns (uint256 _campaignId) {
uint256 priceInWei = airdropPerLinkWeiCharged * _linksAmount;
_tokenAddress == ETHAddress
? require(
msg.value == _linksAmount.mul(_amountPerLink).add(priceInWei),
"ERR__TOTAL_ETH_AMOUNT_PER_LINK_MUST_BE_PAID"
)
: require(
msg.value == priceInWei,
"ERR__CAMPAIGN_PRICE_MUST_BE_PAID"
);
return _createCampaign(_tokenAddress, _linksAmount, _amountPerLink);
}
function getCampaign(address _campaignManager, uint256 _campaignId)
external
view
returns (
uint256,
address,
address,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
require(
campaigns[_campaignManager][_campaignId].campaignId == _campaignId,
"ERR__CAMPAIGN_DOES_NOT_EXIST"
);
Campaign memory _campaign = campaigns[_campaignManager][_campaignId];
return (
_campaign.campaignId,
_campaign.manager,
_campaign.tokenAddress,
_campaign.initialBalance,
_campaign.remainingBalance,
_campaign.linksAmount,
_campaign.amountPerLink,
_campaign.linksRewardedCount
);
}
function getCampaignIdsFromManager(address _campaignManager)
external
view
returns (uint256[] memory)
{
return campaignIds[_campaignManager];
}
function claim(
address _campaignManager,
uint256 _campaignId,
bytes32 r,
bytes32 s,
uint8 v
) external {
require(
campaigns[_campaignManager][_campaignId].campaignId == _campaignId,
"ERR__CAMPAIGN_DOES_NOT_EXIST"
);
address _claimer = msgSender();
Campaign memory _campaign = campaigns[_campaignManager][_campaignId];
require(
addressRewarded[_campaignManager][_campaignId][_claimer] != true,
"ERR__ADDRESS_ALREADY_REWARDED"
);
// require(linksRewarded[_campaignId][_slug] != true, "ERR__LINK_ALREADY_REWARDED");
// Check if signature is correct
bytes32 messageHash = keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encode(_campaignManager, _campaignId, _claimer))
)
);
address signer = ecrecover(messageHash, v, r, s);
require(signer != address(0), "ERR__0x0_SIGNER");
require(signer == trustedAddress, "ERR__INVALID_SIGNER");
require(
_campaign.linksRewardedCount < _campaign.linksAmount,
"ERR__ALL_LINKS_USED"
);
require(
_campaign.remainingBalance >= _campaign.amountPerLink,
"ERR_NOT_ENOUGH_BALANCE_FOR_REWARDING"
);
address _token = _campaign.tokenAddress;
_token == ETHAddress
? payable(_claimer).transfer(_campaign.amountPerLink)
: IERC20(_token).safeTransfer(_claimer, _campaign.amountPerLink);
// Mark as rewarded
addressRewarded[_campaignManager][_campaignId][_claimer] = true;
campaigns[_campaignManager][_campaignId].linksRewardedCount = _campaign
.linksRewardedCount
.add(1);
campaigns[_campaignManager][_campaignId].remainingBalance = _campaign
.remainingBalance
.sub(_campaign.amountPerLink);
// Emit event
emit UserRewarded(
_campaignManager,
_campaignId,
_claimer,
_token,
_campaign.amountPerLink
);
}
function withdrawRemainingBalanceFromCampaign(uint256 _campaignId)
external
{
require(
campaigns[msg.sender][_campaignId].campaignId == _campaignId,
"ERR__CAMPAIGN_BY_SENDER_DOES_NOT_EXIST"
);
Campaign memory _campaign = campaigns[msg.sender][_campaignId];
require(
_campaign.remainingBalance > 0,
"ERR__ZERO_REMAINING_BALANCE_FOR_WITHDRAWAL"
);
address _token = _campaign.tokenAddress;
campaigns[_campaign.manager][_campaignId].remainingBalance = 0;
_token == ETHAddress
? payable(_campaign.manager).transfer(_campaign.remainingBalance)
: IERC20(_token).safeTransfer(
_campaign.manager,
_campaign.remainingBalance
);
}
function _multisend(
address _token,
address[] memory _recipients,
uint256[] memory _amounts,
uint256 _totalAmount
) internal {
uint256 recipientsLength = _recipients.length;
uint256 amountsLength = _amounts.length;
require(amountsLength == recipientsLength, "ERR__INVALID_ARGS");
address _user = msgSender();
if (_token == ETHAddress)
for (uint8 i = 0; i < recipientsLength; i++)
payable(_recipients[i]).transfer(_amounts[i]);
else
for (uint8 i = 0; i < recipientsLength; i++)
IERC20(_token).safeTransferFrom(
_user,
_recipients[i],
_amounts[i]
);
// Emit event
emit Multisent(_token, recipientsLength, _totalAmount);
}
function multisend(
address _token,
address[] memory _recipients,
uint256[] memory _amounts
) external payable {
uint256 recipientsLength = _recipients.length;
uint256 _totalAmount = 0;
for (uint8 i = 0; i < recipientsLength; i++)
_totalAmount = _totalAmount.add(_amounts[i]);
_token == ETHAddress
? require(
msg.value ==
_totalAmount.add(
multisendPerLinkWeiCharged.mul(recipientsLength)
),
"ERR__MULTISEND_TOTAL_ETH_AMOUNT_MUST_BE_PAID"
)
: require(
msg.value == multisendPerLinkWeiCharged * recipientsLength,
"ERR__MULTISEND_PRICE_MUST_BE_PAID"
);
_multisend(_token, _recipients, _amounts, _totalAmount);
}
// function multisendMeta(
// address _token,
// address[] memory _recipients,
// uint256[] memory _amounts
// ) external {
// _multisend(_token, _recipients, _amounts);
// }
function getCampaignId() internal returns (uint256 _campaignId) {
address _campaignManager = msg.sender;
_campaignId = nextCampaignId[_campaignManager];
if (_campaignId <= 0) {
_campaignId = 1;
}
nextCampaignId[_campaignManager] = _campaignId.add(1);
return _campaignId;
}
function getCampaignRewardedCount(address _manager, uint256 _campaignId)
external
view
returns (uint256)
{
return campaigns[_manager][_campaignId].linksRewardedCount;
}
function _depositToken(
address _token,
uint256 _amount,
uint256 _price
) internal returns (uint256 _depositId) {
require(_amount > 0, "ERR__AMOUNT_MUST_BE_GREATHER_THAN_ZERO");
require(_price > 0, "ERR__PRICE_MUST_BE_GREATHER_THAN_ZERO");
IERC20Extended tokenContract = IERC20Extended(_token);
address _owner = msg.sender;
tokenContract.safeTransferFrom(_owner, address(this), _amount);
_depositId = getDepositId();
Deposit memory _deposit = Deposit({
depositId: _depositId,
owner: _owner,
token: _token,
initialBalance: _amount,
remainingBalance: _amount,
price: _price
});
deposits[_owner][_depositId] = _deposit;
depositIds[_owner].push(_depositId);
emit Deposited(_depositId, _owner, _token, _amount, _price);
}
function depositToken(
address _token,
uint256 _amount,
uint256 _price
) external payable returns (uint256 _depositId) {
IERC20Extended tokenContract = IERC20Extended(_token);
uint256 decimalsZeros = 10**tokenContract.decimals();
// Fee = 2% of the total. (tokenAmount * values.tokenPrice * 0.02) / depositPercentageChargedDecimals
// (depositPercentageChargedDecimals is used for when depositPercentageCharged < 0.01)
// OLD
// uint256 priceInWei = _price
// .mul(_amount)
// .div(decimalsZeros)
// .mul(depositPercentageCharged)
// .div(100)
// .div(10**depositPercentageChargedDecimals);
// Same formula but only dividing once, avoiding truncation as much as possible
uint256 bigTotal = _price.mul(_amount).mul(depositPercentageCharged);
uint256 zeroes = decimalsZeros.mul(100).mul(
10**depositPercentageChargedDecimals
);
uint256 priceInWei = bigTotal.div(zeroes);
require(priceInWei > 0, "ERR__A_PRICE_MUST_BE_PAID");
require(msg.value == priceInWei, "ERR__PRICE_MUST_BE_PAID");
return _depositToken(_token, _amount, _price);
}
function getDepositIdsFromOwner(address _owner)
external
view
returns (uint256[] memory)
{
return depositIds[_owner];
}
function getDeposit(address _owner, uint256 _depositId)
external
view
returns (
uint256,
address,
address,
uint256,
uint256,
uint256
)
{
require(
deposits[_owner][_depositId].depositId == _depositId,
"ERR__DEPOSIT_DOES_NOT_EXIST"
);
Deposit memory _deposit = deposits[_owner][_depositId];
return (
_deposit.depositId,
_deposit.owner,
_deposit.token,
_deposit.initialBalance,
_deposit.remainingBalance,
_deposit.price
);
}
function buyToken(
uint256 _depositId,
address payable _owner,
uint256 _amount
) external payable {
require(
deposits[_owner][_depositId].depositId == _depositId,
"ERR__DEPOSIT_DOES_NOT_EXIST"
);
Deposit memory _deposit = deposits[_owner][_depositId];
require(_amount > 0, "ERR__AMOUNT_MUST_BE_GREATHER_THAN_ZERO");
require(
_deposit.remainingBalance >= _amount,
"ERR_NOT_ENOUGH_BALANCE_TO_BUY"
);
IERC20Extended tokenContract = IERC20Extended(_deposit.token);
uint256 decimalsZeros = 10**tokenContract.decimals();
uint256 totalPrice = _deposit.price.mul(_amount).div(decimalsZeros);
require(totalPrice > 0, "ERR__A_PRICE_MUST_BE_PAID");
require(msg.value == totalPrice, "ERR__TOTAL_PRICE_MUST_BE_PAID");
deposits[_owner][_depositId].remainingBalance = _deposit
.remainingBalance
.sub(_amount);
IERC20(_deposit.token).safeTransfer(msg.sender, _amount);
depositOwnersBalancesInWei[_owner] = depositOwnersBalancesInWei[_owner]
.add(msg.value);
totalDepositOwnersBalanceInWei = totalDepositOwnersBalanceInWei.add(
msg.value
);
emit Bought(
msg.sender,
_depositId,
_owner,
_deposit.token,
_amount,
_deposit.price
);
}
function withdrawDeposit(uint256 _depositId) external {
address _owner = msg.sender;
require(
deposits[_owner][_depositId].depositId == _depositId,
"ERR__DEPOSIT_DOES_NOT_EXIST"
);
Deposit memory _deposit = deposits[_owner][_depositId];
require(_deposit.remainingBalance > 0, "ERR_NO_BALANCE_TO_WITHDRAW");
deposits[_owner][_depositId].remainingBalance = 0;
delete deposits[_owner][_depositId];
IERC20(_deposit.token).safeTransfer(_owner, _deposit.remainingBalance);
}
function withdrawDepositOwnerBalance() external {
address payable owner = msg.sender;
require(
depositOwnersBalancesInWei[owner] > 0,
"ERR_NO_BALANCE_TO_WITHDRAW"
);
uint256 toWithdraw = depositOwnersBalancesInWei[owner];
depositOwnersBalancesInWei[owner] = 0;
totalDepositOwnersBalanceInWei = totalDepositOwnersBalanceInWei.sub(
toWithdraw
);
require(
totalDepositOwnersBalanceInWei >= 0,
"ERR_NO_GENERAL_BALANCE_TO_WITHDRAW"
);
owner.transfer(toWithdraw);
emit WithdrawnDepositOwnerBalance(owner, toWithdraw);
}
function getDepositOwnerBalance() external view returns (uint256) {
return depositOwnersBalancesInWei[msg.sender];
}
function getCoinviseBalance() external view returns (uint256) {
uint256 totalBalance = address(this).balance;
return totalBalance.sub(totalDepositOwnersBalanceInWei);
}
function getDepositId() internal returns (uint256 _depositId) {
_depositId = nextDepositId[msg.sender];
if (_depositId <= 0) {
_depositId = 1;
}
nextDepositId[msg.sender] = _depositId.add(1);
return _depositId;
}
}
|
All campaigns (userAddress => campaignId => Campaign)
|
mapping(address => mapping(uint256 => Campaign)) internal campaigns;
| 14,646,023 |
[
1,
1595,
8965,
87,
261,
1355,
1887,
516,
8965,
548,
516,
17820,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
17820,
3719,
2713,
8965,
87,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/11155111/0xB785ca4943ffbCf28A5c8FC63dBCb83F76177856/sources/project:/contracts/RoyaltyNFT.sol
|
Move the last allocation to the deleted spot
|
skills[index].allocation[authorIndex] = skills[index].allocation[skills[index].allocation.length - 1];
| 3,840,903 |
[
1,
7607,
326,
1142,
13481,
358,
326,
4282,
16463,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5411,
15667,
87,
63,
1615,
8009,
29299,
63,
4161,
1016,
65,
273,
15667,
87,
63,
1615,
8009,
29299,
63,
7771,
737,
87,
63,
1615,
8009,
29299,
18,
2469,
300,
404,
15533,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/13337/0x9C26024A4De24F14A888a2aBF879dd05E67F74eF/sources/contracts/token/MintableERC20.sol
|
override base ERC20 functions to allow for handler functionality
|
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
if (handlers[msg.sender]) {
_transfer(from, to, amount);
return true;
}
_spendAllowance(from, msg.sender, amount);
_transfer(from, to, amount);
return true;
}
| 13,236,295 |
[
1,
10601,
1026,
4232,
39,
3462,
4186,
358,
1699,
364,
1838,
14176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
309,
261,
11046,
63,
3576,
18,
15330,
5717,
288,
203,
5411,
389,
13866,
12,
2080,
16,
358,
16,
3844,
1769,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
3639,
389,
87,
1302,
7009,
1359,
12,
2080,
16,
1234,
18,
15330,
16,
3844,
1769,
203,
3639,
389,
13866,
12,
2080,
16,
358,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
// ERC900
interface IStakeManager {
event Staked(address indexed user, uint256 indexed activatonEpoch, uint256 amount, uint256 total);
event Unstaked(address indexed user, uint256 amount, uint256 total);
function stake(address unstakeValidator, address signer, uint256 amount) public;
function stakeFor(address user, address unstakeValidator, address signer, uint256 amount) public;
function unstake() public;
function totalStakedFor(address addr) public view returns (uint256);
// function totalStaked() public view returns (uint256);
// function token() public view returns (address);
function supportsHistory() public pure returns (bool);
// optional
// function lastStakedFor(address addr) public view returns (uint256);
// function totalStakedForAt(address addr, uint256 blockNumber) public view returns (uint256);
// function totalStakedAt(uint256 blockNumber) public view returns (uint256);
}
|
ERC900 function totalStaked() public view returns (uint256); function token() public view returns (address); optional function lastStakedFor(address addr) public view returns (uint256); function totalStakedForAt(address addr, uint256 blockNumber) public view returns (uint256); function totalStakedAt(uint256 blockNumber) public view returns (uint256);
|
interface IStakeManager {
event Staked(address indexed user, uint256 indexed activatonEpoch, uint256 amount, uint256 total);
event Unstaked(address indexed user, uint256 amount, uint256 total);
function stake(address unstakeValidator, address signer, uint256 amount) public;
function stakeFor(address user, address unstakeValidator, address signer, uint256 amount) public;
function unstake() public;
function totalStakedFor(address addr) public view returns (uint256);
function supportsHistory() public pure returns (bool);
}
| 2,516,314 |
[
1,
654,
39,
29,
713,
445,
2078,
510,
9477,
1435,
1071,
1476,
1135,
261,
11890,
5034,
1769,
445,
1147,
1435,
1071,
1476,
1135,
261,
2867,
1769,
3129,
445,
1142,
510,
9477,
1290,
12,
2867,
3091,
13,
1071,
1476,
1135,
261,
11890,
5034,
1769,
445,
2078,
510,
9477,
1290,
861,
12,
2867,
3091,
16,
2254,
5034,
1203,
1854,
13,
1071,
1476,
1135,
261,
11890,
5034,
1769,
445,
2078,
510,
9477,
861,
12,
11890,
5034,
1203,
1854,
13,
1071,
1476,
1135,
261,
11890,
5034,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5831,
467,
510,
911,
1318,
288,
203,
225,
871,
934,
9477,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
5981,
16799,
14638,
16,
2254,
5034,
3844,
16,
2254,
5034,
2078,
1769,
203,
225,
871,
1351,
334,
9477,
12,
2867,
8808,
729,
16,
2254,
5034,
3844,
16,
2254,
5034,
2078,
1769,
203,
203,
225,
445,
384,
911,
12,
2867,
640,
334,
911,
5126,
16,
1758,
10363,
16,
2254,
5034,
3844,
13,
1071,
31,
203,
225,
445,
384,
911,
1290,
12,
2867,
729,
16,
1758,
640,
334,
911,
5126,
16,
1758,
10363,
16,
2254,
5034,
3844,
13,
1071,
31,
203,
225,
445,
640,
334,
911,
1435,
1071,
31,
203,
225,
445,
2078,
510,
9477,
1290,
12,
2867,
3091,
13,
1071,
1476,
1135,
261,
11890,
5034,
1769,
203,
225,
445,
6146,
5623,
1435,
1071,
16618,
1135,
261,
6430,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/97/0x93C7D04b0F91492e50EDC521f8da39D515B9F3C1/sources/contracts/JNFT.sol
|
token id => extra info v2
|
mapping(uint256 => ExtraInfos.ExtraInfoV2) public extraInfoV2;
| 3,273,329 |
[
1,
2316,
612,
516,
2870,
1123,
331,
22,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2874,
12,
11890,
5034,
516,
13592,
7655,
18,
7800,
966,
58,
22,
13,
1071,
2870,
966,
58,
22,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
//import "./ERC20.sol";
//import "./ERC20Basic.sol";
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken {
using SafeMath for uint256;
// public variables
string public name;
string public symbol;
uint8 public decimals = 18;
// internal variables
uint256 _totalSupply;
mapping(address => uint256) _balances;
event Transfer(address indexed from, address indexed to, uint256 value);
// events
// public functions
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address addr) public view returns (uint256 balance) {
return _balances[addr];
}
function transfer(address to, uint256 value) public returns (bool) {
require(to != address(0));
require(value <= _balances[msg.sender]);
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
// internal functions
}
contract StandardToken is BasicToken {
// public variables
// internal variables
mapping (address => mapping (address => uint256)) _allowances;
event Approval(address indexed owner, address indexed agent, uint256 value);
// events
// public functions
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(to != address(0));
require(value <= _balances[from]);
require(value <= _allowances[from][msg.sender]);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
function approve(address agent, uint256 value) public returns (bool) {
_allowances[msg.sender][agent] = value;
emit Approval(msg.sender, agent, value);
return true;
}
function allowance(address owner, address agent) public view returns (uint256) {
return _allowances[owner][agent];
}
function increaseApproval(address agent, uint value) public returns (bool) {
_allowances[msg.sender][agent] = _allowances[msg.sender][agent].add(value);
emit Approval(msg.sender, agent, _allowances[msg.sender][agent]);
return true;
}
function decreaseApproval(address agent, uint value) public returns (bool) {
uint allowanceValue = _allowances[msg.sender][agent];
if (value > allowanceValue) {
_allowances[msg.sender][agent] = 0;
} else {
_allowances[msg.sender][agent] = allowanceValue.sub(value);
}
emit Approval(msg.sender, agent, _allowances[msg.sender][agent]);
return true;
}
// internal functions
}
contract ISOToken is StandardToken {
// public variables
string public name = "International Service Organization";
string public symbol = "ISO";
uint8 public decimals = 18;
// internal variables
// events
// public functions
constructor(
address _tokenReceiver
)
public
{
//init _totalSupply
_totalSupply = 5 * (10 ** 9) * (10 ** uint256(decimals));
_balances[_tokenReceiver] = _totalSupply;
emit Transfer(0x0, _tokenReceiver, _totalSupply);
}
// internal functions
}
|
public variables internal variables events public functions
|
contract ISOToken is StandardToken {
string public name = "International Service Organization";
string public symbol = "ISO";
uint8 public decimals = 18;
constructor(
address _tokenReceiver
)
public
}
{
_totalSupply = 5 * (10 ** 9) * (10 ** uint256(decimals));
_balances[_tokenReceiver] = _totalSupply;
emit Transfer(0x0, _tokenReceiver, _totalSupply);
}
}
| 2,106,134 |
[
1,
482,
3152,
2713,
3152,
2641,
1071,
4186,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
9351,
1345,
353,
8263,
1345,
288,
203,
565,
533,
1071,
508,
273,
315,
21843,
8371,
1956,
12046,
14432,
203,
565,
533,
1071,
3273,
273,
315,
12609,
14432,
203,
565,
2254,
28,
1071,
15105,
273,
6549,
31,
203,
203,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
2316,
12952,
203,
565,
262,
203,
565,
1071,
203,
97,
203,
565,
288,
203,
3639,
389,
4963,
3088,
1283,
273,
1381,
380,
261,
2163,
2826,
2468,
13,
380,
261,
2163,
2826,
2254,
5034,
12,
31734,
10019,
203,
203,
3639,
389,
70,
26488,
63,
67,
2316,
12952,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
20,
92,
20,
16,
389,
2316,
12952,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.16;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Context {
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
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);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
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");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function 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));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface AaveAddressesProvider {
function getLendingPool() external view returns (address);
function getLendingPoolCore() external view returns (address);
}
interface Aave {
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external;
}
interface AToken {
function redeem(uint256 amount) external;
}
interface eVault {
function deposit(uint) external;
function withdraw(uint) external;
function getPricePerFullShare() external view returns (uint);
}
contract eWrappedVault is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
uint public min = 9500;
uint public constant max = 10000;
uint public earnLowerlimit;
address public governance;
address public constant vault = 0x92506699DB1c4cd152B63d59ddedE71B6fDB1236;
address public constant aave = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8;
address public constant aToken = 0xA64BD6C70Cb9051F6A9ba1F163Fdc07E0DfB5F84;
constructor (address _token, uint _earnLowerlimit) public ERC20Detailed(
string(abi.encodePacked("YFElite ", ERC20Detailed(_token).name())),
string(abi.encodePacked("e", ERC20Detailed(_token).symbol())),
ERC20Detailed(_token).decimals()
) {
token = IERC20(_token);
governance = msg.sender;
earnLowerlimit = _earnLowerlimit;
}
function balance() public view returns (uint) {
return token.balanceOf(address(this))
.add(balanceUnderlying());
}
function balanceUnderlying() public view returns (uint) {
return IERC20(vault).balanceOf(address(this)).mul(eVault(vault).getPricePerFullShare()).div(1e18);
}
function setMin(uint _min) external {
require(msg.sender == governance, "!governance");
min = _min;
}
function setGovernance(address _governance) public {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setEarnLowerlimit(uint256 _earnLowerlimit) public{
require(msg.sender == governance, "!governance");
earnLowerlimit = _earnLowerlimit;
}
// Custom logic in here for how much the vault allows to be borrowed
// Sets minimum required on-hand to keep small withdrawals cheap
function available() public view returns (uint) {
return token.balanceOf(address(this)).mul(min).div(max);
}
function _supplyAave(uint amount) internal {
token.safeApprove(getAaveCore(), 0);
token.safeApprove(getAaveCore(), amount);
Aave(getAave()).deposit(address(token), amount, 0);
}
function getAave() public view returns (address) {
return AaveAddressesProvider(aave).getLendingPool();
}
function getAaveCore() public view returns (address) {
return AaveAddressesProvider(aave).getLendingPoolCore();
}
function earn() public {
uint _bal = available();
if (_bal > 0) {
_supplyAave(_bal);
_bal = IERC20(aToken).balanceOf(address(this));
if (_bal > 0) {
IERC20(aToken).safeApprove(vault, 0);
IERC20(aToken).safeApprove(vault, _bal);
eVault(vault).deposit(_bal);
}
}
}
function depositAll() external {
deposit(token.balanceOf(msg.sender));
}
function deposit(uint _amount) public {
uint _pool = balance();
uint _before = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint _after = token.balanceOf(address(this));
_amount = _after.sub(_before); // Additional check for deflationary tokens
uint shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount.mul(totalSupply())).div(_pool);
}
_mint(msg.sender, shares);
if (token.balanceOf(address(this))>earnLowerlimit){
earn();
}
}
function withdrawAll() external {
withdraw(balanceOf(msg.sender));
}
function _withdraw(uint _amount) internal {
eVault(vault).withdraw(_amount);
AToken(aToken).redeem(_amount);
}
// No rebalance implementation for lower fees and faster swaps
function withdraw(uint _shares) public {
uint r = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
// Check balance
uint b = token.balanceOf(address(this));
if (b < r) {
uint _amount = r.sub(b);
_withdraw(_amount);
uint _after = token.balanceOf(address(this));
uint _diff = _after.sub(b);
if (_diff < _amount) {
r = b.add(_diff);
}
}
token.safeTransfer(msg.sender, r);
}
function getPricePerFullShare() public view returns (uint) {
return balance().mul(1e18).div(totalSupply());
}
}
|
No rebalance implementation for lower fees and faster swaps Check balance
|
function withdraw(uint _shares) public {
uint r = (balance().mul(_shares)).div(totalSupply());
_burn(msg.sender, _shares);
uint b = token.balanceOf(address(this));
if (b < r) {
uint _amount = r.sub(b);
_withdraw(_amount);
uint _after = token.balanceOf(address(this));
uint _diff = _after.sub(b);
if (_diff < _amount) {
r = b.add(_diff);
}
}
token.safeTransfer(msg.sender, r);
}
| 13,768,776 |
[
1,
2279,
283,
12296,
4471,
364,
2612,
1656,
281,
471,
12063,
1352,
6679,
2073,
11013,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
598,
9446,
12,
11890,
389,
30720,
13,
1071,
288,
203,
3639,
2254,
436,
273,
261,
12296,
7675,
16411,
24899,
30720,
13,
2934,
2892,
12,
4963,
3088,
1283,
10663,
203,
3639,
389,
70,
321,
12,
3576,
18,
15330,
16,
389,
30720,
1769,
203,
540,
203,
3639,
2254,
324,
273,
1147,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
70,
411,
436,
13,
288,
203,
5411,
2254,
389,
8949,
273,
436,
18,
1717,
12,
70,
1769,
203,
5411,
389,
1918,
9446,
24899,
8949,
1769,
203,
5411,
2254,
389,
5205,
273,
1147,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
2254,
389,
5413,
273,
389,
5205,
18,
1717,
12,
70,
1769,
203,
5411,
309,
261,
67,
5413,
411,
389,
8949,
13,
288,
203,
7734,
436,
273,
324,
18,
1289,
24899,
5413,
1769,
203,
5411,
289,
203,
3639,
289,
203,
540,
203,
3639,
1147,
18,
4626,
5912,
12,
3576,
18,
15330,
16,
436,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2018 Ethfinex Inc
This is a derivative work based on software developed by ZeroEx Intl
This and the original are licensed under Apache License, Version 2.0
Original attribution:
Copyright 2017 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.19;
interface Token {
/// @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, uint _value) public returns (bool);
/// @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, uint _value) public returns (bool);
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) public returns (bool);
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint);
event Transfer(address indexed _from, address indexed _to, uint _value); // solhint-disable-line
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
//solhint-disable-next-line
/// @title TokenTransferProxy - Transfers tokens on behalf of exchange
/// @author Ahmed Ali <[email protected]>
contract TokenTransferProxy {
modifier onlyExchange {
require(msg.sender == exchangeAddress);
_;
}
address public exchangeAddress;
event LogAuthorizedAddressAdded(address indexed target, address indexed caller);
function TokenTransferProxy() public {
setExchange(msg.sender);
}
/*
* Public functions
*/
/// @dev Calls into ERC20 Token contract, invoking transferFrom.
/// @param token Address of token to transfer.
/// @param from Address to transfer token from.
/// @param to Address to transfer token to.
/// @param value Amount of token to transfer.
/// @return Success of transfer.
function transferFrom(
address token,
address from,
address to,
uint value)
public
onlyExchange
returns (bool)
{
return Token(token).transferFrom(from, to, value);
}
/// @dev Used to set exchange address
/// @param _exchange the address of the exchange
function setExchange(address _exchange) internal {
require(exchangeAddress == address(0));
exchangeAddress = _exchange;
}
}
|
@dev Calls into ERC20 Token contract, invoking transferFrom. @param token Address of token to transfer. @param from Address to transfer token from. @param to Address to transfer token to. @param value Amount of token to transfer. @return Success of transfer.
|
function transferFrom(
address token,
address from,
address to,
uint value)
public
onlyExchange
returns (bool)
{
return Token(token).transferFrom(from, to, value);
}
| 1,136,842 |
[
1,
10125,
1368,
4232,
39,
3462,
3155,
6835,
16,
15387,
7412,
1265,
18,
225,
1147,
5267,
434,
1147,
358,
7412,
18,
225,
628,
5267,
358,
7412,
1147,
628,
18,
225,
358,
5267,
358,
7412,
1147,
358,
18,
225,
460,
16811,
434,
1147,
358,
7412,
18,
327,
11958,
434,
7412,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
1147,
16,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
460,
13,
203,
3639,
1071,
203,
3639,
1338,
11688,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
3155,
12,
2316,
2934,
13866,
1265,
12,
2080,
16,
358,
16,
460,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import {OilerOptionDifficulty} from "./OilerOptionDifficulty.sol";
import {OilerOptionBaseFactory} from "./OilerOptionBaseFactory.sol";
contract OilerOptionDifficultyFactory is OilerOptionBaseFactory {
constructor(
address _factoryOwner,
address _registryAddress,
address _bRouter,
address _optionLogicImplementation
) OilerOptionBaseFactory(_factoryOwner, _registryAddress, _bRouter, _optionLogicImplementation) {}
function createOption(
uint256 _strikePrice,
uint256 _expiryTS,
bool _put,
address _collateral,
uint256 _collateralToPushIntoAmount,
uint256 _optionsToPushIntoPool
) external override onlyOwner returns (address optionAddress) {
address option = _createOption();
OilerOptionDifficulty(option).init(_strikePrice, _expiryTS, _put, _collateral);
_pullInitialLiquidityCollateral(_collateral, _collateralToPushIntoAmount);
_initializeOptionsPool(
OptionInitialLiquidity(_collateral, _collateralToPushIntoAmount, option, _optionsToPushIntoPool)
);
registry.registerOption(option, "H");
emit Created(option, "H");
return option;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import {HeaderRLP} from "./lib/HeaderRLP.sol";
import {OilerOption} from "./OilerOptionBase.sol";
contract OilerOptionDifficulty is OilerOption {
string private constant _optionType = "H";
string private constant _name = "OilerOptionHashrate";
constructor() OilerOption() {}
function init(
uint256 _strikePrice,
uint256 _expiryTS,
bool _put,
address _collateralAddress
) external {
super._init(_strikePrice, _expiryTS, _put, _collateralAddress);
}
function exercise(bytes calldata _rlp) external returns (bool) {
require(isActive(), "OilerOptionDifficulty.exercise: not active, cannot exercise");
uint256 blockNumber = HeaderRLP.checkBlockHash(_rlp);
require(
blockNumber >= startBlock,
"OilerOptionDifficulty.exercise: can only be exercised with a block after option creation"
);
uint256 difficulty = HeaderRLP.getDifficulty(_rlp);
_exercise(difficulty);
return true;
}
function optionType() external pure override returns (string memory) {
return _optionType;
}
function name() public pure override returns (string memory) {
return _name;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import {IBRouter} from "./interfaces/IBRouter.sol";
import {IOilerOptionBase} from "./interfaces/IOilerOptionBase.sol";
import {IBPool} from "./interfaces/IBPool.sol";
import {OilerRegistry} from "./OilerRegistry.sol";
import {ProxyFactory} from "./proxies/ProxyFactory.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
abstract contract OilerOptionBaseFactory is Ownable, ProxyFactory {
event Created(address _optionAddress, bytes32 _symbol);
struct OptionInitialLiquidity {
address collateral;
uint256 collateralAmount;
address option;
uint256 optionsAmount;
}
/**
* @dev Stores address of the registry.
*/
OilerRegistry public immutable registry;
/**
* @dev Address on which proxy logic is deployed.
*/
address public optionLogicImplementation;
/**
* @dev Balancer pools bRouter address.
*/
IBRouter public immutable bRouter;
/**
* @param _factoryOwner - Factory owner.
* @param _registryAddress - Oiler options registry address.
* @param _optionLogicImplementation - Proxy implementation address.
*/
constructor(
address _factoryOwner,
address _registryAddress,
address _bRouter,
address _optionLogicImplementation
) Ownable() {
Ownable.transferOwnership(_factoryOwner);
bRouter = IBRouter(_bRouter);
registry = OilerRegistry(_registryAddress);
optionLogicImplementation = _optionLogicImplementation;
}
function createOption(
uint256 _strikePrice,
uint256 _expiryTS,
bool _put,
address _collateral,
uint256 _collateralToPushIntoAmount,
uint256 _optionsToPushIntoPool
) external virtual returns (address optionAddress);
/**
* @dev Allows factory owner to remove liquidity from pool.
* @param _option - option liquidity pool to be withdrawn..
*/
function removeOptionsPoolLiquidity(address _option) external onlyOwner {
_removeOptionsPoolLiquidity(_option);
}
function isClone(address _query) external view returns (bool) {
return _isClone(optionLogicImplementation, _query);
}
function _createOption() internal returns (address) {
return _createClone(optionLogicImplementation);
}
/**
* @dev Transfers collateral from msg.sender to contract.
* @param _collateral - option collateral.
* @param _collateralAmount - collateral amount to be transfered.
*/
function _pullInitialLiquidityCollateral(address _collateral, uint256 _collateralAmount) internal {
require(
IERC20(_collateral).transferFrom(msg.sender, address(this), _collateralAmount),
"OilerOptionBaseFactory: ERC20 transfer failed"
);
}
/**
* @dev Initialized a new balancer liquidity pool by providing to it option token and collateral.
* @notice creates a new liquidity pool.
* @notice during initialization some options are written and provided to the liquidity pool.
* @notice pulls collateral.
* @param _initialLiquidity - See {OptionInitialLiquidity}.
*/
function _initializeOptionsPool(OptionInitialLiquidity memory _initialLiquidity) internal {
// Approve option to pull collateral while writing option.
require(
IERC20(_initialLiquidity.collateral).approve(_initialLiquidity.option, _initialLiquidity.optionsAmount),
"OilerOptionBaseFactory: ERC20 approval failed, option"
);
// Approve bRouter to pull collateral.
require(
IERC20(_initialLiquidity.collateral).approve(address(bRouter), _initialLiquidity.collateralAmount),
"OilerOptionBaseFactory: ERC20 approval failed, bRouter"
);
// Approve bRouter to pull written options.
require(
IERC20(_initialLiquidity.option).approve(address(bRouter), _initialLiquidity.optionsAmount),
"OilerOptionBaseFactory: ERC20 approval failed, bRouter"
);
// Pull liquidity required to write an option.
_pullInitialLiquidityCollateral(
address(IOilerOptionBase(_initialLiquidity.option).collateralInstance()),
_initialLiquidity.optionsAmount
);
// Write the option.
IOilerOptionBase(_initialLiquidity.option).write(_initialLiquidity.optionsAmount);
// Add liquidity.
bRouter.addLiquidity(
_initialLiquidity.option,
_initialLiquidity.collateral,
_initialLiquidity.optionsAmount,
_initialLiquidity.collateralAmount
);
}
/**
* @dev Removes liquidity provided while option creation.
* @notice withdraws remaining in pool options and collateral.
* @notice if option is still active reverts.
* @notice once liquidity is removed the pool becomes unusable.
* @param _option - option liquidity pool to be withdrawn.
*/
function _removeOptionsPoolLiquidity(address _option) internal {
require(
!IOilerOptionBase(_option).isActive(),
"OilerOptionBaseFactory.removeOptionsPoolLiquidity: option still active"
);
address optionCollateral = address(IOilerOptionBase(_option).collateralInstance());
IBPool pool = bRouter.getPoolByTokens(_option, optionCollateral);
require(
pool.approve(address(bRouter), pool.balanceOf(address(this))),
"OilerOptionBaseFactory.removeOptionsPoolLiquidity: approval failed"
);
uint256[] memory amounts = bRouter.removeLiquidity(_option, optionCollateral, pool.balanceOf(address(this)));
require(IERC20(_option).transfer(msg.sender, amounts[0]), "ERR_ERC20_FAILED");
require(IERC20(optionCollateral).transfer(msg.sender, amounts[1]), "ERR_ERC20_FAILED");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
// This library extracts data from Block header encoded in RLP format.
// It is not a complete implementation, but optimized for specific cases - thus many hardcoded values.
// Here's the current RLP structure and the values we're looking for:
//
// idx Element element length with 1 byte storing its length
// ==========================================================================
// Static elements (always same size):
//
// 0 RLP length 1+2
// 1 parentHash 1+32
// 2 ommersHash 1+32
// 3 beneficiary 1+20
// 4 stateRoot 1+32
// 5 TransactionRoot 1+32
// 6 receiptsRoot 1+32
// logsBloom length 1+2
// 7 logsBloom 256
// =========
// Total static elements size: 448 bytes
//
// Dynamic elements (need to read length) start at position 448
// and each one is preceeded with 1 byte length (if element is >= 128)
// or if element is < 128 - then length byte is skipped and it is just the 1-byte element:
//
// 8 difficulty - starts at pos 448
// 9 number - blockNumber
// 10 gasLimit
// 11 gasUsed
// 12 timestamp
// 13 extraData
// 14 mixHash
// 15 nonce
// SAFEMATH DISCLAIMER:
// We and don't use SafeMath here intentionally, because input values are bytes in a byte-array, thus limited to 255
library HeaderRLP {
function checkBlockHash(bytes calldata rlp) external view returns (uint256) {
uint256 rlpBlockNumber = getBlockNumber(rlp);
require(
blockhash(rlpBlockNumber) == keccak256(rlp), // blockhash() costs 20 now but it may cost 5000 in the future
"HeaderRLP.checkBlockHash: Block hashes don't match"
);
return rlpBlockNumber;
}
function nextElementJump(uint8 prefix) public pure returns (uint8) {
// RLP has much more options for element lenghts
// But we are safe between 56 bytes and 2MB
if (prefix <= 128) {
return 1;
} else if (prefix <= 183) {
return prefix - 128 + 1;
}
revert("HeaderRLP.nextElementJump: Given element length not implemented");
}
// no loop saves ~300 gas
function getBlockNumberPositionNoLoop(bytes memory rlp) public pure returns (uint256) {
uint256 pos;
//jumpting straight to the 1st dynamic element at pos 448 - difficulty
pos = 448;
//2nd element - block number
pos += nextElementJump(uint8(rlp[pos]));
return pos;
}
// no loop saves ~300 gas
function getGasLimitPositionNoLoop(bytes memory rlp) public pure returns (uint256) {
uint256 pos;
//jumpting straight to the 1st dynamic element at pos 448 - difficulty
pos = 448;
//2nd element - block number
pos += nextElementJump(uint8(rlp[pos]));
//3rd element - gas limit
pos += nextElementJump(uint8(rlp[pos]));
return pos;
}
// no loop saves ~300 gas
function getTimestampPositionNoLoop(bytes memory rlp) public pure returns (uint256) {
uint256 pos;
//jumpting straight to the 1st dynamic element at pos 448 - difficulty
pos = 448;
//2nd element - block number
pos += nextElementJump(uint8(rlp[pos]));
//3rd element - gas limit
pos += nextElementJump(uint8(rlp[pos]));
//4th element - gas used
pos += nextElementJump(uint8(rlp[pos]));
//timestamp - jackpot!
pos += nextElementJump(uint8(rlp[pos]));
return pos;
}
function getBaseFeePositionNoLoop(bytes memory rlp) public pure returns (uint256) {
//jumping straight to the 1st dynamic element at pos 448 - difficulty
uint256 pos = 448;
// 2nd element - block number
pos += nextElementJump(uint8(rlp[pos]));
// 3rd element - gas limit
pos += nextElementJump(uint8(rlp[pos]));
// 4th element - gas used
pos += nextElementJump(uint8(rlp[pos]));
// timestamp
pos += nextElementJump(uint8(rlp[pos]));
// extradata
pos += nextElementJump(uint8(rlp[pos]));
// mixhash
pos += nextElementJump(uint8(rlp[pos]));
// nonce
pos += nextElementJump(uint8(rlp[pos]));
// nonce
pos += nextElementJump(uint8(rlp[pos]));
return pos;
}
function extractFromRLP(bytes calldata rlp, uint256 elementPosition) public pure returns (uint256 element) {
// RLP hint: If the byte is less than 128 - than this byte IS the value needed - just return it.
if (uint8(rlp[elementPosition]) < 128) {
return uint256(uint8(rlp[elementPosition]));
}
// RLP hint: Otherwise - this byte stores the length of the element needed (in bytes).
uint8 elementSize = uint8(rlp[elementPosition]) - 128;
// ABI Encoding hint for dynamic bytes element:
// 0x00-0x04 (4 bytes): Function signature
// 0x05-0x23 (32 bytes uint): Offset to raw data of RLP[]
// 0x24-0x43 (32 bytes uint): Length of RLP's raw data (in bytes)
// 0x44-.... The RLP raw data starts here
// 0x44 + elementPosition: 1 byte stores a length of our element
// 0x44 + elementPosition + 1: Raw data of the element
// Copies the element from calldata to uint256 stored in memory
assembly {
calldatacopy(
add(mload(0x40), sub(32, elementSize)), // Copy to: Memory 0x40 (free memory pointer) + 32bytes (uint256 size) - length of our element (in bytes)
add(0x44, add(elementPosition, 1)), // Copy from: Calldata 0x44 (RLP raw data offset) + elementPosition + 1 byte for the size of element
elementSize
)
element := mload(mload(0x40)) // Load the 32 bytes (uint256) stored at memory 0x40 pointer - into return value
}
return element;
}
function getBlockNumber(bytes calldata rlp) public pure returns (uint256 bn) {
return extractFromRLP(rlp, getBlockNumberPositionNoLoop(rlp));
}
function getTimestamp(bytes calldata rlp) external pure returns (uint256 ts) {
return extractFromRLP(rlp, getTimestampPositionNoLoop(rlp));
}
function getDifficulty(bytes calldata rlp) external pure returns (uint256 diff) {
return extractFromRLP(rlp, 448);
}
function getGasLimit(bytes calldata rlp) external pure returns (uint256 gasLimit) {
return extractFromRLP(rlp, getGasLimitPositionNoLoop(rlp));
}
function getBaseFee(bytes calldata rlp) external pure returns (uint256 baseFee) {
return extractFromRLP(rlp, getBaseFeePositionNoLoop(rlp));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./lib/GenSymbol.sol";
import "./interfaces/IOilerCollateral.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/drafts/ERC20PermitUpgradeable.sol";
abstract contract OilerOption is ERC20Upgradeable, ERC20BurnableUpgradeable, ERC20PermitUpgradeable {
using SafeMath for uint256;
event Created(address indexed _optionAddress, string _symbol);
event Exercised(uint256 _value);
uint256 private constant MAX_UINT256 = type(uint256).max;
// Added compatibility function below:
function holderBalances(address holder_) public view returns (uint256) {
return balanceOf(holder_);
}
mapping(address => uint256) public writerBalances;
mapping(address => mapping(address => uint256)) public allowed;
// OilerOption variables
uint256 public startTS;
uint256 public startBlock;
uint256 public strikePrice;
uint256 public expiryTS;
bool public put; // put if true, call if false
bool public exercised = false;
IERC20 public collateralInstance;
// Writes an option, locking the collateral
function write(uint256 _amount) external {
_write(_amount, msg.sender, msg.sender);
}
function write(uint256 _amount, address _writer) external {
_write(_amount, _writer, _writer);
}
function write(
uint256 _amount,
address _writer,
address _holder
) external {
_write(_amount, _writer, _holder);
}
// Check if option's Expiration date has already passed
function isAfterExpirationDate() public view returns (bool expired) {
return (expiryTS <= block.timestamp);
}
function withdraw(uint256 _amount) external {
if (isActive()) {
// If the option is still Active - one can only release options that he wrote and still holds
writerBalances[msg.sender] = writerBalances[msg.sender].sub(
_amount,
"Option.withdraw: Release amount exceeds options written"
);
_burn(msg.sender, _amount);
} else {
if (hasBeenExercised()) {
// If the option was exercised - only holders can withdraw the collateral
_burn(msg.sender, _amount);
} else {
// If the option wasn't exercised, but it's not active - this means it expired - and only writers can withdraw the collateral
writerBalances[msg.sender] = writerBalances[msg.sender].sub(
_amount,
"Option.withdraw: Withdraw amount exceeds options written"
);
}
}
// If none of the above failed - then we succesfully withdrew the amount and we're good to burn tokens and release the collateral
bool success = collateralInstance.transfer(msg.sender, _amount);
require(success, "Option.withdraw: collateral transfer failed");
}
// Get withdrawable collateral
function getWithdrawable(address _owner) external view returns (uint256 amount) {
if (isActive()) {
// If the option is still Active - one can only withdraw options that he wrote and still holds
return min(holderBalances(_owner), writerBalances[_owner]);
} else {
if (hasBeenExercised()) {
// If the option was exercised - only holders can withdraw the collateral
return holderBalances(_owner);
} else {
// If the option wasn't exercised, but it's not active - this means it expired - and only writers can withdraw the collateral
return writerBalances[_owner];
}
}
}
// Get amount of collateral locked in options
function getLocked(address _address) external view returns (uint256 amount) {
if (isActive()) {
return writerBalances[_address];
} else {
return 0;
}
}
function name() public view virtual override returns (string memory) {}
// Option is Active (can still be written or exercised) - if it hasn't expired nor hasn't been exercised.
// Option is not Active (and the collateral can be withdrawn) - if it has expired or has been exercised.
function isActive() public view returns (bool active) {
return (!isAfterExpirationDate() && !hasBeenExercised());
}
// Option is Expired if its Expiration Date has already passed and it wasn't exercised
function hasExpired() public view returns (bool) {
return isAfterExpirationDate() && !hasBeenExercised();
}
// Additional getter to make it more readable
function hasBeenExercised() public view returns (bool) {
return exercised;
}
function optionType() external view virtual returns (string memory) {}
function _init(
uint256 _strikePrice,
uint256 _expiryTS,
bool _put,
address _collateralAddress
) internal initializer {
startTS = block.timestamp;
require(_expiryTS > startTS, "OilerOptionBase.init: expiry TS must be above start TS");
expiryTS = _expiryTS;
startBlock = block.number;
strikePrice = _strikePrice;
put = _put;
string memory _symbol = GenSymbol.genOptionSymbol(_expiryTS, this.optionType(), _put, _strikePrice);
__Context_init_unchained();
__ERC20_init_unchained(this.name(), _symbol);
__ERC20Burnable_init_unchained();
__EIP712_init_unchained(this.name(), "1");
__ERC20Permit_init_unchained(this.name());
collateralInstance = IOilerCollateral(_collateralAddress);
_setupDecimals(IOilerCollateral(_collateralAddress).decimals());
emit Created(address(this), this.symbol());
}
function _write(
uint256 _amount,
address _writer,
address _holder
) internal {
require(isActive(), "Option.write: not active, cannot mint");
_mint(_holder, _amount);
writerBalances[_writer] = writerBalances[_writer].add(_amount);
bool success = collateralInstance.transferFrom(msg.sender, address(this), _amount);
require(success, "Option.write: collateral transfer failed");
}
function _exercise(uint256 price) internal {
// (from vanilla option lingo) if it is a PUT then I can sell it at a higher (strike) price than the current price - I have a right to PUT it on the market
// (from vanilla option lingo) if it is a CALL then I can buy it at a lower (strike) price than the current price - I have a right to CALL it from the market
if ((put && strikePrice >= price) || (!put && strikePrice <= price)) {
exercised = true;
emit Exercised(price);
} else {
revert("Option.exercise: exercise conditions aren't met");
}
}
/// @dev Returns the smallest of two numbers.
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
// 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 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.5;
import {DateTime} from "./DateTime.sol";
// SAFEMATH DISCLAIMER:
// We and don't use SafeMath here intentionally, because input values are based on chars arithmetics
// and the results are used solely for display purposes (generating a token SYMBOL).
// Moreover - input data is provided only by contract owners, as creation of tokens is limited to owner only.
library GenSymbol {
function monthToHex(uint8 m) public pure returns (bytes1) {
if (m > 0 && m < 10) {
return bytes1(uint8(bytes1("0")) + m);
} else if (m >= 10 && m < 13) {
return bytes1(uint8(bytes1("A")) + (m - 10));
}
revert("Invalid month");
}
function tsToDate(uint256 _ts) public pure returns (string memory) {
bytes memory date = new bytes(4);
uint256 year = DateTime.getYear(_ts);
require(year >= 2020, "Year cannot be before 2020 as it is coded only by one digit");
require(year < 2030, "Year cannot be after 2029 as it is coded only by one digit");
date[0] = bytes1(
uint8(bytes1("0")) + uint8(year - 2020) // 2020 is coded as "0"
);
date[1] = monthToHex(DateTime.getMonth(_ts)); // October = 10 is coded by "A"
uint8 day = DateTime.getDay(_ts); // Day is just coded as a day of month starting from 1
require(day > 0 && day <= 31, "Invalid day");
date[2] = bytes1(uint8(bytes1("0")) + (day / 10));
date[3] = bytes1(uint8(bytes1("0")) + (day % 10));
return string(date);
}
function RKMconvert(uint256 _num) public pure returns (bytes memory) {
bytes memory map = "0000KKKMMMGGGTTTPPPEEEZZZYYY";
uint8 len;
uint256 i = _num;
while (i != 0) {
// Calculate the length of the input number
len++;
i /= 10;
}
bytes1 prefix = map[len]; // Get the prefix code letter
uint8 prefixPos = len > 3 ? ((len - 1) % 3) + 1 : 0; // Position of prefix (or 0 if the number is 3 digits or less)
// Get the leftmost 4 digits from input number or just take the number as is if its already 4 digits or less
uint256 firstFour = len > 4 ? _num / 10**(len - 4) : _num;
bytes memory bStr = "00000";
// We start from index 4 ^ of zero-string and go left
uint8 index = 4;
while (firstFour != 0) {
// If index is on prefix position - insert a prefix and decrease index
if (index == prefixPos) bStr[index--] = prefix;
bStr[index--] = bytes1(uint8(48 + (firstFour % 10)));
firstFour /= 10;
}
return bStr;
}
function uint2str(uint256 _num) public pure returns (bytes memory) {
if (_num > 99999) return RKMconvert(_num);
if (_num == 0) {
return "00000";
}
uint256 j = _num;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bStr = "00000";
uint256 k = 4;
while (_num != 0) {
bStr[k--] = bytes1(uint8(48 + (_num % 10)));
_num /= 10;
}
return bStr;
}
function genOptionSymbol(
uint256 _ts,
string memory _type,
bool put,
uint256 _strikePrice
) external pure returns (string memory) {
string memory putCall;
putCall = put ? "P" : "C";
return string(abi.encodePacked(_type, tsToDate(_ts), putCall, uint2str(_strikePrice)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/drafts/IERC20Permit.sol";
interface IOilerCollateral is IERC20, IERC20Permit {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
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_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../utils/ContextUpgradeable.sol";
import "./ERC20Upgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
using SafeMathUpgradeable for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.5 <0.8.0;
import "../token/ERC20/ERC20Upgradeable.sol";
import "./IERC20PermitUpgradeable.sol";
import "../cryptography/ECDSAUpgradeable.sol";
import "../utils/CountersUpgradeable.sol";
import "./EIP712Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping (address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal initializer {
__Context_init_unchained();
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory name) internal initializer {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// Stripped version of the following:
// https://github.com/pipermerriam/ethereum-datetime
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
// SAFEMATH DISCLAIMER:
// We and don't use SafeMath here intentionally, because all of the operations are basic arithmetics
// (we have introduced a limit of year 2100 to definitely fit into uint16, hoping Year2100-problem will not be our problem)
// and the results are used solely for display purposes (generating a token SYMBOL).
// Moreover - input data is provided only by contract owners, as creation of tokens is limited to owner only.
library DateTime {
struct _DateTime {
uint16 year;
uint8 month;
uint8 day;
}
uint256 constant DAY_IN_SECONDS = 86400; // leap second?
uint256 constant YEAR_IN_SECONDS = 31536000;
uint256 constant LEAP_YEAR_IN_SECONDS = 31622400;
uint16 constant ORIGIN_YEAR = 1970;
function isLeapYear(uint16 year) public pure returns (bool) {
if (year % 4 != 0) {
return false;
}
if (year % 100 != 0) {
return true;
}
if (year % 400 != 0) {
return false;
}
return true;
}
function leapYearsBefore(uint256 year) public pure returns (uint256) {
year -= 1;
return year / 4 - year / 100 + year / 400;
}
function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
return 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
}
function parseTimestamp(uint256 timestamp) public pure returns (_DateTime memory dt) {
uint256 secondsAccountedFor = 0;
uint256 buf;
uint8 i;
// Year
dt.year = getYear(timestamp);
buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;
secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);
// Month
uint256 secondsInMonth;
for (i = 1; i <= 12; i++) {
secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year);
if (secondsInMonth + secondsAccountedFor > timestamp) {
dt.month = i;
break;
}
secondsAccountedFor += secondsInMonth;
}
// Day
for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) {
if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) {
dt.day = i;
break;
}
secondsAccountedFor += DAY_IN_SECONDS;
}
}
function getYear(uint256 timestamp) public pure returns (uint16) {
require(timestamp < 4102444800, "Years after 2100 aren't supported for sanity and safety reasons");
uint256 secondsAccountedFor = 0;
uint16 year;
uint256 numLeapYears;
// Year
year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS);
numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears;
secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears);
while (secondsAccountedFor > timestamp) {
if (isLeapYear(uint16(year - 1))) {
secondsAccountedFor -= LEAP_YEAR_IN_SECONDS;
} else {
secondsAccountedFor -= YEAR_IN_SECONDS;
}
year -= 1;
}
return year;
}
function getMonth(uint256 timestamp) external pure returns (uint8) {
return parseTimestamp(timestamp).month;
}
function getDay(uint256 timestamp) external pure returns (uint8) {
return parseTimestamp(timestamp).day;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// 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.7.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 Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../math/SafeMathUpgradeable.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library CountersUpgradeable {
using SafeMathUpgradeable for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal initializer {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal initializer {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import {IBPool} from "./IBPool.sol";
interface IBRouter {
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountA,
uint256 amountB
) external returns (uint256 poolTokens);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 poolAmountIn
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint256 maxPrice
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
function getPoolByTokens(address tokenA, address tokenB) external view returns (IBPool pool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/drafts/IERC20Permit.sol";
import {IOilerCollateral} from "./IOilerCollateral.sol";
interface IOilerOptionBase is IERC20, IERC20Permit {
function optionType() external view returns (string memory);
function collateralInstance() external view returns (IOilerCollateral);
function isActive() external view returns (bool active);
function hasExpired() external view returns (bool);
function hasBeenExercised() external view returns (bool);
function put() external view returns (bool);
function write(uint256 _amount) external;
function write(uint256 _amount, address _writer) external;
function write(
uint256 _amount,
address _writer,
address _holder
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
interface IBPool {
function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint256 spotPrice);
function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint256 spotPrice);
function swapExactAmountIn(
address tokenIn,
uint256 tokenAmountIn,
address tokenOut,
uint256 minAmountOut,
uint256 maxPrice
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
function transferFrom(
address src,
address dst,
uint256 amt
) external returns (bool);
function approve(address dst, uint256 amt) external returns (bool);
function transfer(address dst, uint256 amt) external returns (bool);
function balanceOf(address whom) external view returns (uint256);
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external;
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external;
function finalize() external;
function rebind(
address token,
uint256 balance,
uint256 denorm
) external;
function setSwapFee(uint256 swapFee) external;
function setPublicSwap(bool publicSwap) external;
function bind(
address token,
uint256 balance,
uint256 denorm
) external;
function unbind(address token) external;
function gulp(address token) external;
function isBound(address token) external view returns (bool);
function getBalance(address token) external view returns (uint256);
function totalSupply() external view returns (uint256);
function getSwapFee() external view returns (uint256);
function isPublicSwap() external view returns (bool);
function getDenormalizedWeight(address token) external view returns (uint256);
function getTotalDenormalizedWeight() external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function EXIT_FEE() external view returns (uint256);
function calcPoolOutGivenSingleIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountIn,
uint256 swapFee
) external pure returns (uint256 poolAmountOut);
function calcSingleInGivenPoolOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountOut,
uint256 swapFee
) external pure returns (uint256 tokenAmountIn);
function calcSingleOutGivenPoolIn(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountIn,
uint256 swapFee
) external pure returns (uint256 tokenAmountOut);
function calcPoolInGivenSingleOut(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountOut,
uint256 swapFee
) external pure returns (uint256 poolAmountIn);
function getCurrentTokens() external view returns (address[] memory tokens);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IOilerOptionBaseFactory} from "./interfaces/IOilerOptionBaseFactory.sol";
import {IOilerOptionBase} from "./interfaces/IOilerOptionBase.sol";
import {IOilerOptionsRouter} from "./interfaces/IOilerOptionsRouter.sol";
contract OilerRegistry is Ownable {
uint256 public constant PUT = 1;
uint256 public constant CALL = 0;
/**
* @dev Active options store, once the option expires the mapping keys are replaced.
* option type => option contract.
*/
mapping(bytes32 => address[2]) public activeOptions;
/**
* @dev Archived options store.
* Once an option expires and is replaced it's pushed to an array under it's type key.
* option type => option contracts.
*/
mapping(bytes32 => address[]) public archivedOptions;
/**
* @dev Stores supported types of options.
*/
bytes32[] public optionTypes; // Array of all option types ever registered
/**
* @dev Indicates who's the factory of specific option types.
* option type => factory.
*/
mapping(bytes32 => address) public factories;
IOilerOptionsRouter public optionsRouter;
constructor(address _owner) Ownable() {
Ownable.transferOwnership(_owner);
}
function registerOption(address _optionAddress, string memory _optionType) external {
require(address(optionsRouter) != address(0), "OilerRegistry.registerOption: router not set");
bytes32 optionTypeHash = keccak256(abi.encodePacked(_optionType));
// Check if caller is factory registered for current option.
require(factories[optionTypeHash] == msg.sender, "OilerRegistry.registerOption: not a factory."); // Ensure that contract under address is an option.
require(
IOilerOptionBaseFactory(msg.sender).isClone(_optionAddress),
"OilerRegistry.registerOption: invalid option contract."
);
uint256 optionDirection = IOilerOptionBase(_optionAddress).put() ? PUT : CALL;
// Ensure option is not being registered again.
require(
_optionAddress != activeOptions[optionTypeHash][optionDirection],
"OilerRegistry.registerOption: option already registered"
);
// Ensure currently set option is expired.
if (activeOptions[optionTypeHash][optionDirection] != address(0)) {
require(
!IOilerOptionBase(activeOptions[optionTypeHash][optionDirection]).isActive(),
"OilerRegistry.registerOption: option still active"
);
}
archivedOptions[optionTypeHash].push(activeOptions[optionTypeHash][optionDirection]);
activeOptions[optionTypeHash][optionDirection] = _optionAddress;
optionsRouter.setUnlimitedApprovals(IOilerOptionBase(_optionAddress));
}
function setOptionsTypeFactory(string memory _optionType, address _factory) external onlyOwner {
bytes32 optionTypeHash = keccak256(abi.encodePacked(_optionType));
require(_factory != address(0), "Cannot set factory to 0x0");
require(factories[optionTypeHash] != address(0), "OptionType wasn't yet registered");
if (_factory != address(uint256(-1))) {
// Send -1 if you want to remove the factory and disable this optionType
require(
optionTypeHash ==
keccak256(
abi.encodePacked(
IOilerOptionBase(IOilerOptionBaseFactory(_factory).optionLogicImplementation()).optionType()
)
),
"The factory is for different optionType"
);
}
factories[optionTypeHash] = _factory;
}
function registerFactory(address factory) external onlyOwner {
bytes32 optionTypeHash = keccak256(
abi.encodePacked(
IOilerOptionBase(IOilerOptionBaseFactory(factory).optionLogicImplementation()).optionType()
)
);
require(factories[optionTypeHash] == address(0), "The factory for this OptionType was already registered");
factories[optionTypeHash] = factory;
optionTypes.push(optionTypeHash);
}
function setOptionsRouter(IOilerOptionsRouter _optionsRouter) external onlyOwner {
optionsRouter = _optionsRouter;
}
function getOptionTypesLength() external view returns (uint256) {
return optionTypes.length;
}
function getOptionTypeAt(uint256 _index) external view returns (bytes32) {
return optionTypes[_index];
}
function getOptionTypeFactory(string memory _optionType) external view returns (address) {
return factories[keccak256(abi.encodePacked(_optionType))];
}
function getAllArchivedOptionsOfType(bytes32 _optionType) external view returns (address[] memory) {
return archivedOptions[_optionType];
}
function getAllArchivedOptionsOfType(string memory _optionType) external view returns (address[] memory) {
return archivedOptions[keccak256(abi.encodePacked(_optionType))];
}
function checkActive(string memory _optionType) public view returns (bool, bool) {
bytes32 id = keccak256(abi.encodePacked(_optionType));
return checkActive(id);
}
function checkActive(bytes32 _optionType) public view returns (bool, bool) {
return (
activeOptions[_optionType][CALL] != address(0)
? IOilerOptionBase(activeOptions[_optionType][CALL]).isActive()
: false,
activeOptions[_optionType][PUT] != address(0)
? IOilerOptionBase(activeOptions[_optionType][PUT]).isActive()
: false
);
}
function getActiveOptions(bytes32 _optionType) public view returns (address[2] memory result) {
(bool isCallActive, bool isPutActive) = checkActive(_optionType);
if (isCallActive) {
result[0] = activeOptions[_optionType][0];
}
if (isPutActive) {
result[1] = activeOptions[_optionType][1];
}
}
function getActiveOptions(string memory _optionType) public view returns (address[2] memory result) {
return getActiveOptions(keccak256(abi.encodePacked(_optionType)));
}
function getArchivedOptions(bytes32 _optionType) public view returns (address[] memory result) {
(bool isCallActive, bool isPutActive) = checkActive(_optionType);
uint256 extraLength = 0;
if (!isCallActive) {
extraLength++;
}
if (!isPutActive) {
extraLength++;
}
uint256 archivedLength = getArchivedOptionsLength(_optionType);
result = new address[](archivedLength + extraLength);
for (uint256 i = 0; i < archivedLength; i++) {
result[i] = archivedOptions[_optionType][i];
}
uint256 cursor;
if (!isCallActive) {
result[archivedLength + cursor++] = activeOptions[_optionType][0];
}
if (!isPutActive) {
result[archivedLength + cursor++] = activeOptions[_optionType][1];
}
return result;
}
function getArchivedOptions(string memory _optionType) public view returns (address[] memory result) {
return getArchivedOptions(keccak256(abi.encodePacked(_optionType)));
}
function getArchivedOptionsLength(string memory _optionType) public view returns (uint256) {
return archivedOptions[keccak256(abi.encodePacked(_optionType))].length;
}
function getArchivedOptionsLength(bytes32 _optionType) public view returns (uint256) {
return archivedOptions[_optionType].length;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
// TODO rename CloneFactory.
contract ProxyFactory {
function _createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
function _isClone(address target, address query) internal view returns (bool result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)
mstore(add(clone, 0xa), targetBytes)
mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))))
}
}
}
// 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.5;
interface IOilerOptionBaseFactory {
function optionLogicImplementation() external view returns (address);
function isClone(address _query) external view returns (bool);
function createOption(
uint256 _strikePrice,
uint256 _expiryTS,
bool _put,
address _collateral,
uint256 _collateralToPushIntoAmount,
uint256 _optionsToPushIntoPool
) external returns (address optionAddress);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "./IOilerOptionBase.sol";
import "./IOilerRegistry.sol";
import "./IBRouter.sol";
interface IOilerOptionsRouter {
// TODO add expiration?
struct Permit {
uint8 v;
bytes32 r;
bytes32 s;
}
function registry() external view returns (IOilerRegistry);
function bRouter() external view returns (IBRouter);
function setUnlimitedApprovals(IOilerOptionBase _option) external;
function write(IOilerOptionBase _option, uint256 _amount) external;
function write(
IOilerOptionBase _option,
uint256 _amount,
Permit calldata _permit
) external;
function writeAndAddLiquidity(
IOilerOptionBase _option,
uint256 _amount,
uint256 _liquidityProviderCollateralAmount
) external;
function writeAndAddLiquidity(
IOilerOptionBase _option,
uint256 _amount,
uint256 _liquidityProviderCollateralAmount,
Permit calldata _writePermit,
Permit calldata _liquidityAddPermit
) external;
}
// 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.5;
import "./IOilerOptionsRouter.sol";
interface IOilerRegistry {
function PUT() external view returns (uint256);
function CALL() external view returns (uint256);
function activeOptions(bytes32 _type) external view returns (address[2] memory);
function archivedOptions(bytes32 _type, uint256 _index) external view returns (address);
function optionTypes(uint256 _index) external view returns (bytes32);
function factories(bytes32 _optionType) external view returns (address);
function optionsRouter() external view returns (IOilerOptionsRouter);
function getOptionTypesLength() external view returns (uint256);
function getOptionTypeAt(uint256 _index) external view returns (bytes32);
function getArchivedOptionsLength(string memory _optionType) external view returns (uint256);
function getArchivedOptionsLength(bytes32 _optionType) external view returns (uint256);
function getOptionTypeFactory(string memory _optionType) external view returns (address);
function getAllArchivedOptionsOfType(string memory _optionType) external view returns (address[] memory);
function getAllArchivedOptionsOfType(bytes32 _optionType) external view returns (address[] memory);
function registerFactory(address factory) external;
function setOptionsTypeFactory(string memory _optionType, address _factory) external;
function registerOption(address _optionAddress, string memory _optionType) external;
function setOptionsRouter(IOilerOptionsRouter _optionsRouter) external;
}
|
solhint-disable-next-line func-name-mixedcase
|
interface IBPool {
function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint256 spotPrice);
function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint256 spotPrice);
function swapExactAmountIn(
address tokenIn,
uint256 tokenAmountIn,
address tokenOut,
uint256 minAmountOut,
uint256 maxPrice
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
function transferFrom(
address src,
address dst,
uint256 amt
) external returns (bool);
function approve(address dst, uint256 amt) external returns (bool);
function transfer(address dst, uint256 amt) external returns (bool);
function balanceOf(address whom) external view returns (uint256);
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external;
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external;
function finalize() external;
function rebind(
address token,
uint256 balance,
uint256 denorm
) external;
function setSwapFee(uint256 swapFee) external;
function setPublicSwap(bool publicSwap) external;
function bind(
address token,
uint256 balance,
uint256 denorm
) external;
function unbind(address token) external;
function gulp(address token) external;
function isBound(address token) external view returns (bool);
function getBalance(address token) external view returns (uint256);
function totalSupply() external view returns (uint256);
function getSwapFee() external view returns (uint256);
function isPublicSwap() external view returns (bool);
function getDenormalizedWeight(address token) external view returns (uint256);
function getTotalDenormalizedWeight() external view returns (uint256);
function EXIT_FEE() external view returns (uint256);
function calcPoolOutGivenSingleIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountIn,
uint256 swapFee
) external pure returns (uint256 poolAmountOut);
function calcSingleInGivenPoolOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountOut,
uint256 swapFee
) external pure returns (uint256 tokenAmountIn);
function calcSingleOutGivenPoolIn(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountIn,
uint256 swapFee
) external pure returns (uint256 tokenAmountOut);
function calcPoolInGivenSingleOut(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountOut,
uint256 swapFee
) external pure returns (uint256 poolAmountIn);
function getCurrentTokens() external view returns (address[] memory tokens);
pragma solidity 0.7.5;
}
| 1,250,917 |
[
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
1326,
17,
529,
17,
19562,
3593,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
5831,
23450,
2864,
288,
203,
565,
445,
1322,
13130,
5147,
12,
2867,
1147,
382,
16,
1758,
1147,
1182,
13,
3903,
1476,
1135,
261,
11890,
5034,
16463,
5147,
1769,
203,
203,
565,
445,
1322,
13130,
5147,
55,
634,
14667,
12,
2867,
1147,
382,
16,
1758,
1147,
1182,
13,
3903,
1476,
1135,
261,
11890,
5034,
16463,
5147,
1769,
203,
203,
565,
445,
7720,
14332,
6275,
382,
12,
203,
3639,
1758,
1147,
382,
16,
203,
3639,
2254,
5034,
1147,
6275,
382,
16,
203,
3639,
1758,
1147,
1182,
16,
203,
3639,
2254,
5034,
1131,
6275,
1182,
16,
203,
3639,
2254,
5034,
943,
5147,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
1147,
6275,
1182,
16,
2254,
5034,
16463,
5147,
4436,
1769,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
1705,
16,
203,
3639,
1758,
3046,
16,
203,
3639,
2254,
5034,
25123,
203,
565,
262,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
6617,
537,
12,
2867,
3046,
16,
2254,
5034,
25123,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
7412,
12,
2867,
3046,
16,
2254,
5034,
25123,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
600,
362,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
1233,
2864,
12,
11890,
5034,
2845,
6275,
1182,
16,
2254,
5034,
8526,
745,
892,
943,
6275,
87,
382,
13,
3903,
31,
203,
203,
565,
445,
2427,
2864,
12,
11890,
5034,
2845,
6275,
382,
16,
2254,
5034,
8526,
745,
892,
1131,
6275,
87,
1182,
13,
3903,
31,
203,
203,
2
] |
pragma solidity ^0.6.0;
interface OneInchInterace {
function SWAP825( //inject NONSTANDARD NAMING
TokenInterface fromToken,
TokenInterface toToken,
uint256 fromTokenAmount,
uint256 minReturnAmount,
uint256 guaranteedAmount,
address payable referrer,
address[] calldata callAddresses,
bytes calldata callDataConcat,
uint256[] calldata starts,
uint256[] calldata gasLimitsAndValues
)
external
payable
returns (uint256 returnAmount);
}
interface OneSplitInterface {
function SWAP825( //inject NONSTANDARD NAMING
TokenInterface fromToken,
TokenInterface toToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution, // [Uniswap, Kyber, Bancor, Oasis]
uint256 disableFlags // 16 - Compound, 32 - Fulcrum, 64 - Chai, 128 - Aave, 256 - SmartToken, 1024 - bDAI
) external payable;
function GETEXPECTEDRETURN114( //inject NONSTANDARD NAMING
TokenInterface fromToken,
TokenInterface toToken,
uint256 amount,
uint256 parts,
uint256 disableFlags
)
external
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
interface TokenInterface {
function ALLOWANCE188(address, address) external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF858(address) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE753(address, uint) external; //inject NONSTANDARD NAMING
function TRANSFER276(address, uint) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM312(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING
function DECIMALS820() external view returns (uint); //inject NONSTANDARD NAMING
}
interface MemoryInterface {
function GETUINT570(uint _id) external returns (uint _num); //inject NONSTANDARD NAMING
function SETUINT148(uint _id, uint _val) external; //inject NONSTANDARD NAMING
}
interface EventInterface {
function EMITEVENT19(uint _connectorType, uint _connectorID, bytes32 _eventCode, bytes calldata _eventData) external; //inject NONSTANDARD NAMING
}
contract DSMath {
function ADD467(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require((z = x + y) >= x, "math-not-safe");
}
function MUL202(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require(y == 0 || (z = x * y) / y == x, "math-not-safe");
}
function SUB93(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require((z = x - y) <= x, "sub-overflow");
}
uint constant wad990 = 10 ** 18; //inject NONSTANDARD NAMING
function WMUL381(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD467(MUL202(x, y), wad990 / 2) / wad990;
}
function WDIV159(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD467(MUL202(x, wad990), y / 2) / y;
}
}
contract Helpers is DSMath {
function GETADDRESSETH223() internal pure returns (address) { //inject NONSTANDARD NAMING
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
function GETMEMORYADDR657() internal pure returns (address) { //inject NONSTANDARD NAMING
return 0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F; // InstaMemory Address
}
function GETEVENTADDR661() internal pure returns (address) { //inject NONSTANDARD NAMING
return 0x2af7ea6Cb911035f3eb1ED895Cb6692C39ecbA97; // InstaEvent Address
}
function GETUINT570(uint getId, uint val) internal returns (uint returnVal) { //inject NONSTANDARD NAMING
returnVal = getId == 0 ? val : MemoryInterface(GETMEMORYADDR657()).GETUINT570(getId);
}
function SETUINT148(uint setId, uint val) internal { //inject NONSTANDARD NAMING
if (setId != 0) MemoryInterface(GETMEMORYADDR657()).SETUINT148(setId, val);
}
function CONNECTORID229() public pure returns(uint _type, uint _id) { //inject NONSTANDARD NAMING
(_type, _id) = (1, 0);
}
}
contract OneHelpers is Helpers {
function GETONEINCHADDRESS220() internal pure returns (address) { //inject NONSTANDARD NAMING
return 0x11111254369792b2Ca5d084aB5eEA397cA8fa48B;
}
function GETONESPLITADDRESS198() internal pure returns (address) { //inject NONSTANDARD NAMING
return 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E;
}
function CONVERT18TODEC400(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { //inject NONSTANDARD NAMING
amt = (_amt / 10 ** (18 - _dec));
}
function CONVERTTO18876(uint _dec, uint256 _amt) internal pure returns (uint256 amt) { //inject NONSTANDARD NAMING
amt = MUL202(_amt, 10 ** (18 - _dec));
}
function GETTOKENBAL256(TokenInterface token) internal view returns(uint _amt) { //inject NONSTANDARD NAMING
_amt = address(token) == GETADDRESSETH223() ? address(this).balance : token.BALANCEOF858(address(this));
}
function CONVERTDIV928(uint xDec, uint yDec, uint x, uint y) internal pure returns(uint z) { //inject NONSTANDARD NAMING
z = WDIV159(CONVERTTO18876(xDec, x), CONVERTTO18876(yDec, y));
}
function GETTOKENSDEC993(TokenInterface buyAddr, TokenInterface sellAddr) internal view returns(uint buyDec, uint sellDec) { //inject NONSTANDARD NAMING
buyDec = address(buyAddr) == GETADDRESSETH223() ? 18 : buyAddr.DECIMALS820();
sellDec = address(sellAddr) == GETADDRESSETH223() ? 18 : sellAddr.DECIMALS820();
}
function DECODEDATA941( //inject NONSTANDARD NAMING
bytes memory data
)
internal pure returns (
address buyAddr,
address sellAddr,
uint256 fromTokenAmount
)
{
bytes memory _data = data;
// solium-disable-next-line security/no-inline-assembly
assembly {
sellAddr := mload(add(_data, 36))
buyAddr := mload(add(_data, 68))
fromTokenAmount := mload(add(_data, 100))
}
}
}
contract Resolver is OneHelpers {
function ONESPLITSWAP198( //inject NONSTANDARD NAMING
TokenInterface _sellAddr,
TokenInterface _buyAddr,
uint _sellAmt,
uint unitAmt
) internal returns (uint buyAmt, uint[] memory distribution){
(uint _buyDec, uint _sellDec) = GETTOKENSDEC993(_buyAddr, _sellAddr);
uint _sellAmt18 = CONVERTTO18876(_sellDec, _sellAmt);
uint _slippageAmt = CONVERT18TODEC400(_buyDec, WMUL381(unitAmt, _sellAmt18));
OneSplitInterface oneSplitContract = OneSplitInterface(GETONESPLITADDRESS198());
(buyAmt, distribution) = oneSplitContract.GETEXPECTEDRETURN114(
_sellAddr,
_buyAddr,
_sellAmt,
3, // TODO - shall we hardcode?
0 // TODO - do we need to disable anything?
);
require(_slippageAmt <= buyAmt, "Too much slippage");
uint ethAmt;
if (address(_sellAddr) == GETADDRESSETH223()) {
ethAmt = _sellAmt;
} else {
_sellAddr.APPROVE753(address(oneSplitContract), _sellAmt);
}
oneSplitContract.SWAP825.value(ethAmt)(
_sellAddr,
_buyAddr,
_sellAmt,
_slippageAmt,
distribution,
0
);
}
function ONEINCHSWAP661( //inject NONSTANDARD NAMING
bytes memory _callData,
uint ethAmt
)
internal returns (uint buyAmt) {
// solium-disable-next-line security/no-call-value
(bool success, bytes memory data) = address(GETONEINCHADDRESS220()).call.value(ethAmt)(_callData);
if (!success) revert("1Inch-swap-failed");
buyAmt = abi.decode(data, (uint));
}
}
contract BasicResolver is Resolver {
event LOGSELLONEINCH128( //inject NONSTANDARD NAMING
address indexed buyToken,
address indexed sellToken,
uint256 buyAmt,
uint256 sellAmt,
uint256 setId
);
event LOGSELLONESPLIT850( //inject NONSTANDARD NAMING
address indexed buyToken,
address indexed sellToken,
uint256 buyAmt,
uint256 sellAmt,
uint256 getId,
uint256 setId
);
function SELL42( //inject NONSTANDARD NAMING
address buyAddr,
address sellAddr,
uint sellAmt,
uint unitAmt,
uint getId,
uint setId
) external payable {
uint _sellAmt = sellAmt;
TokenInterface _buyAddr = TokenInterface(buyAddr);
TokenInterface _sellAddr = TokenInterface(sellAddr);
uint initalBal = GETTOKENBAL256(_buyAddr);
_sellAmt = _sellAmt == uint(-1) ? GETTOKENBAL256(_sellAddr) : _sellAmt;
ONESPLITSWAP198(
_sellAddr,
_buyAddr,
_sellAmt,
unitAmt
);
uint finialBal = GETTOKENBAL256(_buyAddr);
uint _buyAmt = SUB93(finialBal, initalBal);
// setUint(setId, _buyAmt);
emit LOGSELLONESPLIT850(address(_buyAddr), address(_sellAddr), _buyAmt, _sellAmt, getId, setId);
}
function SELL42( //inject NONSTANDARD NAMING
bytes calldata callData,
uint setId
) external payable {
(address _buyAddr, address _sellAddr, uint sellAmt) = DECODEDATA941(callData);
uint ethAmt;
if (address(_sellAddr) == GETADDRESSETH223()) {
ethAmt = sellAmt;
} else {
TokenInterface(_sellAddr).APPROVE753(GETONEINCHADDRESS220(), sellAmt);
}
uint _buyAmt = ONEINCHSWAP661(callData, ethAmt);
// setUint(setId, _buyAmt);
emit LOGSELLONEINCH128(address(_buyAddr), address(_sellAddr), _buyAmt, sellAmt, setId);
}
}
|
inject NONSTANDARD NAMING
|
function MUL202(uint x, uint y) internal pure returns (uint z) {
| 13,006,924 |
[
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
490,
1506,
18212,
12,
11890,
619,
16,
2254,
677,
13,
2713,
16618,
1135,
261,
11890,
998,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* @authors: [@mtsalenc]
* @reviewers: [@clesaege]
* @auditors: []
* @bounties: []
* @deployments: []
*/
pragma solidity 0.5.17;
/**
* @title CappedMath
* @dev Math operations with caps for under and overflow.
*/
library CappedMath {
uint constant private UINT_MAX = 2**256 - 1;
/**
* @dev Adds two unsigned integers, returns 2^256 - 1 on overflow.
*/
function addCap(uint _a, uint _b) internal pure returns (uint) {
uint c = _a + _b;
return c >= _a ? c : UINT_MAX;
}
/**
* @dev Subtracts two integers, returns 0 on underflow.
*/
function subCap(uint _a, uint _b) internal pure returns (uint) {
if (_b > _a)
return 0;
else
return _a - _b;
}
/**
* @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow.
*/
function mulCap(uint _a, uint _b) internal pure returns (uint) {
// Gas optimization: this is cheaper than requiring '_a' not being zero, but the
// benefit is lost if '_b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0)
return 0;
uint c = _a * _b;
return c / _a == _b ? c : UINT_MAX;
}
}
/**
* @authors: [@hbarcelos]
* @reviewers: [@fnanni-0]
* @auditors: []
* @bounties: []
* @deployments: []
*/
/**
* @title CappedMath
* @dev Math operations with caps for under and overflow.
*/
library CappedMath128 {
uint128 private constant UINT128_MAX = 2**128 - 1;
/**
* @dev Adds two unsigned integers, returns 2^128 - 1 on overflow.
*/
function addCap(uint128 _a, uint128 _b) internal pure returns (uint128) {
uint128 c = _a + _b;
return c >= _a ? c : UINT128_MAX;
}
/**
* @dev Subtracts two integers, returns 0 on underflow.
*/
function subCap(uint128 _a, uint128 _b) internal pure returns (uint128) {
if (_b > _a) return 0;
else return _a - _b;
}
/**
* @dev Multiplies two unsigned integers, returns 2^128 - 1 on overflow.
*/
function mulCap(uint128 _a, uint128 _b) internal pure returns (uint128) {
if (_a == 0) return 0;
uint128 c = _a * _b;
return c / _a == _b ? c : UINT128_MAX;
}
}
/**
* @authors: [@ferittuncer]
* @reviewers: [@remedcu]
* @auditors: []
* @bounties: []
* @deployments: []
*/
/** @title IArbitrable
* Arbitrable interface.
* When developing arbitrable contracts, we need to:
* -Define the action taken when a ruling is received by the contract.
* -Allow dispute creation. For this a function must call arbitrator.createDispute.value(_fee)(_choices,_extraData);
*/
interface IArbitrable {
/** @dev To be raised when a ruling is given.
* @param _arbitrator The arbitrator giving the ruling.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling The ruling which was given.
*/
event Ruling(IArbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling);
/** @dev Give a ruling for a dispute. Must be called by the arbitrator.
* The purpose of this function is to ensure that the address calling it has the right to rule on the contract.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Not able/wanting to make a decision".
*/
function rule(uint _disputeID, uint _ruling) external;
}
/**
* @authors: [@ferittuncer]
* @reviewers: [@remedcu]
* @auditors: []
* @bounties: []
* @deployments: []
*/
/** @title Arbitrator
* Arbitrator abstract contract.
* When developing arbitrator contracts we need to:
* -Define the functions for dispute creation (createDispute) and appeal (appeal). Don't forget to store the arbitrated contract and the disputeID (which should be unique, may nbDisputes).
* -Define the functions for cost display (arbitrationCost and appealCost).
* -Allow giving rulings. For this a function must call arbitrable.rule(disputeID, ruling).
*/
interface IArbitrator {
enum DisputeStatus {Waiting, Appealable, Solved}
/** @dev To be emitted when a dispute is created.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event DisputeCreation(uint indexed _disputeID, IArbitrable indexed _arbitrable);
/** @dev To be emitted when a dispute can be appealed.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event AppealPossible(uint indexed _disputeID, IArbitrable indexed _arbitrable);
/** @dev To be emitted when the current ruling is appealed.
* @param _disputeID ID of the dispute.
* @param _arbitrable The contract which created the dispute.
*/
event AppealDecision(uint indexed _disputeID, IArbitrable indexed _arbitrable);
/** @dev Create a dispute. Must be called by the arbitrable contract.
* Must be paid at least arbitrationCost(_extraData).
* @param _choices Amount of choices the arbitrator can make in this dispute.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return disputeID ID of the dispute created.
*/
function createDispute(uint _choices, bytes calldata _extraData) external payable returns(uint disputeID);
/** @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return cost Amount to be paid.
*/
function arbitrationCost(bytes calldata _extraData) external view returns(uint cost);
/** @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule.
* @param _disputeID ID of the dispute to be appealed.
* @param _extraData Can be used to give extra info on the appeal.
*/
function appeal(uint _disputeID, bytes calldata _extraData) external payable;
/** @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation.
* @param _disputeID ID of the dispute to be appealed.
* @param _extraData Can be used to give additional info on the dispute to be created.
* @return cost Amount to be paid.
*/
function appealCost(uint _disputeID, bytes calldata _extraData) external view returns(uint cost);
/** @dev Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0).
* @param _disputeID ID of the dispute.
* @return start The start of the period.
* @return end The end of the period.
*/
function appealPeriod(uint _disputeID) external view returns(uint start, uint end);
/** @dev Return the status of a dispute.
* @param _disputeID ID of the dispute to rule.
* @return status The status of the dispute.
*/
function disputeStatus(uint _disputeID) external view returns(DisputeStatus status);
/** @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal.
* @param _disputeID ID of the dispute.
* @return ruling The ruling which has been given or the one which will be given if there is no appeal.
*/
function currentRuling(uint _disputeID) external view returns(uint ruling);
}
/** @title IEvidence
* ERC-1497: Evidence Standard
*/
interface IEvidence {
/** @dev To be emitted when meta-evidence is submitted.
* @param _metaEvidenceID Unique identifier of meta-evidence.
* @param _evidence A link to the meta-evidence JSON.
*/
event MetaEvidence(uint indexed _metaEvidenceID, string _evidence);
/** @dev To be raised when evidence is submitted. Should point to the resource (evidences are not to be stored on chain due to gas considerations).
* @param _arbitrator The arbitrator of the contract.
* @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to.
* @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party.
* @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json.
*/
event Evidence(IArbitrator indexed _arbitrator, uint indexed _evidenceGroupID, address indexed _party, string _evidence);
/** @dev To be emitted when a dispute is created to link the correct meta-evidence to the disputeID.
* @param _arbitrator The arbitrator of the contract.
* @param _disputeID ID of the dispute in the Arbitrator contract.
* @param _metaEvidenceID Unique identifier of meta-evidence.
* @param _evidenceGroupID Unique identifier of the evidence group that is linked to this dispute.
*/
event Dispute(IArbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID, uint _evidenceGroupID);
}
/**
* @authors: [@unknownunknown1*, @mtsalenc*, @hbarcelos*]
* @reviewers: [@fnanni-0*, @greenlucid, @shalzz]
* @auditors: []
* @bounties: []
* @deployments: []
*/
/**
* @title LightGeneralizedTCR
* This contract is a curated registry for any types of items. Just like a TCR contract it features the request-challenge protocol and appeal fees crowdfunding.
* The difference between LightGeneralizedTCR and GeneralizedTCR is that instead of storing item data in storage and event logs, LightCurate only stores the URI of item in the logs. This makes it considerably cheaper to use and allows more flexibility with the item columns.
*/
contract LightGeneralizedTCR is IArbitrable, IEvidence {
using CappedMath for uint256;
using CappedMath128 for uint128;
/* Enums */
enum Status {
Absent, // The item is not in the registry.
Registered, // The item is in the registry.
RegistrationRequested, // The item has a request to be added to the registry.
ClearingRequested // The item has a request to be removed from the registry.
}
enum Party {
None, // Party per default when there is no challenger or requester. Also used for unconclusive ruling.
Requester, // Party that made the request to change a status.
Challenger // Party that challenges the request to change a status.
}
enum RequestType {
Registration, // Identifies a request to register an item to the registry.
Clearing // Identifies a request to remove an item from the registry.
}
enum DisputeStatus {
None, // No dispute was created.
AwaitingRuling, // Dispute was created, but the final ruling was not given yet.
Resolved // Dispute was ruled.
}
/* Structs */
struct Item {
Status status; // The current status of the item.
uint128 sumDeposit; // The total deposit made by the requester and the challenger (if any).
uint120 requestCount; // The number of requests.
mapping(uint256 => Request) requests; // List of status change requests made for the item in the form requests[requestID].
}
// Arrays with 3 elements map with the Party enum for better readability:
// - 0: is unused, matches `Party.None`.
// - 1: for `Party.Requester`.
// - 2: for `Party.Challenger`.
struct Request {
RequestType requestType;
uint64 submissionTime; // Time when the request was made. Used to track when the challenge period ends.
uint24 arbitrationParamsIndex; // The index for the arbitration params for the request.
address payable requester; // Address of the requester.
// Pack the requester together with the other parameters, as they are written in the same request.
address payable challenger; // Address of the challenger, if any.
}
struct DisputeData {
uint256 disputeID; // The ID of the dispute on the arbitrator.
DisputeStatus status; // The current status of the dispute.
Party ruling; // The ruling given to a dispute. Only set after it has been resolved.
uint240 roundCount; // The number of rounds.
mapping(uint256 => Round) rounds; // Data of the different dispute rounds. rounds[roundId].
}
struct Round {
Party sideFunded; // Stores the side that successfully paid the appeal fees in the latest round. Note that if both sides have paid a new round is created.
uint256 feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute.
uint256[3] amountPaid; // Tracks the sum paid for each Party in this round.
mapping(address => uint256[3]) contributions; // Maps contributors to their contributions for each side in the form contributions[address][party].
}
struct ArbitrationParams {
IArbitrator arbitrator; // The arbitrator trusted to solve disputes for this request.
bytes arbitratorExtraData; // The extra data for the trusted arbitrator of this request.
}
/* Constants */
uint256 public constant RULING_OPTIONS = 2; // The amount of non 0 choices the arbitrator can give.
uint256 private constant RESERVED_ROUND_ID = 0; // For compatibility with GeneralizedTCR consider the request/challenge cycle the first round (index 0).
/* Storage */
bool private initialized;
address public relayerContract; // The contract that is used to add or remove items directly to speed up the interchain communication.
address public governor; // The address that can make changes to the parameters of the contract.
uint256 public submissionBaseDeposit; // The base deposit to submit an item.
uint256 public removalBaseDeposit; // The base deposit to remove an item.
uint256 public submissionChallengeBaseDeposit; // The base deposit to challenge a submission.
uint256 public removalChallengeBaseDeposit; // The base deposit to challenge a removal request.
uint256 public challengePeriodDuration; // The time after which a request becomes executable if not challenged.
// Multipliers are in basis points.
uint256 public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round.
uint256 public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round.
uint256 public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where arbitrator refused to arbitrate.
uint256 public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers.
mapping(bytes32 => Item) public items; // Maps the item ID to its data in the form items[_itemID].
mapping(address => mapping(uint256 => bytes32)) public arbitratorDisputeIDToItemID; // Maps a dispute ID to the ID of the item with the disputed request in the form arbitratorDisputeIDToItemID[arbitrator][disputeID].
mapping(bytes32 => mapping(uint256 => DisputeData)) public requestsDisputeData; // Maps an item and a request to the data of the dispute related to them. requestsDisputeData[itemID][requestIndex]
ArbitrationParams[] public arbitrationParamsChanges;
/* Modifiers */
modifier onlyGovernor() {
require(msg.sender == governor, "The caller must be the governor.");
_;
}
modifier onlyRelayer() {
require(msg.sender == relayerContract, "The caller must be the relay.");
_;
}
/* Events */
/**
* @dev Emitted when a party makes a request, raises a dispute or when a request is resolved.
* @param _itemID The ID of the affected item.
* @param _updatedDirectly Whether this was emitted in either `addItemDirectly` or `removeItemDirectly`. This is used in the subgraph.
*/
event ItemStatusChange(bytes32 indexed _itemID, bool _updatedDirectly);
/**
* @dev Emitted when someone submits an item for the first time.
* @param _itemID The ID of the new item.
* @param _data The item data URI.
* @param _addedDirectly Whether the item was added via `addItemDirectly`.
*/
event NewItem(bytes32 indexed _itemID, string _data, bool _addedDirectly);
/**
* @dev Emitted when someone submits a request.
* @param _itemID The ID of the affected item.
* @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to.
*/
event RequestSubmitted(bytes32 indexed _itemID, uint256 _evidenceGroupID);
/**
* @dev Emitted when a party contributes to an appeal. The roundID assumes the initial request and challenge deposits are the first round. This is done so indexers can know more information about the contribution without using call handlers.
* @param _itemID The ID of the item.
* @param _requestID The index of the request that received the contribution.
* @param _roundID The index of the round that received the contribution.
* @param _contributor The address making the contribution.
* @param _contribution How much of the contribution was accepted.
* @param _side The party receiving the contribution.
*/
event Contribution(
bytes32 indexed _itemID,
uint256 _requestID,
uint256 _roundID,
address indexed _contributor,
uint256 _contribution,
Party _side
);
/**
* @dev Emitted when the address of the connected TCR is set. The connected TCR is an instance of the Generalized TCR contract where each item is the address of a TCR related to this one.
* @param _connectedTCR The address of the connected TCR.
*/
event ConnectedTCRSet(address indexed _connectedTCR);
/**
* @dev Emitted when someone withdraws more than 0 rewards.
* @param _beneficiary The address that made contributions to a request.
* @param _itemID The ID of the item submission to withdraw from.
* @param _request The request from which to withdraw.
* @param _round The round from which to withdraw.
* @param _reward The amount withdrawn.
*/
event RewardWithdrawn(
address indexed _beneficiary,
bytes32 indexed _itemID,
uint256 _request,
uint256 _round,
uint256 _reward
);
/**
* @dev Initialize the arbitrable curated registry.
* @param _arbitrator Arbitrator to resolve potential disputes. The arbitrator is trusted to support appeal periods and not reenter.
* @param _arbitratorExtraData Extra data for the trusted arbitrator contract.
* @param _connectedTCR The address of the TCR that stores related TCR addresses. This parameter can be left empty.
* @param _registrationMetaEvidence The URI of the meta evidence object for registration requests.
* @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests.
* @param _governor The trusted governor of this contract.
* @param _baseDeposits The base deposits for requests/challenges as follows:
* - The base deposit to submit an item.
* - The base deposit to remove an item.
* - The base deposit to challenge a submission.
* - The base deposit to challenge a removal request.
* @param _challengePeriodDuration The time in seconds parties have to challenge a request.
* @param _stakeMultipliers Multipliers of the arbitration cost in basis points (see MULTIPLIER_DIVISOR) as follows:
* - The multiplier applied to each party's fee stake for a round when there is no winner/loser in the previous round (e.g. when the arbitrator refused to arbitrate).
* - The multiplier applied to the winner's fee stake for the subsequent round.
* - The multiplier applied to the loser's fee stake for the subsequent round.
* @param _relayerContract The address of the relay contract to add/remove items directly.
*/
function initialize(
IArbitrator _arbitrator,
bytes calldata _arbitratorExtraData,
address _connectedTCR,
string calldata _registrationMetaEvidence,
string calldata _clearingMetaEvidence,
address _governor,
uint256[4] calldata _baseDeposits,
uint256 _challengePeriodDuration,
uint256[3] calldata _stakeMultipliers,
address _relayerContract
) external {
require(!initialized, "Already initialized.");
emit ConnectedTCRSet(_connectedTCR);
governor = _governor;
submissionBaseDeposit = _baseDeposits[0];
removalBaseDeposit = _baseDeposits[1];
submissionChallengeBaseDeposit = _baseDeposits[2];
removalChallengeBaseDeposit = _baseDeposits[3];
challengePeriodDuration = _challengePeriodDuration;
sharedStakeMultiplier = _stakeMultipliers[0];
winnerStakeMultiplier = _stakeMultipliers[1];
loserStakeMultiplier = _stakeMultipliers[2];
relayerContract = _relayerContract;
_doChangeArbitrationParams(_arbitrator, _arbitratorExtraData, _registrationMetaEvidence, _clearingMetaEvidence);
initialized = true;
}
/* External and Public */
// ************************ //
// * Requests * //
// ************************ //
/**
* @dev Directly add an item to the list bypassing request-challenge. Can only be used by the relay contract.
* @param _item The URI to the item data.
*/
function addItemDirectly(string calldata _item) external onlyRelayer {
bytes32 itemID = keccak256(abi.encodePacked(_item));
Item storage item = items[itemID];
require(item.status == Status.Absent, "Item must be absent to be added.");
// Note that if the item is added directly once, the next time it is added it will emit this event again.
if (item.requestCount == 0) {
emit NewItem(itemID, _item, true);
}
item.status = Status.Registered;
emit ItemStatusChange(itemID, true);
}
/**
* @dev Directly remove an item from the list bypassing request-challenge. Can only be used by the relay contract.
* @param _itemID The ID of the item to remove.
*/
function removeItemDirectly(bytes32 _itemID) external onlyRelayer {
Item storage item = items[_itemID];
require(item.status == Status.Registered, "Item must be registered to be removed.");
item.status = Status.Absent;
emit ItemStatusChange(_itemID, true);
}
/**
* @dev Submit a request to register an item. Accepts enough ETH to cover the deposit, reimburses the rest.
* @param _item The URI to the item data.
*/
function addItem(string calldata _item) external payable {
bytes32 itemID = keccak256(abi.encodePacked(_item));
Item storage item = items[itemID];
// Extremely unlikely, but we check that for correctness sake.
require(item.requestCount < uint120(-1), "Too many requests for item.");
require(item.status == Status.Absent, "Item must be absent to be added.");
// Note that if the item was added previously using `addItemDirectly`, the event will be emitted again here.
if (item.requestCount == 0) {
emit NewItem(itemID, _item, false);
}
Request storage request = item.requests[item.requestCount++];
uint256 arbitrationParamsIndex = arbitrationParamsChanges.length - 1;
IArbitrator arbitrator = arbitrationParamsChanges[arbitrationParamsIndex].arbitrator;
bytes storage arbitratorExtraData = arbitrationParamsChanges[arbitrationParamsIndex].arbitratorExtraData;
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
uint256 totalCost = arbitrationCost.addCap(submissionBaseDeposit);
require(msg.value >= totalCost, "You must fully fund the request.");
// Casting is safe here because this line will never be executed in case
// totalCost > type(uint128).max, since it would be an unpayable value.
item.sumDeposit = uint128(totalCost);
item.status = Status.RegistrationRequested;
request.requestType = RequestType.Registration;
request.submissionTime = uint64(block.timestamp);
request.arbitrationParamsIndex = uint24(arbitrationParamsIndex);
request.requester = msg.sender;
emit RequestSubmitted(itemID, getEvidenceGroupID(itemID, item.requestCount - 1));
emit Contribution(itemID, item.requestCount - 1, RESERVED_ROUND_ID, msg.sender, totalCost, Party.Requester);
if (msg.value > totalCost) {
msg.sender.send(msg.value - totalCost);
}
}
/**
* @dev Submit a request to remove an item from the list. Accepts enough ETH to cover the deposit, reimburses the rest.
* @param _itemID The ID of the item to remove.
* @param _evidence A link to an evidence using its URI. Ignored if not provided.
*/
function removeItem(bytes32 _itemID, string calldata _evidence) external payable {
Item storage item = items[_itemID];
// Extremely unlikely, but we check that for correctness sake.
require(item.requestCount < uint120(-1), "Too many requests for item.");
require(item.status == Status.Registered, "Item must be registered to be removed.");
Request storage request = item.requests[item.requestCount++];
uint256 arbitrationParamsIndex = arbitrationParamsChanges.length - 1;
IArbitrator arbitrator = arbitrationParamsChanges[arbitrationParamsIndex].arbitrator;
bytes storage arbitratorExtraData = arbitrationParamsChanges[arbitrationParamsIndex].arbitratorExtraData;
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData);
uint256 totalCost = arbitrationCost.addCap(removalBaseDeposit);
require(msg.value >= totalCost, "You must fully fund the request.");
// Casting is safe here because this line will never be executed in case
// totalCost > type(uint128).max, since it would be an unpayable value.
item.sumDeposit = uint128(totalCost);
item.status = Status.ClearingRequested;
request.submissionTime = uint64(block.timestamp);
request.arbitrationParamsIndex = uint24(arbitrationParamsIndex);
request.requester = msg.sender;
request.requestType = RequestType.Clearing;
uint256 evidenceGroupID = getEvidenceGroupID(_itemID, item.requestCount - 1);
emit RequestSubmitted(_itemID, evidenceGroupID);
emit Contribution(_itemID, item.requestCount - 1, RESERVED_ROUND_ID, msg.sender, totalCost, Party.Requester);
// Emit evidence if it was provided.
if (bytes(_evidence).length > 0) {
emit Evidence(arbitrator, evidenceGroupID, msg.sender, _evidence);
}
if (msg.value > totalCost) {
msg.sender.send(msg.value - totalCost);
}
}
/**
* @dev Challenges the request of the item. Accepts enough ETH to cover the deposit, reimburses the rest.
* @param _itemID The ID of the item which request to challenge.
* @param _evidence A link to an evidence using its URI. Ignored if not provided.
*/
function challengeRequest(bytes32 _itemID, string calldata _evidence) external payable {
Item storage item = items[_itemID];
require(item.status > Status.Registered, "The item must have a pending request.");
uint256 lastRequestIndex = item.requestCount - 1;
Request storage request = item.requests[lastRequestIndex];
require(
block.timestamp - request.submissionTime <= challengePeriodDuration,
"Challenges must occur during the challenge period."
);
DisputeData storage disputeData = requestsDisputeData[_itemID][lastRequestIndex];
require(disputeData.status == DisputeStatus.None, "The request should not have already been disputed.");
ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex];
IArbitrator arbitrator = arbitrationParams.arbitrator;
uint256 arbitrationCost = arbitrator.arbitrationCost(arbitrationParams.arbitratorExtraData);
uint256 totalCost;
{
uint256 challengerBaseDeposit = item.status == Status.RegistrationRequested
? submissionChallengeBaseDeposit
: removalChallengeBaseDeposit;
totalCost = arbitrationCost.addCap(challengerBaseDeposit);
}
require(msg.value >= totalCost, "You must fully fund the challenge.");
emit Contribution(_itemID, lastRequestIndex, RESERVED_ROUND_ID, msg.sender, totalCost, Party.Challenger);
// Casting is safe here because this line will never be executed in case
// totalCost > type(uint128).max, since it would be an unpayable value.
item.sumDeposit = item.sumDeposit.addCap(uint128(totalCost)).subCap(uint128(arbitrationCost));
request.challenger = msg.sender;
// Raise a dispute.
disputeData.disputeID = arbitrator.createDispute.value(arbitrationCost)(
RULING_OPTIONS,
arbitrationParams.arbitratorExtraData
);
disputeData.status = DisputeStatus.AwaitingRuling;
// For compatibility with GeneralizedTCR consider the request/challenge cycle
// the first round (index 0), so we need to make the next round index 1.
disputeData.roundCount = 2;
arbitratorDisputeIDToItemID[address(arbitrator)][disputeData.disputeID] = _itemID;
uint256 metaEvidenceID = 2 * request.arbitrationParamsIndex + uint256(request.requestType);
uint256 evidenceGroupID = getEvidenceGroupID(_itemID, lastRequestIndex);
emit Dispute(arbitrator, disputeData.disputeID, metaEvidenceID, evidenceGroupID);
if (bytes(_evidence).length > 0) {
emit Evidence(arbitrator, evidenceGroupID, msg.sender, _evidence);
}
if (msg.value > totalCost) {
msg.sender.send(msg.value - totalCost);
}
}
/**
* @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if both sides are fully funded.
* @param _itemID The ID of the item which request to fund.
* @param _side The recipient of the contribution.
*/
function fundAppeal(bytes32 _itemID, Party _side) external payable {
require(_side > Party.None, "Invalid side.");
Item storage item = items[_itemID];
require(item.status > Status.Registered, "The item must have a pending request.");
uint256 lastRequestIndex = item.requestCount - 1;
Request storage request = item.requests[lastRequestIndex];
DisputeData storage disputeData = requestsDisputeData[_itemID][lastRequestIndex];
require(
disputeData.status == DisputeStatus.AwaitingRuling,
"A dispute must have been raised to fund an appeal."
);
ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex];
IArbitrator arbitrator = arbitrationParams.arbitrator;
uint256 lastRoundIndex = disputeData.roundCount - 1;
Round storage round = disputeData.rounds[lastRoundIndex];
require(round.sideFunded != _side, "Side already fully funded.");
uint256 multiplier;
{
(uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(disputeData.disputeID);
require(
block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd,
"Contributions must be made within the appeal period."
);
Party winner = Party(arbitrator.currentRuling(disputeData.disputeID));
if (winner == Party.None) {
multiplier = sharedStakeMultiplier;
} else if (_side == winner) {
multiplier = winnerStakeMultiplier;
} else {
multiplier = loserStakeMultiplier;
require(
block.timestamp < (appealPeriodStart + appealPeriodEnd) / 2,
"The loser must contribute during the first half of the appeal period."
);
}
}
uint256 appealCost = arbitrator.appealCost(disputeData.disputeID, arbitrationParams.arbitratorExtraData);
uint256 totalCost = appealCost.addCap(appealCost.mulCap(multiplier) / MULTIPLIER_DIVISOR);
contribute(_itemID, lastRequestIndex, lastRoundIndex, uint256(_side), msg.sender, msg.value, totalCost);
if (round.amountPaid[uint256(_side)] >= totalCost) {
if (round.sideFunded == Party.None) {
round.sideFunded = _side;
} else {
// Resets the value because both sides are funded.
round.sideFunded = Party.None;
// Raise appeal if both sides are fully funded.
arbitrator.appeal.value(appealCost)(disputeData.disputeID, arbitrationParams.arbitratorExtraData);
disputeData.roundCount++;
round.feeRewards = round.feeRewards.subCap(appealCost);
}
}
}
/**
* @dev If a dispute was raised, sends the fee stake rewards and reimbursements proportionally to the contributions made to the winner of a dispute.
* @param _beneficiary The address that made contributions to a request.
* @param _itemID The ID of the item submission to withdraw from.
* @param _requestID The request from which to withdraw from.
* @param _roundID The round from which to withdraw from.
*/
function withdrawFeesAndRewards(
address payable _beneficiary,
bytes32 _itemID,
uint256 _requestID,
uint256 _roundID
) external {
DisputeData storage disputeData = requestsDisputeData[_itemID][_requestID];
require(disputeData.status == DisputeStatus.Resolved, "Request must be resolved.");
Round storage round = disputeData.rounds[_roundID];
uint256 reward;
if (_roundID == disputeData.roundCount - 1) {
// Reimburse if not enough fees were raised to appeal the ruling.
reward =
round.contributions[_beneficiary][uint256(Party.Requester)] +
round.contributions[_beneficiary][uint256(Party.Challenger)];
} else if (disputeData.ruling == Party.None) {
uint256 totalFeesInRound = round.amountPaid[uint256(Party.Challenger)] +
round.amountPaid[uint256(Party.Requester)];
uint256 claimableFees = round.contributions[_beneficiary][uint256(Party.Challenger)] +
round.contributions[_beneficiary][uint256(Party.Requester)];
reward = totalFeesInRound > 0 ? (claimableFees * round.feeRewards) / totalFeesInRound : 0;
} else {
// Reward the winner.
reward = round.amountPaid[uint256(disputeData.ruling)] > 0
? (round.contributions[_beneficiary][uint256(disputeData.ruling)] * round.feeRewards) /
round.amountPaid[uint256(disputeData.ruling)]
: 0;
}
round.contributions[_beneficiary][uint256(Party.Requester)] = 0;
round.contributions[_beneficiary][uint256(Party.Challenger)] = 0;
if (reward > 0) {
_beneficiary.send(reward);
emit RewardWithdrawn(_beneficiary, _itemID, _requestID, _roundID, reward);
}
}
/**
* @dev Executes an unchallenged request if the challenge period has passed.
* @param _itemID The ID of the item to execute.
*/
function executeRequest(bytes32 _itemID) external {
Item storage item = items[_itemID];
uint256 lastRequestIndex = items[_itemID].requestCount - 1;
Request storage request = item.requests[lastRequestIndex];
require(
block.timestamp - request.submissionTime > challengePeriodDuration,
"Time to challenge the request must pass."
);
DisputeData storage disputeData = requestsDisputeData[_itemID][lastRequestIndex];
require(disputeData.status == DisputeStatus.None, "The request should not be disputed.");
if (item.status == Status.RegistrationRequested) {
item.status = Status.Registered;
} else if (item.status == Status.ClearingRequested) {
item.status = Status.Absent;
} else {
revert("There must be a request.");
}
emit ItemStatusChange(_itemID, false);
uint256 sumDeposit = item.sumDeposit;
item.sumDeposit = 0;
if (sumDeposit > 0) {
// reimburse the requester
request.requester.send(sumDeposit);
}
}
/**
* @dev Give a ruling for a dispute. Can only be called by the arbitrator. TRUSTED.
* Accounts for the situation where the winner loses a case due to paying less appeal fees than expected.
* @param _disputeID ID of the dispute in the arbitrator contract.
* @param _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refused to arbitrate".
*/
function rule(uint256 _disputeID, uint256 _ruling) external {
require(_ruling <= RULING_OPTIONS, "Invalid ruling option");
bytes32 itemID = arbitratorDisputeIDToItemID[msg.sender][_disputeID];
Item storage item = items[itemID];
uint256 lastRequestIndex = items[itemID].requestCount - 1;
Request storage request = item.requests[lastRequestIndex];
DisputeData storage disputeData = requestsDisputeData[itemID][lastRequestIndex];
require(disputeData.status == DisputeStatus.AwaitingRuling, "The request must not be resolved.");
ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex];
require(address(arbitrationParams.arbitrator) == msg.sender, "Only the arbitrator can give a ruling");
uint256 finalRuling;
Round storage round = disputeData.rounds[disputeData.roundCount - 1];
// If one side paid its fees, the ruling is in its favor.
// Note that if the other side had also paid, sideFudned would have been reset
// and an appeal would have been created.
if (round.sideFunded == Party.Requester) {
finalRuling = uint256(Party.Requester);
} else if (round.sideFunded == Party.Challenger) {
finalRuling = uint256(Party.Challenger);
} else {
finalRuling = _ruling;
}
emit Ruling(IArbitrator(msg.sender), _disputeID, finalRuling);
Party winner = Party(finalRuling);
disputeData.status = DisputeStatus.Resolved;
disputeData.ruling = winner;
uint256 sumDeposit = item.sumDeposit;
item.sumDeposit = 0;
if (winner == Party.None) {
// If the arbitrator refuse to rule, then the item status should be the same it was before the request.
// Regarding item.status this is equivalent to the challenger winning the dispute.
item.status = item.status == Status.RegistrationRequested ? Status.Absent : Status.Registered;
// Since nobody has won, then we reimburse both parties equally.
// If item.sumDeposit is odd, 1 wei will remain in the contract balance.
uint256 halfSumDeposit = sumDeposit / 2;
request.requester.send(halfSumDeposit);
request.challenger.send(halfSumDeposit);
} else if (winner == Party.Requester) {
item.status = item.status == Status.RegistrationRequested ? Status.Registered : Status.Absent;
request.requester.send(sumDeposit);
} else {
item.status = item.status == Status.RegistrationRequested ? Status.Absent : Status.Registered;
request.challenger.send(sumDeposit);
}
emit ItemStatusChange(itemID, false);
}
/**
* @dev Submit a reference to evidence. EVENT.
* @param _itemID The ID of the item which the evidence is related to.
* @param _evidence A link to an evidence using its URI.
*/
function submitEvidence(bytes32 _itemID, string calldata _evidence) external {
Item storage item = items[_itemID];
uint256 lastRequestIndex = item.requestCount - 1;
Request storage request = item.requests[lastRequestIndex];
ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex];
emit Evidence(
arbitrationParams.arbitrator,
getEvidenceGroupID(_itemID, lastRequestIndex),
msg.sender,
_evidence
);
}
// ************************ //
// * Governance * //
// ************************ //
/**
* @dev Change the duration of the challenge period.
* @param _challengePeriodDuration The new duration of the challenge period.
*/
function changeChallengePeriodDuration(uint256 _challengePeriodDuration) external onlyGovernor {
challengePeriodDuration = _challengePeriodDuration;
}
/**
* @dev Change the base amount required as a deposit to submit an item.
* @param _submissionBaseDeposit The new base amount of wei required to submit an item.
*/
function changeSubmissionBaseDeposit(uint256 _submissionBaseDeposit) external onlyGovernor {
submissionBaseDeposit = _submissionBaseDeposit;
}
/**
* @dev Change the base amount required as a deposit to remove an item.
* @param _removalBaseDeposit The new base amount of wei required to remove an item.
*/
function changeRemovalBaseDeposit(uint256 _removalBaseDeposit) external onlyGovernor {
removalBaseDeposit = _removalBaseDeposit;
}
/**
* @dev Change the base amount required as a deposit to challenge a submission.
* @param _submissionChallengeBaseDeposit The new base amount of wei required to challenge a submission.
*/
function changeSubmissionChallengeBaseDeposit(uint256 _submissionChallengeBaseDeposit) external onlyGovernor {
submissionChallengeBaseDeposit = _submissionChallengeBaseDeposit;
}
/**
* @dev Change the base amount required as a deposit to challenge a removal request.
* @param _removalChallengeBaseDeposit The new base amount of wei required to challenge a removal request.
*/
function changeRemovalChallengeBaseDeposit(uint256 _removalChallengeBaseDeposit) external onlyGovernor {
removalChallengeBaseDeposit = _removalChallengeBaseDeposit;
}
/**
* @dev Change the governor of the curated registry.
* @param _governor The address of the new governor.
*/
function changeGovernor(address _governor) external onlyGovernor {
governor = _governor;
}
/**
* @dev Change the proportion of arbitration fees that must be paid as fee stake by parties when there is no winner or loser.
* @param _sharedStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points.
*/
function changeSharedStakeMultiplier(uint256 _sharedStakeMultiplier) external onlyGovernor {
sharedStakeMultiplier = _sharedStakeMultiplier;
}
/**
* @dev Change the proportion of arbitration fees that must be paid as fee stake by the winner of the previous round.
* @param _winnerStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points.
*/
function changeWinnerStakeMultiplier(uint256 _winnerStakeMultiplier) external onlyGovernor {
winnerStakeMultiplier = _winnerStakeMultiplier;
}
/**
* @dev Change the proportion of arbitration fees that must be paid as fee stake by the party that lost the previous round.
* @param _loserStakeMultiplier Multiplier of arbitration fees that must be paid as fee stake. In basis points.
*/
function changeLoserStakeMultiplier(uint256 _loserStakeMultiplier) external onlyGovernor {
loserStakeMultiplier = _loserStakeMultiplier;
}
/**
* @dev Change the address of connectedTCR, the Generalized TCR instance that stores addresses of TCRs related to this one.
* @param _connectedTCR The address of the connectedTCR contract to use.
*/
function changeConnectedTCR(address _connectedTCR) external onlyGovernor {
emit ConnectedTCRSet(_connectedTCR);
}
/**
* @dev Change the address of the relay contract.
* @param _relayerContract The new address of the relay contract.
*/
function changeRelayerContract(address _relayerContract) external onlyGovernor {
relayerContract = _relayerContract;
}
/**
* @notice Changes the params related to arbitration.
* @dev Effectively makes all new items use the new set of params.
* @param _arbitrator Arbitrator to resolve potential disputes. The arbitrator is trusted to support appeal periods and not reenter.
* @param _arbitratorExtraData Extra data for the trusted arbitrator contract.
* @param _registrationMetaEvidence The URI of the meta evidence object for registration requests.
* @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests.
*/
function changeArbitrationParams(
IArbitrator _arbitrator,
bytes calldata _arbitratorExtraData,
string calldata _registrationMetaEvidence,
string calldata _clearingMetaEvidence
) external onlyGovernor {
_doChangeArbitrationParams(_arbitrator, _arbitratorExtraData, _registrationMetaEvidence, _clearingMetaEvidence);
}
/* Internal */
/**
* @dev Effectively makes all new items use the new set of params.
* @param _arbitrator Arbitrator to resolve potential disputes. The arbitrator is trusted to support appeal periods and not reenter.
* @param _arbitratorExtraData Extra data for the trusted arbitrator contract.
* @param _registrationMetaEvidence The URI of the meta evidence object for registration requests.
* @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests.
*/
function _doChangeArbitrationParams(
IArbitrator _arbitrator,
bytes memory _arbitratorExtraData,
string memory _registrationMetaEvidence,
string memory _clearingMetaEvidence
) internal {
emit MetaEvidence(2 * arbitrationParamsChanges.length, _registrationMetaEvidence);
emit MetaEvidence(2 * arbitrationParamsChanges.length + 1, _clearingMetaEvidence);
arbitrationParamsChanges.push(
ArbitrationParams({arbitrator: _arbitrator, arbitratorExtraData: _arbitratorExtraData})
);
}
/**
* @notice Make a fee contribution.
* @dev It cannot be inlined in fundAppeal because of the stack limit.
* @param _itemID The item receiving the contribution.
* @param _requestID The request to contribute.
* @param _roundID The round to contribute.
* @param _side The side for which to contribute.
* @param _contributor The contributor.
* @param _amount The amount contributed.
* @param _totalRequired The total amount required for this side.
* @return The amount of appeal fees contributed.
*/
function contribute(
bytes32 _itemID,
uint256 _requestID,
uint256 _roundID,
uint256 _side,
address payable _contributor,
uint256 _amount,
uint256 _totalRequired
) internal {
Round storage round = requestsDisputeData[_itemID][_requestID].rounds[_roundID];
uint256 pendingAmount = _totalRequired.subCap(round.amountPaid[_side]);
// Take up to the amount necessary to fund the current round at the current costs.
uint256 contribution; // Amount contributed.
uint256 remainingETH; // Remaining ETH to send back.
if (pendingAmount > _amount) {
contribution = _amount;
} else {
contribution = pendingAmount;
remainingETH = _amount - pendingAmount;
}
round.contributions[_contributor][_side] += contribution;
round.amountPaid[_side] += contribution;
round.feeRewards += contribution;
// Reimburse leftover ETH.
if (remainingETH > 0) {
// Deliberate use of send in order to not block the contract in case of reverting fallback.
_contributor.send(remainingETH);
}
if (contribution > 0) {
emit Contribution(_itemID, _requestID, _roundID, msg.sender, contribution, Party(_side));
}
}
// ************************ //
// * Getters * //
// ************************ //
/**
* @dev Gets the evidengeGroupID for a given item and request.
* @param _itemID The ID of the item.
* @param _requestID The ID of the request.
* @return The evidenceGroupID
*/
function getEvidenceGroupID(bytes32 _itemID, uint256 _requestID) public pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(_itemID, _requestID)));
}
/**
* @notice Gets the arbitrator for new requests.
* @dev Gets the latest value in arbitrationParamsChanges.
* @return The arbitrator address.
*/
function arbitrator() external view returns (IArbitrator) {
return arbitrationParamsChanges[arbitrationParamsChanges.length - 1].arbitrator;
}
/**
* @notice Gets the arbitratorExtraData for new requests.
* @dev Gets the latest value in arbitrationParamsChanges.
* @return The arbitrator extra data.
*/
function arbitratorExtraData() external view returns (bytes memory) {
return arbitrationParamsChanges[arbitrationParamsChanges.length - 1].arbitratorExtraData;
}
/**
* @dev Gets the number of times MetaEvidence was updated.
* @return The number of times MetaEvidence was updated.
*/
function metaEvidenceUpdates() external view returns (uint256) {
return arbitrationParamsChanges.length;
}
/**
* @dev Gets the contributions made by a party for a given round of a request.
* @param _itemID The ID of the item.
* @param _requestID The request to query.
* @param _roundID The round to query.
* @param _contributor The address of the contributor.
* @return contributions The contributions.
*/
function getContributions(
bytes32 _itemID,
uint256 _requestID,
uint256 _roundID,
address _contributor
) external view returns (uint256[3] memory contributions) {
DisputeData storage disputeData = requestsDisputeData[_itemID][_requestID];
Round storage round = disputeData.rounds[_roundID];
contributions = round.contributions[_contributor];
}
/**
* @dev Returns item's information. Includes the total number of requests for the item
* @param _itemID The ID of the queried item.
* @return status The current status of the item.
* @return numberOfRequests Total number of requests for the item.
* @return sumDeposit The total deposit made by the requester and the challenger (if any)
*/
function getItemInfo(bytes32 _itemID)
external
view
returns (
Status status,
uint256 numberOfRequests,
uint256 sumDeposit
)
{
Item storage item = items[_itemID];
return (item.status, item.requestCount, item.sumDeposit);
}
/**
* @dev Gets information on a request made for the item.
* @param _itemID The ID of the queried item.
* @param _requestID The request to be queried.
* @return disputed True if a dispute was raised.
* @return disputeID ID of the dispute, if any.
* @return submissionTime Time when the request was made.
* @return resolved True if the request was executed and/or any raised disputes were resolved.
* @return parties Address of requester and challenger, if any.
* @return numberOfRounds Number of rounds of dispute.
* @return ruling The final ruling given, if any.
* @return arbitrator The arbitrator trusted to solve disputes for this request.
* @return arbitratorExtraData The extra data for the trusted arbitrator of this request.
* @return metaEvidenceID The meta evidence to be used in a dispute for this case.
*/
function getRequestInfo(bytes32 _itemID, uint256 _requestID)
external
view
returns (
bool disputed,
uint256 disputeID,
uint256 submissionTime,
bool resolved,
address payable[3] memory parties,
uint256 numberOfRounds,
Party ruling,
IArbitrator requestArbitrator,
bytes memory requestArbitratorExtraData,
uint256 metaEvidenceID
)
{
Item storage item = items[_itemID];
require(item.requestCount > _requestID, "Request does not exist.");
Request storage request = items[_itemID].requests[_requestID];
submissionTime = request.submissionTime;
parties[uint256(Party.Requester)] = request.requester;
parties[uint256(Party.Challenger)] = request.challenger;
(disputed, disputeID, numberOfRounds, ruling) = getRequestDisputeData(_itemID, _requestID);
(requestArbitrator, requestArbitratorExtraData, metaEvidenceID) = getRequestArbitrationParams(
_itemID,
_requestID
);
resolved = getRequestResolvedStatus(_itemID, _requestID);
}
/**
* @dev Gets the dispute data relative to a given item request.
* @param _itemID The ID of the queried item.
* @param _requestID The request to be queried.
* @return disputed True if a dispute was raised.
* @return disputeID ID of the dispute, if any.
* @return ruling The final ruling given, if any.
* @return numberOfRounds Number of rounds of dispute.
*/
function getRequestDisputeData(bytes32 _itemID, uint256 _requestID)
internal
view
returns (
bool disputed,
uint256 disputeID,
uint256 numberOfRounds,
Party ruling
)
{
DisputeData storage disputeData = requestsDisputeData[_itemID][_requestID];
return (
disputeData.status >= DisputeStatus.AwaitingRuling,
disputeData.disputeID,
disputeData.roundCount,
disputeData.ruling
);
}
/**
* @dev Gets the arbitration params relative to a given item request.
* @param _itemID The ID of the queried item.
* @param _requestID The request to be queried.
* @return arbitrator The arbitrator trusted to solve disputes for this request.
* @return arbitratorExtraData The extra data for the trusted arbitrator of this request.
* @return metaEvidenceID The meta evidence to be used in a dispute for this case.
*/
function getRequestArbitrationParams(bytes32 _itemID, uint256 _requestID)
internal
view
returns (
IArbitrator arbitrator,
bytes memory arbitratorExtraData,
uint256 metaEvidenceID
)
{
Request storage request = items[_itemID].requests[_requestID];
ArbitrationParams storage arbitrationParams = arbitrationParamsChanges[request.arbitrationParamsIndex];
return (
arbitrationParams.arbitrator,
arbitrationParams.arbitratorExtraData,
2 * request.arbitrationParamsIndex + uint256(request.requestType)
);
}
/**
* @dev Gets the resovled status of a given item request.
* @param _itemID The ID of the queried item.
* @param _requestID The request to be queried.
* @return resolved True if the request was executed and/or any raised disputes were resolved.
*/
function getRequestResolvedStatus(bytes32 _itemID, uint256 _requestID) internal view returns (bool resolved) {
Item storage item = items[_itemID];
if (item.requestCount == 0) {
return false;
}
if (_requestID < item.requestCount - 1) {
// It was resolved because it is not the last request.
return true;
}
return item.sumDeposit == 0;
}
/**
* @dev Gets the information of a round of a request.
* @param _itemID The ID of the queried item.
* @param _requestID The request to be queried.
* @param _roundID The round to be queried.
* @return appealed Whether appealed or not.
* @return amountPaid Tracks the sum paid for each Party in this round.
* @return hasPaid True if the Party has fully paid its fee in this round.
* @return feeRewards Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute.
*/
function getRoundInfo(
bytes32 _itemID,
uint256 _requestID,
uint256 _roundID
)
external
view
returns (
bool appealed,
uint256[3] memory amountPaid,
bool[3] memory hasPaid,
uint256 feeRewards
)
{
Item storage item = items[_itemID];
require(item.requestCount > _requestID, "Request does not exist.");
DisputeData storage disputeData = requestsDisputeData[_itemID][_requestID];
require(disputeData.roundCount > _roundID, "Round does not exist");
Round storage round = disputeData.rounds[_roundID];
appealed = _roundID < disputeData.roundCount - 1;
hasPaid[uint256(Party.Requester)] = appealed || round.sideFunded == Party.Requester;
hasPaid[uint256(Party.Challenger)] = appealed || round.sideFunded == Party.Challenger;
return (appealed, round.amountPaid, hasPaid, round.feeRewards);
}
}
/**
* @title LightGTCRFactory
* This contract acts as a registry for LightGeneralizedTCR instances.
*/
contract LightGTCRFactory {
/**
* @dev Emitted when a new Generalized TCR contract is deployed using this factory.
* @param _address The address of the newly deployed Generalized TCR.
*/
event NewGTCR(LightGeneralizedTCR indexed _address);
LightGeneralizedTCR[] public instances;
address public GTCR;
/**
* @dev Constructor.
* @param _GTCR Address of the generalized TCR contract that is going to be used for each new deployment.
*/
constructor(address _GTCR) public {
GTCR = _GTCR;
}
/**
* @dev Deploy the arbitrable curated registry.
* @param _arbitrator Arbitrator to resolve potential disputes. The arbitrator is trusted to support appeal periods and not reenter.
* @param _arbitratorExtraData Extra data for the trusted arbitrator contract.
* @param _connectedTCR The address of the TCR that stores related TCR addresses. This parameter can be left empty.
* @param _registrationMetaEvidence The URI of the meta evidence object for registration requests.
* @param _clearingMetaEvidence The URI of the meta evidence object for clearing requests.
* @param _governor The trusted governor of this contract.
* @param _baseDeposits The base deposits for requests/challenges as follows:
* - The base deposit to submit an item.
* - The base deposit to remove an item.
* - The base deposit to challenge a submission.
* - The base deposit to challenge a removal request.
* @param _challengePeriodDuration The time in seconds parties have to challenge a request.
* @param _stakeMultipliers Multipliers of the arbitration cost in basis points (see LightGeneralizedTCR MULTIPLIER_DIVISOR) as follows:
* - The multiplier applied to each party's fee stake for a round when there is no winner/loser in the previous round.
* - The multiplier applied to the winner's fee stake for an appeal round.
* - The multiplier applied to the loser's fee stake for an appeal round.
* @param _relayContract The address of the relay contract to add/remove items directly.
*/
function deploy(
IArbitrator _arbitrator,
bytes memory _arbitratorExtraData,
address _connectedTCR,
string memory _registrationMetaEvidence,
string memory _clearingMetaEvidence,
address _governor,
uint256[4] memory _baseDeposits,
uint256 _challengePeriodDuration,
uint256[3] memory _stakeMultipliers,
address _relayContract
) public {
LightGeneralizedTCR instance = clone(GTCR);
instance.initialize(
_arbitrator,
_arbitratorExtraData,
_connectedTCR,
_registrationMetaEvidence,
_clearingMetaEvidence,
_governor,
_baseDeposits,
_challengePeriodDuration,
_stakeMultipliers,
_relayContract
);
instances.push(instance);
emit NewGTCR(instance);
}
/**
* @notice Adaptation of @openzeppelin/contracts/proxy/Clones.sol.
* @dev Deploys and returns the address of a clone that mimics the behaviour of `GTCR`.
* @param _implementation Address of the contract to clone.
* This function uses the create opcode, which should never revert.
*/
function clone(address _implementation) internal returns (LightGeneralizedTCR instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, _implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != LightGeneralizedTCR(0), "ERC1167: create failed");
}
/**
* @return The number of deployed tcrs using this factory.
*/
function count() external view returns (uint256) {
return instances.length;
}
}
|
The address that can make changes to the parameters of the contract.
|
address public governor;
| 631,717 |
[
1,
1986,
1758,
716,
848,
1221,
3478,
358,
326,
1472,
434,
326,
6835,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
1758,
1071,
314,
1643,
29561,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/* Copyright 2019 Intel Corporation
*
* 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.4.0;
contract DirectRegistry{
enum RegistryStatus {
Unknown,
Active,
OffLine,
Decommissioned
}
struct RegistryInfo {
bytes32 orgId;
string uri;
bytes32 scAddr;
bytes32[] appTypeIds;
RegistryStatus status;
}
event RegistryAddEvent(
bytes32 orgId,
string uri,
bytes32 scAddr,
bytes32[] appTypeIds,
RegistryStatus status
);
event RegistryUpdateEvent(
bytes32 orgId,
string uri,
bytes32 scAddr,
bytes32[] appTypeIds
);
event RegistrySetStatusEvent(
bytes32 orgId,
RegistryStatus status
);
// To know the contractor owner
address private contractOwner;
// Map of registryInfo identified by key registryId
mapping (bytes32 => RegistryInfo) private registryMap;
// Map of index to wokerId
mapping (uint => bytes32) private registryList;
// Total number of registries
uint private registryCount;
constructor() public {
contractOwner = msg.sender;
registryCount = 0;
}
// Restrict to call registryRegister by authorised contract owner or
// is registry is of known organization.
modifier onlyOwner() {
require(
msg.sender == contractOwner,
"Sender not authorized"
);
_;
}
function registryAdd (
bytes32 orgId,
string memory uri,
bytes32 scAddr,
bytes32[] memory appTypeIds) public onlyOwner() {
// Add a new registry entry to registry list
// with registry list organization id, uri, smart contract
// address of worker registry contract and application type ids
require(orgId.length != 0, "Empty org id");
require(bytes(uri).length != 0, "Empty uri");
require(scAddr.length != 0, "Empty address");
// Check if registry exists, if yes then error
RegistryInfo memory registry = registryMap[orgId];
require(registry.orgId != orgId && registry.scAddr != scAddr,
"Registry exists with these details");
registryMap[orgId] = RegistryInfo(
orgId,
uri,
scAddr,
appTypeIds,
RegistryStatus.Active);
// Insert to registryList with current registryCount as key and registryId as value.
registryList[registryCount] = orgId;
// Increment registry count
registryCount++;
emit RegistryAddEvent(orgId, uri, scAddr, appTypeIds, RegistryStatus.Active);
}
function registryUpdate(bytes32 orgId, string memory uri, bytes32 scAddr,
bytes32[] memory appTypeIds) public {
// Update registry with identified by organization id
require(orgId.length != 0, "Empty org id");
require(bytes(uri).length != 0, "Empty uri");
require(scAddr.length != 0, "Empty address");
// Check if registry already exists, if yes then update the registryMap
RegistryInfo memory registry = registryMap[orgId];
require(registry.orgId == orgId, "Registry doesn't exist with these details");
registryMap[orgId].uri = uri;
registryMap[orgId].scAddr = scAddr;
for (uint i = 0; i < appTypeIds.length; i++) {
bool exists = false;
for (uint j = 0; j < registry.appTypeIds.length; j++) {
if (registry.appTypeIds[j] == appTypeIds[i]) {
exists = true;
break;
}
}
if (!exists) {
registryMap[orgId].appTypeIds.push(appTypeIds[i]);
}
}
emit RegistryUpdateEvent(orgId, uri, scAddr, appTypeIds);
}
function registrySetStatus(bytes32 orgId, RegistryStatus status) public {
// Set the registry status identified by organization id
require(orgId.length != 0, "Empty org id");
require(registryMap[orgId].orgId == orgId, "orgId doesn't exist");
registryMap[orgId].status = status;
emit RegistrySetStatusEvent(orgId, status);
}
function registryLookUp(bytes32 appTypeId) public view returns(
uint totalCount,
string memory lookUpTag,
bytes32[] memory orgIds) {
uint wCount = 0;
// lookUpTag is empty now, need to implement with specific content
// to be used to get the next available registries.
string memory lookUpString = "";
// Since solidity doesn't support returning dynamic array of memory storage,
// allocate the array with registry count.
bytes32[] memory wList = new bytes32[](registryCount);
for (uint i = 0; i < registryCount; i++) {
// Do lookup in registryList with an index and get the registry id
// and use it to lookup in registryMap
RegistryInfo memory registry = registryMap[registryList[i]];
if (appTypeId != 0) {
for(uint j = 0; j < registry.appTypeIds.length; j++) {
if (registry.appTypeIds[j] == appTypeId) {
//If match, update registry list and registry count
wList[wCount] = registry.orgId;
wCount ++;
}
}
}
else {
wList[wCount] = registry.orgId;
wCount ++;
}
}
// If array size is smaller than registry count then return only required size array.
if (wCount < registryCount) {
bytes32[] memory result = new bytes32[](wCount);
for (uint k = 0; k < wCount; k++) {
result[k] = wList[k];
}
return (wCount, lookUpString, result);
}
return (wCount, lookUpString, wList);
}
function registryRetrieve(bytes32 orgId) public view
returns (
string memory _uri,
bytes32 _scAddr,
bytes32[] memory _appTypeIds,
RegistryStatus status) {
// Retrieve registry details identified by orgId
require(orgId.length != 0, "Empty org id");
require(registryMap[orgId].orgId == orgId, "orgId doesn't exist");
// Do lookup with the given registryId from registryMap
RegistryInfo memory registry = registryMap[orgId];
return (registry.uri, registry.scAddr, registry.appTypeIds, registry.status);
}
//stub for registryLookUpNext
function registryLookUpNext(
bytes32 appTypeId,
string memory lookUpTag) public pure
returns(
int totalCount,
string memory newLookupTag,
bytes32[] memory registryIds) {
require(appTypeId.length != 0, "Empty Application id");
require(bytes(lookUpTag).length != 0, "lookUpTag is empty");
bytes32[] memory wIds;
string memory newTag = "";
int count = 0;
return (count, newTag, wIds);
}
}
|
Total number of registries
|
uint private registryCount;
| 931,538 |
[
1,
5269,
1300,
434,
960,
22796,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
2254,
3238,
4023,
1380,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0xC201fC7147daBbCaE388F20990f5cFa1fe322010/sources/contracts/Bet.sol
|
* @notice Transits bet to a new state/
|
function _nextState() internal {
betStorage.betState++;
}
| 4,666,661 |
[
1,
1429,
1282,
2701,
358,
279,
394,
919,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
389,
4285,
1119,
1435,
2713,
288,
203,
3639,
2701,
3245,
18,
70,
278,
1119,
9904,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.7;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/9fdc91758dbd958a28a238a87c71b21e501a47c7/contracts/math/SafeMath.sol";
import "https://github.com/swaldman/sol-key-iterable-mapping/blob/8773f95687c6467979936f32b0aaa72f921e4a75/src/main/solidity/AddressUInt256KeyIterableMapping.sol";
contract SimpleEthCommitment {
// libraries
using SafeMath for uint256;
using AddressUInt256KeyIterableMapping for AddressUInt256KeyIterableMapping.Store;
// event definitions
event Created();
event Funded( address indexed funder, uint256 oldValue, uint256 newValue );
event Unfunded( address indexed funder, uint256 amount );
event Committed( address indexed funder );
event CommittingStarts( address indexed firstComitter );
event CommitmentsCanceled( address indexed withdrawer );
event Locked( address indexed lastCommitter );
event Burnt( address indexed burner );
event Completed();
event Withdrawal( address indexed withdrawer, uint256 amount );
// STILL TO DO!!! Emit events in code
// storage
AddressUInt256KeyIterableMapping.Store private team;
mapping (address=>bool) public committed;
enum State { Funding, Committing, Locked, Complete, Burnt }
uint256 public duration;
uint256 public expiration;
// without a low max, unbounded iterations might become unperformable in transactions
uint8 constant MAX_TEAM_SIZE = 5;
State public state;
constructor( uint256 _duration ) public {
duration = _duration;
expiration = 0;
state = State.Funding;
emit Created();
}
// public functions
function fund() public payable {
require( state == State.Funding );
require( msg.value > 0 );
( , uint256 value ) = team.get( msg.sender );
uint256 newValue = value.add( msg.value );
team.put( msg.sender, newValue );
require( team.keyCount() <= MAX_TEAM_SIZE );
emit Funded( msg.sender, value, newValue );
}
function commit() public {
require( state == State.Funding || state == State.Committing );
require( team.keyCount() > 1 );
( bool exists, uint256 value ) = team.get( msg.sender );
require( exists && value > 0 );
committed[ msg.sender ] = true;
if ( allCommitted() ) {
lock();
}
else {
if ( state == State.Funding ) {
state = State.Committing;
emit CommittingStarts( msg.sender );
}
}
emit Committed( msg.sender );
}
function burn() public {
if ( state == State.Locked && now > expiration) complete();
require( state == State.Locked );
state = State.Burnt;
address(0).transfer( address(this).balance );
emit Burnt( msg.sender );
}
function withdraw() public {
if ( state == State.Locked && now > expiration) complete();
require( state == State.Funding || state == State.Committing || state == State.Complete );
( bool exists, uint256 toPay ) = team.get( msg.sender );
require( exists && toPay > 0 );
team.remove( msg.sender );
delete committed[msg.sender];
if ( state == State.Committing ) uncommit();
msg.sender.transfer(toPay);
if ( state == State.Complete ) {
emit Withdrawal( msg.sender, toPay );
}
else if ( state == State.Funding ) {
emit Unfunded( msg.sender, toPay );
}
else {
// we started in Funding | Committing | Complete, and switched to Funding if Committing
// so we should be Funding | Complete here
revert();
}
}
// public accessors
function getState() public view returns (uint256 _state) {
_state = uint256(state);
}
function getParticipants() public view returns( address[] memory _participants ) {
_participants = team.allKeys();
}
function bondFor( address participant ) public view returns( uint256 amount ) {
( bool exists, uint256 value ) = team.get( participant );
require( exists );
amount = value;
}
function isCommitted( address participant ) public view returns (bool _committed) {
_committed = committed[ participant ];
}
// private utilities
function complete() private {
require( state == State.Locked );
state = State.Complete;
emit Completed();
}
function lock() private {
require( state == State.Committing );
state = State.Locked;
expiration = now.add( duration );
emit Locked( msg.sender );
}
// dangerous, unbounded iteration.
// if there are too many users, this function may not be able to execute
function allCommitted() private view returns (bool) {
uint256 count = team.keyCount();
for ( uint256 i = 0; i < count; ++i ) {
if (!committed[ team.keyAt(i) ]) return false;
}
return true;
}
// dangerous, unbounded iteration.
// if there are too many users, this function may not be able to execute
function uncommit() private {
uint256 count = team.keyCount();
for ( uint256 i = 0; i < count; ++i ) delete committed[ team.keyAt(i) ];
state = State.Funding;
emit CommitmentsCanceled( msg.sender );
}
}
|
libraries event definitions STILL TO DO!!! Emit events in code storage without a low max, unbounded iterations might become unperformable in transactions
|
contract SimpleEthCommitment {
using SafeMath for uint256;
using AddressUInt256KeyIterableMapping for AddressUInt256KeyIterableMapping.Store;
event Created();
event Funded( address indexed funder, uint256 oldValue, uint256 newValue );
event Unfunded( address indexed funder, uint256 amount );
event Committed( address indexed funder );
event CommittingStarts( address indexed firstComitter );
event CommitmentsCanceled( address indexed withdrawer );
event Locked( address indexed lastCommitter );
event Burnt( address indexed burner );
event Completed();
event Withdrawal( address indexed withdrawer, uint256 amount );
AddressUInt256KeyIterableMapping.Store private team;
mapping (address=>bool) public committed;
uint256 public duration;
uint256 public expiration;
uint8 constant MAX_TEAM_SIZE = 5;
State public state;
enum State { Funding, Committing, Locked, Complete, Burnt }
constructor( uint256 _duration ) public {
duration = _duration;
expiration = 0;
state = State.Funding;
emit Created();
}
function fund() public payable {
require( state == State.Funding );
require( msg.value > 0 );
( , uint256 value ) = team.get( msg.sender );
uint256 newValue = value.add( msg.value );
team.put( msg.sender, newValue );
require( team.keyCount() <= MAX_TEAM_SIZE );
emit Funded( msg.sender, value, newValue );
}
function commit() public {
require( state == State.Funding || state == State.Committing );
require( team.keyCount() > 1 );
( bool exists, uint256 value ) = team.get( msg.sender );
require( exists && value > 0 );
committed[ msg.sender ] = true;
if ( allCommitted() ) {
lock();
}
else {
if ( state == State.Funding ) {
state = State.Committing;
emit CommittingStarts( msg.sender );
}
}
emit Committed( msg.sender );
}
function commit() public {
require( state == State.Funding || state == State.Committing );
require( team.keyCount() > 1 );
( bool exists, uint256 value ) = team.get( msg.sender );
require( exists && value > 0 );
committed[ msg.sender ] = true;
if ( allCommitted() ) {
lock();
}
else {
if ( state == State.Funding ) {
state = State.Committing;
emit CommittingStarts( msg.sender );
}
}
emit Committed( msg.sender );
}
function commit() public {
require( state == State.Funding || state == State.Committing );
require( team.keyCount() > 1 );
( bool exists, uint256 value ) = team.get( msg.sender );
require( exists && value > 0 );
committed[ msg.sender ] = true;
if ( allCommitted() ) {
lock();
}
else {
if ( state == State.Funding ) {
state = State.Committing;
emit CommittingStarts( msg.sender );
}
}
emit Committed( msg.sender );
}
function commit() public {
require( state == State.Funding || state == State.Committing );
require( team.keyCount() > 1 );
( bool exists, uint256 value ) = team.get( msg.sender );
require( exists && value > 0 );
committed[ msg.sender ] = true;
if ( allCommitted() ) {
lock();
}
else {
if ( state == State.Funding ) {
state = State.Committing;
emit CommittingStarts( msg.sender );
}
}
emit Committed( msg.sender );
}
function burn() public {
if ( state == State.Locked && now > expiration) complete();
require( state == State.Locked );
state = State.Burnt;
address(0).transfer( address(this).balance );
emit Burnt( msg.sender );
}
function withdraw() public {
if ( state == State.Locked && now > expiration) complete();
require( state == State.Funding || state == State.Committing || state == State.Complete );
( bool exists, uint256 toPay ) = team.get( msg.sender );
require( exists && toPay > 0 );
team.remove( msg.sender );
delete committed[msg.sender];
if ( state == State.Committing ) uncommit();
msg.sender.transfer(toPay);
if ( state == State.Complete ) {
emit Withdrawal( msg.sender, toPay );
}
else if ( state == State.Funding ) {
emit Unfunded( msg.sender, toPay );
}
else {
revert();
}
}
function withdraw() public {
if ( state == State.Locked && now > expiration) complete();
require( state == State.Funding || state == State.Committing || state == State.Complete );
( bool exists, uint256 toPay ) = team.get( msg.sender );
require( exists && toPay > 0 );
team.remove( msg.sender );
delete committed[msg.sender];
if ( state == State.Committing ) uncommit();
msg.sender.transfer(toPay);
if ( state == State.Complete ) {
emit Withdrawal( msg.sender, toPay );
}
else if ( state == State.Funding ) {
emit Unfunded( msg.sender, toPay );
}
else {
revert();
}
}
function withdraw() public {
if ( state == State.Locked && now > expiration) complete();
require( state == State.Funding || state == State.Committing || state == State.Complete );
( bool exists, uint256 toPay ) = team.get( msg.sender );
require( exists && toPay > 0 );
team.remove( msg.sender );
delete committed[msg.sender];
if ( state == State.Committing ) uncommit();
msg.sender.transfer(toPay);
if ( state == State.Complete ) {
emit Withdrawal( msg.sender, toPay );
}
else if ( state == State.Funding ) {
emit Unfunded( msg.sender, toPay );
}
else {
revert();
}
}
function withdraw() public {
if ( state == State.Locked && now > expiration) complete();
require( state == State.Funding || state == State.Committing || state == State.Complete );
( bool exists, uint256 toPay ) = team.get( msg.sender );
require( exists && toPay > 0 );
team.remove( msg.sender );
delete committed[msg.sender];
if ( state == State.Committing ) uncommit();
msg.sender.transfer(toPay);
if ( state == State.Complete ) {
emit Withdrawal( msg.sender, toPay );
}
else if ( state == State.Funding ) {
emit Unfunded( msg.sender, toPay );
}
else {
revert();
}
}
function getState() public view returns (uint256 _state) {
_state = uint256(state);
}
function getParticipants() public view returns( address[] memory _participants ) {
_participants = team.allKeys();
}
function bondFor( address participant ) public view returns( uint256 amount ) {
( bool exists, uint256 value ) = team.get( participant );
require( exists );
amount = value;
}
function isCommitted( address participant ) public view returns (bool _committed) {
_committed = committed[ participant ];
}
function complete() private {
require( state == State.Locked );
state = State.Complete;
emit Completed();
}
function lock() private {
require( state == State.Committing );
state = State.Locked;
expiration = now.add( duration );
emit Locked( msg.sender );
}
function allCommitted() private view returns (bool) {
uint256 count = team.keyCount();
for ( uint256 i = 0; i < count; ++i ) {
if (!committed[ team.keyAt(i) ]) return false;
}
return true;
}
function allCommitted() private view returns (bool) {
uint256 count = team.keyCount();
for ( uint256 i = 0; i < count; ++i ) {
if (!committed[ team.keyAt(i) ]) return false;
}
return true;
}
function uncommit() private {
uint256 count = team.keyCount();
for ( uint256 i = 0; i < count; ++i ) delete committed[ team.keyAt(i) ];
state = State.Funding;
emit CommitmentsCanceled( msg.sender );
}
}
| 12,536,204 |
[
1,
31417,
871,
6377,
2347,
15125,
8493,
5467,
25885,
16008,
2641,
316,
981,
2502,
2887,
279,
4587,
943,
16,
640,
26220,
11316,
4825,
12561,
640,
16092,
429,
316,
8938,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
4477,
41,
451,
5580,
475,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
225,
1450,
5267,
14342,
5034,
653,
13668,
3233,
364,
5267,
14342,
5034,
653,
13668,
3233,
18,
2257,
31,
203,
203,
225,
871,
12953,
5621,
203,
225,
871,
478,
12254,
12,
1758,
8808,
284,
9341,
16,
2254,
5034,
11144,
16,
2254,
5034,
6129,
11272,
203,
225,
871,
1351,
12125,
785,
12,
1758,
8808,
284,
9341,
16,
2254,
5034,
3844,
11272,
203,
225,
871,
1286,
7948,
12,
1758,
8808,
284,
9341,
11272,
203,
225,
871,
10269,
1787,
11203,
12,
1758,
8808,
1122,
799,
6132,
11272,
203,
225,
871,
10269,
1346,
23163,
12,
1758,
8808,
598,
9446,
264,
11272,
203,
225,
871,
3488,
329,
12,
1758,
8808,
1142,
5580,
387,
11272,
203,
225,
871,
605,
321,
88,
12,
1758,
8808,
18305,
264,
11272,
203,
225,
871,
28722,
5621,
203,
225,
871,
3423,
9446,
287,
12,
1758,
8808,
598,
9446,
264,
16,
2254,
5034,
3844,
11272,
203,
203,
203,
203,
225,
5267,
14342,
5034,
653,
13668,
3233,
18,
2257,
3238,
5927,
31,
203,
225,
2874,
261,
2867,
9207,
6430,
13,
1071,
16015,
31,
203,
203,
203,
225,
2254,
5034,
1071,
3734,
31,
203,
225,
2254,
5034,
1071,
7686,
31,
203,
203,
225,
2254,
28,
5381,
4552,
67,
1448,
2192,
67,
4574,
273,
1381,
31,
7010,
203,
225,
3287,
1071,
919,
31,
203,
203,
225,
2792,
3287,
288,
478,
14351,
16,
10269,
1787,
16,
3488,
329,
16,
14575,
16,
605,
321,
88,
289,
203,
225,
3885,
12,
2254,
5034,
389,
8760,
262,
2
] |
./partial_match/1/0x28e5552e8F51DE209e18CDDf90D2A4F260f26216/sources/Pass.sol
|
Function to generate the metadata for a token
|
) internal pure returns (string memory) {
| 2,739,134 |
[
1,
2083,
358,
2103,
326,
1982,
364,
279,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
262,
2713,
16618,
1135,
261,
1080,
3778,
13,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/84531/0xd7149865d07cCfdfB10f858AFAb297A8251882Cc/sources/contracts/stores/PoolStore.sol
|
@notice Returns total amount of CLP for `asset`
|
function getClpSupply(address asset) public view returns (uint256) {
return clpSupply[asset];
}
| 11,525,498 |
[
1,
1356,
2078,
3844,
434,
385,
14461,
364,
1375,
9406,
68,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1927,
9953,
3088,
1283,
12,
2867,
3310,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
927,
84,
3088,
1283,
63,
9406,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//
// Made by: Omicron Blockchain Solutions
// https://omicronblockchain.com
//
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "@openzeppelin/contracts/interfaces/IERC721.sol";
import "../interfaces/IMintableERC721.sol";
/**
* @title Reedemable ERC721 Giveaway
* @author Omicron Blockchain Solutions
*
* @notice Reedemable ERC721 Giveaway is a smart contract that allow accounts that own a specific ERC721 token
* to get another ERC721 token for free, in a fixed period of time; the smart contract
* is generic and can support any type of mintable NFT (see MintableERC721 interface).
* For instance, suppose that users already own NFTs named A. Then, for each minted NFT A, the owner
* can also mint another NFT called B. The releationship is one-to-one and it can be only one NFT of type B
* minted for a distinct NFT of type A.
*
* @dev All the "fixed" parameters can be changed on the go after smart contract is deployed
* and operational, but this ability is reserved for quick fix-like adjustments, and to provide
* an ability to restart and run a giveaway after the previous one ends.
*
* Note that both the `giveawayTokenContract` and `baseTokenContract` contracts must be mintble NFTS
* for this to work.
*
* When redeem an NFT token by this contract, the token is minted by the recipient.
*
* To successfully redeem a token, the caller must:
* 1) Own NFTs minted using the `baseTokenContract`
* 2) The NFTs minted using the `baseTokenContract` should already not been used to redeem NFTs
* of the `giveawayTokenContract`.
*
* Deployment and setup:
* 1. Deploy smart contract, specify the giveawat smart contract address during the deployment:
* - Mintable ER721 deployed instance address
* 2. Execute `initialize` function and set up the giveaway parameters;
* giveaway is not active until it's initialized and a valid `baseTokenContract` address is provided.
*/
contract RedeemableGiveaway is Ownable {
/**
* @dev Next token ID to mint;
* initially this is the first available ID which can be minted;
* at any point in time this should point to a available, mintable ID
* for the token.
*
* `nextId` cannot be zero, we do not ever mint NFTs with zero IDs.
*/
uint256 public nextId = 1;
/**
* @dev Last token ID to mint;
* once `nextId` exceeds `finalId` the giveaway pauses.
*/
uint256 public finalId;
// ----- SLOT.1 (96/256)
/**
* @notice Giveaway start at unix timestamp; the giveaway is active after the start (inclusive)
*/
uint32 public giveawayStart;
/**
* @notice Giveaway end unix timestamp; the giveaway is active before the end (exclusive)
*/
uint32 public giveawayEnd;
/**
* @notice Counter of the tokens gifted (minted) by this sale smart contract.
*/
uint32 public giveawayCounter;
/**
* @notice The contract address of the giveaway token.
*/
address public immutable giveawayTokenContract;
/**
* @notice The contract address of the base token.
*/
address public baseTokenContract;
/**
* @notice Track redeemed base tokens.
* @dev This is usefull to prevent same tokens to be used again after redeem.
*/
mapping(uint256 => bool) redeemedBaseTokens;
/**
* @dev Fired in initialize()
*
* @param _by an address which executed the initialization
* @param _nextId next ID of the giveaway token to mint
* @param _finalId final ID of the giveaway token to mint
* @param _giveawayStart start of the giveaway, unix timestamp
* @param _giveawayEnd end of the giveaway, unix timestamp
* @param _baseTokenContract base token contract address used for redeeming
*/
event Initialized(
address indexed _by,
uint256 _nextId,
uint256 _finalId,
uint32 _giveawayStart,
uint32 _giveawayEnd,
address _baseTokenContract
);
/**
* @dev Fired in redeem(), redeemTo(), redeemSingle(), and redeemSingleTo()
*
* @param _by an address which executed the transaction, probably a base NFT owner
* @param _to an address which received token(s) minted
* @param _giveawayTokens array with IDS of the minted tokens
*/
event Redeemed(address indexed _by, address indexed _to, uint256[] _giveawayTokens);
/**
* @dev Creates/deploys RedeemableERC721Giveaway and binds it to Mintable ERC721
* smart contract on construction
*
* @param _giveawayTokenContract deployed Mintable ERC721 smart contract; giveaway will mint ERC721
* tokens of that type to the recipient
*/
constructor(address _giveawayTokenContract) {
// Verify the input is set.
require(_giveawayTokenContract != address(0), "giveaway token contract is not set");
// Verify input is valid smart contract of the expected interfaces.
require(
IERC165(_giveawayTokenContract).supportsInterface(type(IMintableERC721).interfaceId) &&
IERC165(_giveawayTokenContract).supportsInterface(type(IMintableERC721).interfaceId),
"unexpected token contract type"
);
// Assign the addresses.
giveawayTokenContract = _giveawayTokenContract;
}
/**
* @notice Number of tokens left on giveaway.
*
* @dev Doesn't take into account if giveway is active or not,
* if `nextId - finalId < 1` returns zero.
*
* @return Number of tokens left on giveway.
*/
function itemsOnGiveaway() public view returns (uint256) {
// Calculate items left on givewaway, taking into account that
// `finalId` is givewaway (inclusive bound).
return finalId >= nextId ? finalId + 1 - nextId : 0;
}
/**
* @notice Number of tokens available on giveaway.
*
* @dev Takes into account if giveaway is active or not, doesn't throw,
* returns zero if giveaway is inactive
*
* @return Number of tokens available on giveaway.
*/
function itemsAvailable() public view returns (uint256) {
// Delegate to itemsOnSale() if giveaway is active, returns zero otherwise.
return isActive() ? itemsOnGiveaway() : 0;
}
/**
* @notice Active giveaway is an operational giveaway capable of minting tokens.
*
* @dev The giveaway is active when all the requirements below are met:
* 1. `baseTokenContract` is set
* 2. `finalId` is not reached (`nextId <= finalId`)
* 3. current timestamp is between `giveawayStart` (inclusive) and `giveawayEnd` (exclusive)
*
* Function is marked as virtual to be overridden in the helper test smart contract (mock)
* in order to test how it affects the giveaway process
*
* @return true if giveaway is active (operational) and can mint tokens, false otherwise.
*/
function isActive() public view virtual returns (bool) {
// Evaluate giveaway state based on the internal state variables and return.
return
baseTokenContract != address(0) &&
nextId <= finalId &&
giveawayStart <= block.timestamp &&
giveawayEnd > block.timestamp;
}
/**
* @dev Restricted access function to set up giveaway parameters, all at once,
* or any subset of them.
*
* To skip parameter initialization, set it to the biggest number for the corresponding type;
* for `_baseTokenContract`, use address(0) or '0x0000000000000000000000000000000000000000' from Javascript.
*
* Example: The following initialization will update only _giveawayStart and _giveawayEnd,
* leaving the rest of the fields unchanged:
*
* initialize(
* type(uint256).max,
* type(uint256).max,
* 1637080155850,
* 1639880155950,
* address(0)
* )
*
* Requires next ID to be greater than zero (strict): `_nextId > 0`
*
* Requires transaction sender to be the deployer of this contract.
*
* @param _nextId next ID of the token to mint, will be increased
* in smart contract storage after every successful giveaway
* @param _finalId final ID of the token to mint; giveaway is capable of producing
* `_finalId - _nextId + 1` tokens
* @param _giveawayStart start of the giveaway, unix timestamp
* @param _giveawayEnd end of the giveaway, unix timestamp; sale is active only
* when current time is within _giveawayStart (inclusive) and _giveawayEnd (exclusive)
* @param _baseTokenContract end of the sale, unix timestamp; sale is active only
* when current time is within _giveawayStart (inclusive) and _giveawayEnd (exclusive)
*/
function initialize(
uint256 _nextId, // <<<--- keep type in sync with the body type(uint256).max !!!
uint256 _finalId, // <<<--- keep type in sync with the body type(uint256).max !!!
uint32 _giveawayStart, // <<<--- keep type in sync with the body type(uint32).max !!!
uint32 _giveawayEnd, // <<<--- keep type in sync with the body type(uint32).max !!!
address _baseTokenContract // <<<--- keep type in sync with the body address(0) !!!
) public onlyOwner {
// Verify the inputs.
// No need to verify extra parameters - "incorrect" values will deactivate the sale.
require(_nextId > 0, "zero nextId");
// Initialize contract state based on the values supplied.
// Take into account our convention that value `-1` means "do not set"
if (_nextId != type(uint256).max) {
nextId = _nextId;
}
if (_finalId != type(uint256).max) {
finalId = _finalId;
}
if (_giveawayStart != type(uint32).max) {
giveawayStart = _giveawayStart;
}
if (_giveawayEnd != type(uint32).max) {
giveawayEnd = _giveawayEnd;
}
if (_baseTokenContract != address(0)) {
// The base contract must implement the Mintable NFT interface.
require(
IERC165(_baseTokenContract).supportsInterface(type(IMintableERC721).interfaceId) &&
IERC165(_baseTokenContract).supportsInterface(type(IMintableERC721).interfaceId),
"unexpected token contract type"
);
baseTokenContract = _baseTokenContract;
}
// Emit initialize event - read values from the storage since not all of them might be set.
emit Initialized(msg.sender, nextId, finalId, giveawayStart, giveawayEnd, baseTokenContract);
}
/**
* @notice Given an array of base tokens, check if any of the tokens were previously redeemed.
* @param _baseTokens Array with base tokens ID.
* @return true if any base token was previously redeemed, false otherwise.
*/
function areRedeemed(uint256[] calldata _baseTokens) external view returns (bool[] memory) {
bool[] memory redeemed = new bool[](_baseTokens.length);
for (uint256 i = 0; i < _baseTokens.length; i++) {
redeemed[i] = redeemedBaseTokens[_baseTokens[i]];
}
return redeemed;
}
/**
* @notice Redeem several tokens using the caller address. This function will fail if the provided `_baseTokens`
* are not owned by the caller or have previously redeemed.
*
* @param _baseTokens Array with base tokens ID.
*/
function redeem(uint256[] memory _baseTokens) public {
redeemTo(msg.sender, _baseTokens);
}
/**
* @notice Redeem several tokens into the address specified by `_to`. This function will fail
* if the provided `_baseTokens` are not owned by the caller or have previously redeemed.
*
* @param _to Address where the minted tokens will be assigned.
* @param _baseTokens Array with base tokens ID.
*/
function redeemTo(address _to, uint256[] memory _baseTokens) public {
// Verify the recipient's address.
require(_to != address(0), "recipient not set");
// Verify more than 1 tokens were provided, else the caller can use
// the single variants of the redeem functions.
require(_baseTokens.length > 1, "incorrect amount");
// Verify that all the specified base tokens IDs are owned by the transaction caller
// and does not have already been redeemed.
for (uint256 i = 0; i < _baseTokens.length; i++) {
require(IERC721(baseTokenContract).ownerOf(_baseTokens[i]) == msg.sender, "wrong owner");
require(!redeemedBaseTokens[_baseTokens[i]], "token already redeemed");
}
// Verify there is enough items available to giveaway.
// Verifies giveaway is in active state under the hood.
require(itemsAvailable() >= _baseTokens.length, "inactive giveaway or not enough items available");
// Store the minted giveaway tokens.
uint256[] memory giveawayTokens = new uint256[](_baseTokens.length);
// For each base token provided, mint a giveaway token.
for (uint256 i = 0; i < _baseTokens.length; i++) {
// Mint token to to the recipient.
IMintableERC721(giveawayTokenContract).mint(_to, nextId);
// Save the minted token ID.
giveawayTokens[i] = nextId;
// Set the next token ID to mint.
nextId += 1;
// Increase the giveaway counter.
giveawayCounter += 1;
// Record the base token, so that it cannot be used again for redeeming.
redeemedBaseTokens[_baseTokens[i]] = true;
}
// All the tokens were redeemed, emit the corresponding event.
emit Redeemed(msg.sender, _to, giveawayTokens);
}
/**
* @notice Redeem a single token using the caller address. This function will fail if the provided `_baseToken`
* is not owned by the caller or have previously redeemed.
*
* @param _baseToken Base token ID to redeem.
*/
function redeemSingle(uint256 _baseToken) public {
redeemSingleTo(msg.sender, _baseToken);
}
/**
* @notice Redeem a single token into the address specified by `_to`. This function will fail
* if the provided `_baseToken` is not owned by the caller or have previously redeemed.
*
* @param _to Address where the minted token will be assigned.
* @param _baseToken Base token ID to redeem.
*/
function redeemSingleTo(address _to, uint256 _baseToken) public {
// Verify the recipient's address.
require(_to != address(0), "recipient not set");
// Verify that the specified base tokens ID is owned by the transaction caller
// and does not have already been redeemed.
require(IERC721(baseTokenContract).ownerOf(_baseToken) == msg.sender, "wrong owner");
require(!redeemedBaseTokens[_baseToken], "token already redeemed");
// Verify there is enough items available to giveaway.
// Verifies giveaway is in active state under the hood.
require(itemsAvailable() >= 1, "inactive giveaway or not enough items available");
// Store the minted giveaway token.
uint256[] memory giveawayTokens = new uint256[](1);
// Mint token to to the recipient.
IMintableERC721(giveawayTokenContract).mint(_to, nextId);
// Save the minted token ID.
giveawayTokens[0] = nextId;
// Set the next token ID to mint.
nextId += 1;
// Increase the giveaway counter.
giveawayCounter += 1;
// Record the base token, so that it cannot be used again for redeeming.
redeemedBaseTokens[_baseToken] = true;
// All the tokens were redeemed, emit the corresponding event.
emit Redeemed(msg.sender, _to, giveawayTokens);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721.sol";
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
interface IMintableERC721 {
/**
* @notice Checks if specified token exists
*
* @dev Returns whether the specified token ID has an ownership
* information associated with it
*
* @param _tokenId ID of the token to query existence for
* @return whether the token exists (true - exists, false - doesn't exist)
*/
function exists(uint256 _tokenId) external view returns(bool);
/**
* @dev Creates new token with token ID specified
* and assigns an ownership `_to` for this token
*
* @dev Unsafe: doesn't execute `onERC721Received` on the receiver.
* Prefer the use of `saveMint` instead of `mint`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint token to
* @param _tokenId ID of the token to mint
*/
function mint(address _to, uint256 _tokenId) external;
/**
* @dev Creates new tokens starting with token ID specified
* and assigns an ownership `_to` for these tokens
*
* @dev Token IDs to be minted: [_tokenId, _tokenId + n)
*
* @dev n must be greater or equal 2: `n > 1`
*
* @dev Unsafe: doesn't execute `onERC721Received` on the receiver.
* Prefer the use of `saveMintBatch` instead of `mintBatch`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint tokens to
* @param _tokenId ID of the first token to mint
* @param n how many tokens to mint, sequentially increasing the _tokenId
*/
function mintBatch(address _to, uint256 _tokenId, uint256 n) external;
/**
* @dev Creates new token with token ID specified
* and assigns an ownership `_to` for this token
*
* @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint token to
* @param _tokenId ID of the token to mint
*/
function safeMint(address _to, uint256 _tokenId) external;
/**
* @dev Creates new token with token ID specified
* and assigns an ownership `_to` for this token
*
* @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint token to
* @param _tokenId ID of the token to mint
* @param _data additional data with no specified format, sent in call to `_to`
*/
function safeMint(address _to, uint256 _tokenId, bytes memory _data) external;
/**
* @dev Creates new tokens starting with token ID specified
* and assigns an ownership `_to` for these tokens
*
* @dev Token IDs to be minted: [_tokenId, _tokenId + n)
*
* @dev n must be greater or equal 2: `n > 1`
*
* @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint token to
* @param _tokenId ID of the token to mint
* @param n how many tokens to mint, sequentially increasing the _tokenId
*/
function safeMintBatch(address _to, uint256 _tokenId, uint256 n) external;
/**
* @dev Creates new tokens starting with token ID specified
* and assigns an ownership `_to` for these tokens
*
* @dev Token IDs to be minted: [_tokenId, _tokenId + n)
*
* @dev n must be greater or equal 2: `n > 1`
*
* @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint token to
* @param _tokenId ID of the token to mint
* @param n how many tokens to mint, sequentially increasing the _tokenId
* @param _data additional data with no specified format, sent in call to `_to`
*/
function safeMintBatch(address _to, uint256 _tokenId, uint256 n, bytes memory _data) external;
}
// 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 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/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;
}
|
Emit initialize event - read values from the storage since not all of them might be set.
|
emit Initialized(msg.sender, nextId, finalId, giveawayStart, giveawayEnd, baseTokenContract);
| 14,093,756 |
[
1,
17982,
4046,
871,
300,
855,
924,
628,
326,
2502,
3241,
486,
777,
434,
2182,
4825,
506,
444,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
3626,
10188,
1235,
12,
3576,
18,
15330,
16,
1024,
548,
16,
727,
548,
16,
8492,
26718,
1685,
16,
8492,
26718,
1638,
16,
1026,
1345,
8924,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-08
*/
pragma solidity ^0.7.6;
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
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);
}
}
}
}
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) {
// 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;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
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 payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
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);
}
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
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_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable {
function __ERC20Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal initializer {
}
/**
* @dev 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");
}
uint256[50] private __gap;
}
abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
using SafeMathUpgradeable for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
uint256[50] private __gap;
}
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
/**
* @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");
}
}
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal virtual view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal virtual {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* @title BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal override view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return adm The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override virtual {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
contract PUNDIXTokenProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy {
/**
* Contract initializer.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, address _admin, bytes memory _data) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(_logic, _data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(_admin);
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) {
BaseAdminUpgradeabilityProxy._willFallback();
}
}
library ECDSAUpgradeable {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
library CountersUpgradeable {
using SafeMathUpgradeable 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);
}
}
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal initializer {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal initializer {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
uint256[50] private __gap;
}
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping (address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal initializer {
__Context_init_unchained();
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory name) internal initializer {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
uint256[49] private __gap;
}
contract TokenRecipient {
function tokenFallback(address _sender, uint256 _value, bytes memory _extraData) public virtual returns (bool) {}
}
contract PUNDIXToken is Initializable, ContextUpgradeable, AccessControlUpgradeable, ERC20BurnableUpgradeable, ERC20PausableUpgradeable, ERC20PermitUpgradeable {
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
function initialize(address to) public virtual initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained("Pundi X Token", "PUNDIX");
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__ERC20Permit_init("PUNDIX");
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(ADMIN_ROLE, _msgSender());
_mint(to, 258498693019069996455928086);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount);
}
function pause() public virtual {
require(hasRole(ADMIN_ROLE, _msgSender()), "must have admin role to pause");
_pause();
}
function unpause() public virtual {
require(hasRole(ADMIN_ROLE, _msgSender()), "must have admin role to unpause");
_unpause();
}
function transferERCToken(address tokenContractAddress, address to, uint256 amount) public {
require(hasRole(ADMIN_ROLE, _msgSender()), "must have admin role to transfer other ERC20");
require(IERC20Upgradeable(tokenContractAddress).transfer(to, amount));
}
function transferAndCall(address recipient, uint256 amount, bytes memory data) public {
require(recipient != address(0), "transfer to the zero address");
require(amount <= balanceOf(recipient), "insufficient balance");
transfer(recipient, amount);
require(TokenRecipient(recipient).tokenFallback(msg.sender, amount, data));
}
}
|
* @dev Returns the address that signed a hashed message (`hash`) with `signature`. This address can then be used for verification purposes. The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: this function rejects them by requiring the `s` value to be in the lower half order, and the `v` value to be either 27 or 28. IMPORTANT: `hash` _must_ be the result of a hash operation for the verification to be secure: it is possible to craft signatures that recover to arbitrary addresses for non-hashed data. A safe way to ensure this is by receiving a hash of the original message (which may otherwise be too long), and then calling {toEthSignedMessageHash} on it./ Check the signature length ecrecover takes the signature parameters, and the only way to get them currently is to use assembly. solhint-disable-next-line no-inline-assembly
|
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
| 7,899,415 |
[
1,
1356,
326,
1758,
716,
6726,
279,
14242,
883,
21863,
2816,
24065,
598,
1375,
8195,
8338,
1220,
1758,
848,
1508,
506,
1399,
364,
11805,
13694,
18,
1021,
1375,
557,
266,
3165,
68,
512,
7397,
11396,
5360,
364,
312,
22534,
429,
261,
5836,
17,
6270,
13,
14862,
30,
333,
445,
4925,
87,
2182,
635,
29468,
326,
1375,
87,
68,
460,
358,
506,
316,
326,
2612,
8816,
1353,
16,
471,
326,
1375,
90,
68,
460,
358,
506,
3344,
12732,
578,
9131,
18,
21840,
6856,
30,
1375,
2816,
68,
389,
11926,
67,
506,
326,
563,
434,
279,
1651,
1674,
364,
326,
11805,
358,
506,
8177,
30,
518,
353,
3323,
358,
276,
5015,
14862,
716,
5910,
358,
11078,
6138,
364,
1661,
17,
2816,
329,
501,
18,
432,
4183,
4031,
358,
3387,
333,
353,
635,
15847,
279,
1651,
434,
326,
2282,
883,
261,
12784,
2026,
3541,
506,
4885,
1525,
3631,
471,
1508,
4440,
288,
2
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] |
[
1,
915,
5910,
12,
3890,
1578,
1651,
16,
1731,
3778,
3372,
13,
2713,
16618,
1135,
261,
2867,
13,
288,
203,
430,
261,
8195,
18,
2469,
480,
15892,
13,
288,
203,
266,
1097,
2932,
7228,
19748,
30,
2057,
3372,
769,
8863,
203,
97,
203,
203,
3890,
1578,
272,
31,
203,
11890,
28,
331,
31,
203,
203,
28050,
288,
203,
86,
519,
312,
945,
12,
1289,
12,
8195,
16,
374,
92,
3462,
3719,
203,
87,
519,
312,
945,
12,
1289,
12,
8195,
16,
374,
92,
7132,
3719,
203,
90,
519,
1160,
12,
20,
16,
312,
945,
12,
1289,
12,
8195,
16,
374,
92,
4848,
20349,
203,
97,
203,
203,
2463,
5910,
12,
2816,
16,
331,
16,
436,
16,
272,
1769,
203,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity =0.7.5;
import "./openzeppelin-contracts/contracts/token/ERC20/ERC20.sol";
import "./openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
import "./PoolManager.sol";
import "./IStrategy.sol";
contract Pool is ERC20 {
using SafeMath for uint256;
PoolManager poolMAN;
address StrategyControler;
IStrategy currentStrategy;
IStrategy oldStrategy;
IERC20 stakingToken;
event Test(uint256 num);
//modifer that requires caller to be region owner. Each region will have its own poolmanager. Change name of pool manager to region?
modifier onlyRegionOwner {
require(
msg.sender == poolMAN.getRegionOwner(),
"Only region owner can call this function."
);
_;
}
modifier onlyStrategyController {
require(
msg.sender == StrategyControler,
"Only strategy controller can call this function."
);
_;
}
/*
some sort of control mechanism to remember whether a user should withdraw from strategy itself, or from balance of this contract
when a strategy changes, the withdrawAll function should be called to return all funds to this pool.
*/
/*
pools should be deployed after pool manager and StrategyControler already exist (deployed on chain so can pass address to constructor)
*/
/*
use this to keep track of which strategy the user last invested into. Dont let them deposit into a new strategy until they have
withdrawn from the old strategy
*/
bool locked;
constructor(string memory name, string memory symbol, address stakTok, address SC, address PM)
ERC20(name, symbol) {
stakingToken = IERC20(stakTok);
StrategyControler = SC;
poolMAN = PoolManager(PM);
locked = false;
}
function setStrategy(IStrategy newStrategy) external onlyStrategyController{
require(address(newStrategy) != 0x0000000000000000000000000000000000000000, "new strategy cannot be zero address");
require(msg.sender == StrategyControler, "Only the StrategyControler contract can change the strategy");
require(!locked, "Finish migrating from old to current strategy before setting a new one"); //make sure strategy 2 before this new one that is about to go into effect is empty of money because it will be forgotten
require(address(newStrategy) != address(currentStrategy), "Cannot set the same strategy, address of new strategy is same as address of old"); //dont let the user set the same strategy that is already in effect
//set new strategy. This will change what happens when users deposit into this pool, the new strategy will be called to deposit into new strategy's logic
oldStrategy = currentStrategy;
currentStrategy = newStrategy;
if(address(oldStrategy) != 0x0000000000000000000000000000000000000000){
locked = true;
}
}
function moveToNewStrategy(uint256 amount) external onlyRegionOwner{
//@todo check this logic I wrote at 2 am sometime to make sure its right
//should move money from old strategy to new, and update the money in each with the balanceOf this contract from stakingToken
uint256 bal1 = stakingToken.balanceOf(address(this));
//require(false, "fails here?");
oldStrategy.withdraw(amount);
//require(false, "made it into move");
uint256 bal2 = stakingToken.balanceOf(address(this));
uint256 tokensToTransfer = bal2 - bal1;
bal1 = stakingToken.balanceOf(address(this));
stakingToken.transfer(address(currentStrategy), tokensToTransfer); //transfer happens outside deposit to make writing the strategy contracts easier
currentStrategy.deposit(tokensToTransfer); //deposit actually moves the money into whereever the strategy wants it to go
bal2 = stakingToken.balanceOf(address(this));
if(oldStrategy.totalBalance() == 0){
locked = false;
}
}
//@todo fix dust problem with moveAll method
function moveAllToNewStrategy() external onlyRegionOwner{
require(locked == true, "contract must be between strategies to move funds to new strategy");
uint256 oldTotal = oldStrategy.totalBalance();
uint256 startBal = stakingToken.balanceOf(address(this));
oldStrategy.withdraw(oldTotal);
uint256 afterBal = stakingToken.balanceOf(address(this));
uint256 tokensToTransfer = afterBal - startBal;
stakingToken.transfer(address(currentStrategy), tokensToTransfer);
currentStrategy.deposit(tokensToTransfer);
locked = false;
}
/*
maybe keep running ratio of funds withdawn and put into new strategy
then when user tries to stake more, let them stake proportionally in both, or prevent it alltogether
*/
// function withdraw in pieces. Maybe execute ahead of strategy change? Users can get their money out based on ratio withdramn, know how
//to withdraw proportionally?
/*
it seems that the yearn and harvest people might have the deposit and withdraw in an amount to slowly put things into new strategy
manually to really manage the funds more like micromanagy. Letting them get around slippage by withdrawing and depositing
parts of the funds slowly. Some strategies might involve going though swap pools to add liquidity in equal amounts or something,
which would cause significant slippage in a pool if the fund size is big enough and done all at once.
*/
function deposit(address user, uint256 amount) public{ //amount here is in staking token. DIFFERENT BETWEEN WITHDRAW AND STAKE
emit Test(1);
require(!locked, "deposits are disabled temporarily because contract is migrating strategies. Withdraws will work as normal.");
require(msg.sender == address(poolMAN), "pool manager must deposit funds");
require(address(currentStrategy) != 0x0000000000000000000000000000000000000000, "current address must not be zero address");
uint256 balBefore = currentStrategy.totalBalance();
emit Test(balBefore);
stakingToken.transfer(address(currentStrategy), amount);
currentStrategy.deposit(amount);
uint256 balAfter = currentStrategy.totalBalance();
uint256 tokensToMint;
//make sure that tokens still get minted if totalSupply is 0
if(totalSupply() != 0){
tokensToMint = ((balAfter - balBefore) * totalSupply() ) / balBefore;
}
else{
tokensToMint=(balAfter - balBefore);
}
_mint(user, tokensToMint);
}
function withdraw(address user, uint256 amount) public{//amount here is in pool token. DIFFERENT BETWEEN WITHDRAW AND STAKE
//@to done make this scale to users share of the pool
require(msg.sender == address(poolMAN), "withdraw can only be called through pool manager");
require(balanceOf(user) >= amount, "user balance too low"); // make sure user owns as much as they want to withdraw
/*
make this withdraw some funds from old strategy and some from new strategy depending on migration state of
funds by regionmanager from one strategy to another, in case someone withdraws while funds are moving
ratio of funds in old to new * share of users stake to withdraw * ratio of users investment to total pool value
(ratio of funds in old/ total Funds in both) * ( amount / balanceOf(user) ) * (balanceOf(user) / totalSupply()) -- how much to deposit into old. replace old with new for new in first funds ratio
*/
uint256 starting_funds = stakingToken.balanceOf(address(this));
uint256 oldToWithdraw;
if(address(oldStrategy) != 0x0000000000000000000000000000000000000000){
oldToWithdraw = (oldStrategy.totalBalance() * amount) / (totalSupply());
// (amount / totalSupply) * oldStrategyBalance
}
uint256 newToWithdraw = (currentStrategy.totalBalance() * amount) / (totalSupply());
// (amount / totalSupply) * currentStrategyBalance
if(address(oldStrategy) != 0x0000000000000000000000000000000000000000){
oldStrategy.withdraw(oldToWithdraw);
}
currentStrategy.withdraw(newToWithdraw);
uint256 finish_funds = stakingToken.balanceOf(address(this));
_burn(user, amount);
stakingToken.transfer(user, finish_funds - starting_funds);
}
function getToken() public view returns (IERC20){
return stakingToken;
}
//view function to get address of strategy manager contract
function getStrategyController() public view returns (address){
return StrategyControler;
}
//view function to get address of pool manager contract
function getPoolManager() public view returns (PoolManager){
return poolMAN;
}
function getCurrentStrategy() public view returns (IStrategy){
return currentStrategy;
}
function getLastStrategy() public view returns (IStrategy){
return oldStrategy;
}
}
|
deposit actually moves the money into whereever the strategy wants it to go
|
currentStrategy.deposit(tokensToTransfer);
| 12,619,266 |
[
1,
323,
1724,
6013,
13934,
326,
15601,
1368,
1625,
6084,
326,
6252,
14805,
518,
358,
1960,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
783,
4525,
18,
323,
1724,
12,
7860,
774,
5912,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.2;
pragma experimental ABIEncoderV2;
import 'RLP.sol';
import 'StorageStructure.sol';
/// @title CertiÐApp Smart Contract
/// @author Soham Zemse from The EraSwap Team
/// @notice This contract accepts certificates signed by multiple authorised signers
contract CertiDApp is StorageStructure {
using RLP for bytes;
using RLP for RLP.RLPItem;
/// @notice Sets up the CertiDApp manager address when deployed
constructor() public {
_changeManager(msg.sender);
}
/// @notice Used by present manager to change the manager wallet address
/// @param _newManagerAddress Address of next manager wallet
function changeManager(address _newManagerAddress) public onlyManager {
_changeManager(_newManagerAddress);
}
/// @notice Used by manager to for to update KYC / verification status of Certifying Authorities
/// @param _authorityAddress Wallet address of certifying authority
/// @param _data RLP encoded KYC details of certifying authority
function updateCertifyingAuthority(
address _authorityAddress,
bytes memory _data,
AuthorityStatus _status
) public onlyManager {
if(_data.length > 0) {
certifyingAuthorities[_authorityAddress].data = _data;
}
certifyingAuthorities[_authorityAddress].status = _status;
emit AuthorityStatusUpdated(_authorityAddress, _status);
}
/// @notice Used by Certifying Authorities to change their wallet (in case of theft).
/// Migrating prevents any new certificate registrations signed by the old wallet.
/// Already registered certificates would be valid.
/// @param _newAuthorityAddress Next wallet address of the same certifying authority
function migrateCertifyingAuthority(
address _newAuthorityAddress
) public onlyAuthorisedCertifier {
require(
certifyingAuthorities[_newAuthorityAddress].status == AuthorityStatus.NotAuthorised
, 'cannot migrate to an already authorised address'
);
certifyingAuthorities[msg.sender].status = AuthorityStatus.Migrated;
emit AuthorityStatusUpdated(msg.sender, AuthorityStatus.Migrated);
certifyingAuthorities[_newAuthorityAddress] = CertifyingAuthority({
data: certifyingAuthorities[msg.sender].data,
status: AuthorityStatus.Authorised
});
emit AuthorityStatusUpdated(_newAuthorityAddress, AuthorityStatus.Authorised);
emit AuthorityMigrated(msg.sender, _newAuthorityAddress);
}
/// @notice Used to submit a signed certificate to smart contract for adding it to storage.
/// Anyone can submit the certificate, the one submitting has to pay the nominal gas fee.
/// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard.
function registerCertificate(
bytes memory _signedCertificate
) public returns (
bytes32
) {
(Certificate memory _certificateObj, bytes32 _certificateHash) = parseSignedCertificate(_signedCertificate, true);
/// @notice Signers in this transaction
bytes memory _newSigners = _certificateObj.signers;
/// @notice If certificate already registered then signers can be updated.
/// Initializing _updatedSigners with existing signers on blockchain if any.
/// More signers would be appended to this in next 'for' loop.
bytes memory _updatedSigners = certificates[_certificateHash].signers;
/// @notice Check with every the new signer if it is not already included in storage.
/// This is helpful when a same certificate is submitted again with more signatures,
/// the contract will consider only new signers in that case.
for(uint256 i = 0; i < _newSigners.length; i += 20) {
address _signer;
assembly {
_signer := mload(add(_newSigners, add(0x14, i)))
}
if(_checkUniqueSigner(_signer, certificates[_certificateHash].signers)) {
_updatedSigners = abi.encodePacked(_updatedSigners, _signer);
emit Certified(
_certificateHash,
_signer
);
}
}
/// @notice check whether the certificate is freshly being registered.
/// For new certificates, directly proceed with adding it.
/// For existing certificates only update the signers if there are any new.
if(certificates[_certificateHash].signers.length > 0) {
require(_updatedSigners.length > certificates[_certificateHash].signers.length, 'need new signers');
certificates[_certificateHash].signers = _updatedSigners;
} else {
certificates[_certificateHash] = _certificateObj;
}
return _certificateHash;
}
/// @notice Used by contract to seperate signers from certificate data.
/// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard.
/// @param _allowedSignersOnly Should it consider only KYC approved signers ?
/// @return _certificateObj Seperation of certificate data and signers (computed from signatures)
/// @return _certificateHash Unique identifier of the certificate data
function parseSignedCertificate(
bytes memory _signedCertificate,
bool _allowedSignersOnly
) public view returns (
Certificate memory _certificateObj,
bytes32 _certificateHash
) {
RLP.RLPItem[] memory _certificateRLP = _signedCertificate.toRlpItem().toList();
_certificateObj.data = _certificateRLP[0].toRlpBytes();
_certificateHash = keccak256(abi.encodePacked(
PERSONAL_PREFIX,
_getBytesStr(_certificateObj.data.length),
_certificateObj.data
));
/// @notice loop through every signature and use eliptic curves cryptography to recover the
/// address of the wallet used for signing the certificate.
for(uint256 i = 1; i < _certificateRLP.length; i += 1) {
bytes memory _signature = _certificateRLP[i].toBytes();
bytes32 _r;
bytes32 _s;
uint8 _v;
assembly {
let _pointer := add(_signature, 0x20)
_r := mload(_pointer)
_s := mload(add(_pointer, 0x20))
_v := byte(0, mload(add(_pointer, 0x40)))
if lt(_v, 27) { _v := add(_v, 27) }
}
require(_v == 27 || _v == 28, 'invalid recovery value');
address _signer = ecrecover(_certificateHash, _v, _r, _s);
require(_checkUniqueSigner(_signer, _certificateObj.signers), 'each signer should be unique');
if(_allowedSignersOnly) {
require(certifyingAuthorities[_signer].status == AuthorityStatus.Authorised, 'certifier not authorised');
}
/// @dev packing every signer address into a single bytes value
_certificateObj.signers = abi.encodePacked(_certificateObj.signers, _signer);
}
}
/// @notice Used to change the manager
/// @param _newManagerAddress Address of next manager wallet
function _changeManager(address _newManagerAddress) private {
manager = _newManagerAddress;
emit ManagerUpdated(_newManagerAddress);
}
/// @notice Used to check whether an address exists in packed addresses bytes
/// @param _signer Address of the signer wallet
/// @param _packedSigners Bytes string of addressed packed together
/// @return boolean value which means if _signer doesnot exist in _packedSigners bytes string
function _checkUniqueSigner(
address _signer,
bytes memory _packedSigners
) private pure returns (bool){
if(_packedSigners.length == 0) return true;
require(_packedSigners.length % 20 == 0, 'invalid packed signers length');
address _tempSigner;
/// @notice loop through every packed signer and check if signer exists in the packed signers
for(uint256 i = 0; i < _packedSigners.length; i += 20) {
assembly {
_tempSigner := mload(add(_packedSigners, add(0x14, i)))
}
if(_tempSigner == _signer) return false;
}
return true;
}
/// @notice Used to get a number's utf8 representation
/// @param i Integer
/// @return utf8 representation of i
function _getBytesStr(uint i) private pure returns (bytes memory) {
if (i == 0) {
return "0";
}
uint j = i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0) {
bstr[k--] = byte(uint8(48 + i % 10));
i /= 10;
}
return bstr;
}
}
pragma solidity 0.6.2;
import 'StorageStructure.sol';
/**
* https://eips.ethereum.org/EIPS/eip-897
* Credits: OpenZeppelin Labs
*/
contract Proxy is StorageStructure {
string public version;
address public implementation;
uint256 public constant proxyType = 2;
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param version representing the version name of the upgraded implementation
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(string version, address indexed implementation);
/**
* @dev constructor that sets the manager address
*/
constructor() public {
manager = msg.sender;
}
/**
* @dev Upgrades the implementation address
* @param _newImplementation address of the new implementation
*/
function upgradeTo(
string calldata _version,
address _newImplementation
) external onlyManager {
require(implementation != _newImplementation);
_setImplementation(_version, _newImplementation);
}
/**
* @dev Fallback function allowing to perform a delegatecall
* to the given implementation. This function will return
* whatever the implementation call returns
*/
fallback () external {
address _impl = implementation;
require(_impl != address(0));
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
/**
* @dev Sets the address of the current implementation
* @param _newImp address of the new implementation
*/
function _setImplementation(string memory _version, address _newImp) internal {
version = _version;
implementation = _newImp;
emit Upgraded(version, implementation);
}
}
/**
* Credits: https://github.com/hamdiallam/Solidity-RLP/blob/master/contracts/RLPReader.sol
*/
pragma solidity ^0.6.2;
library RLP {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint ptr = self.nextPtr;
uint itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
require(isList(self));
uint ptr = self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param item RLP encoded bytes
*/
function rlpLen(RLPItem memory item) internal pure returns (uint) {
return item.len;
}
/*
* @param item RLP encoded bytes
*/
function payloadLen(RLPItem memory item) internal pure returns (uint) {
return item.len - _payloadOffset(item.memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item));
uint items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
if(item.len == 0) return false;
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if(byte0 < LIST_SHORT_START) return false;
return true;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
if (result.length == 0) return result;
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix
require(item.len == 21);
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
require(item.len > 0 && item.len <= 33);
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint result;
uint memPtr = item.memPtr + offset;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint) {
// one byte prefix
require(item.len == 33);
uint result;
uint memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset; // data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint) {
if (item.len == 0) return 0;
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) private pure returns (uint) {
uint itemLen;
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) private pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
pragma solidity 0.6.2;
/// @title Storage Structure for CertiÐApp Certificate Contract
/// @dev This contract is intended to be inherited in Proxy and Implementation contracts.
contract StorageStructure {
enum AuthorityStatus { NotAuthorised, Authorised, Migrated, Suspended }
struct Certificate {
bytes data;
bytes signers;
}
struct CertifyingAuthority {
bytes data;
AuthorityStatus status;
}
mapping(bytes32 => Certificate) public certificates;
mapping(address => CertifyingAuthority) public certifyingAuthorities;
mapping(bytes32 => bytes32) extraData;
address public manager;
bytes constant public PERSONAL_PREFIX = "\x19Ethereum Signed Message:\n";
event ManagerUpdated(
address _newManager
);
event Certified(
bytes32 indexed _certificateHash,
address indexed _certifyingAuthority
);
event AuthorityStatusUpdated(
address indexed _certifyingAuthority,
AuthorityStatus _newStatus
);
event AuthorityMigrated(
address indexed _oldAddress,
address indexed _newAddress
);
modifier onlyManager() {
require(msg.sender == manager, 'only manager can call');
_;
}
modifier onlyAuthorisedCertifier() {
require(
certifyingAuthorities[msg.sender].status == AuthorityStatus.Authorised
, 'only authorised certifier can call'
);
_;
}
}
pragma solidity 0.6.2;
pragma experimental ABIEncoderV2;
import 'RLP.sol';
import 'StorageStructure.sol';
/// @title CertiÐApp Smart Contract
/// @author Soham Zemse from The EraSwap Team
/// @notice This contract accepts certificates signed by multiple authorised signers
contract CertiDApp is StorageStructure {
using RLP for bytes;
using RLP for RLP.RLPItem;
/// @notice Sets up the CertiDApp manager address when deployed
constructor() public {
_changeManager(msg.sender);
}
/// @notice Used by present manager to change the manager wallet address
/// @param _newManagerAddress Address of next manager wallet
function changeManager(address _newManagerAddress) public onlyManager {
_changeManager(_newManagerAddress);
}
/// @notice Used by manager to for to update KYC / verification status of Certifying Authorities
/// @param _authorityAddress Wallet address of certifying authority
/// @param _data RLP encoded KYC details of certifying authority
function updateCertifyingAuthority(
address _authorityAddress,
bytes memory _data,
AuthorityStatus _status
) public onlyManager {
if(_data.length > 0) {
certifyingAuthorities[_authorityAddress].data = _data;
}
certifyingAuthorities[_authorityAddress].status = _status;
emit AuthorityStatusUpdated(_authorityAddress, _status);
}
/// @notice Used by Certifying Authorities to change their wallet (in case of theft).
/// Migrating prevents any new certificate registrations signed by the old wallet.
/// Already registered certificates would be valid.
/// @param _newAuthorityAddress Next wallet address of the same certifying authority
function migrateCertifyingAuthority(
address _newAuthorityAddress
) public onlyAuthorisedCertifier {
require(
certifyingAuthorities[_newAuthorityAddress].status == AuthorityStatus.NotAuthorised
, 'cannot migrate to an already authorised address'
);
certifyingAuthorities[msg.sender].status = AuthorityStatus.Migrated;
emit AuthorityStatusUpdated(msg.sender, AuthorityStatus.Migrated);
certifyingAuthorities[_newAuthorityAddress] = CertifyingAuthority({
data: certifyingAuthorities[msg.sender].data,
status: AuthorityStatus.Authorised
});
emit AuthorityStatusUpdated(_newAuthorityAddress, AuthorityStatus.Authorised);
emit AuthorityMigrated(msg.sender, _newAuthorityAddress);
}
/// @notice Used to submit a signed certificate to smart contract for adding it to storage.
/// Anyone can submit the certificate, the one submitting has to pay the nominal gas fee.
/// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard.
function registerCertificate(
bytes memory _signedCertificate
) public returns (
bytes32
) {
(Certificate memory _certificateObj, bytes32 _certificateHash) = parseSignedCertificate(_signedCertificate, true);
/// @notice Signers in this transaction
bytes memory _newSigners = _certificateObj.signers;
/// @notice If certificate already registered then signers can be updated.
/// Initializing _updatedSigners with existing signers on blockchain if any.
/// More signers would be appended to this in next 'for' loop.
bytes memory _updatedSigners = certificates[_certificateHash].signers;
/// @notice Check with every the new signer if it is not already included in storage.
/// This is helpful when a same certificate is submitted again with more signatures,
/// the contract will consider only new signers in that case.
for(uint256 i = 0; i < _newSigners.length; i += 20) {
address _signer;
assembly {
_signer := mload(add(_newSigners, add(0x14, i)))
}
if(_checkUniqueSigner(_signer, certificates[_certificateHash].signers)) {
_updatedSigners = abi.encodePacked(_updatedSigners, _signer);
emit Certified(
_certificateHash,
_signer
);
}
}
/// @notice check whether the certificate is freshly being registered.
/// For new certificates, directly proceed with adding it.
/// For existing certificates only update the signers if there are any new.
if(certificates[_certificateHash].signers.length > 0) {
require(_updatedSigners.length > certificates[_certificateHash].signers.length, 'need new signers');
certificates[_certificateHash].signers = _updatedSigners;
} else {
certificates[_certificateHash] = _certificateObj;
}
return _certificateHash;
}
/// @notice Used by contract to seperate signers from certificate data.
/// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard.
/// @param _allowedSignersOnly Should it consider only KYC approved signers ?
/// @return _certificateObj Seperation of certificate data and signers (computed from signatures)
/// @return _certificateHash Unique identifier of the certificate data
function parseSignedCertificate(
bytes memory _signedCertificate,
bool _allowedSignersOnly
) public view returns (
Certificate memory _certificateObj,
bytes32 _certificateHash
) {
RLP.RLPItem[] memory _certificateRLP = _signedCertificate.toRlpItem().toList();
_certificateObj.data = _certificateRLP[0].toRlpBytes();
_certificateHash = keccak256(abi.encodePacked(
PERSONAL_PREFIX,
_getBytesStr(_certificateObj.data.length),
_certificateObj.data
));
/// @notice loop through every signature and use eliptic curves cryptography to recover the
/// address of the wallet used for signing the certificate.
for(uint256 i = 1; i < _certificateRLP.length; i += 1) {
bytes memory _signature = _certificateRLP[i].toBytes();
bytes32 _r;
bytes32 _s;
uint8 _v;
assembly {
let _pointer := add(_signature, 0x20)
_r := mload(_pointer)
_s := mload(add(_pointer, 0x20))
_v := byte(0, mload(add(_pointer, 0x40)))
if lt(_v, 27) { _v := add(_v, 27) }
}
require(_v == 27 || _v == 28, 'invalid recovery value');
address _signer = ecrecover(_certificateHash, _v, _r, _s);
require(_checkUniqueSigner(_signer, _certificateObj.signers), 'each signer should be unique');
if(_allowedSignersOnly) {
require(certifyingAuthorities[_signer].status == AuthorityStatus.Authorised, 'certifier not authorised');
}
/// @dev packing every signer address into a single bytes value
_certificateObj.signers = abi.encodePacked(_certificateObj.signers, _signer);
}
}
/// @notice Used to change the manager
/// @param _newManagerAddress Address of next manager wallet
function _changeManager(address _newManagerAddress) private {
manager = _newManagerAddress;
emit ManagerUpdated(_newManagerAddress);
}
/// @notice Used to check whether an address exists in packed addresses bytes
/// @param _signer Address of the signer wallet
/// @param _packedSigners Bytes string of addressed packed together
/// @return boolean value which means if _signer doesnot exist in _packedSigners bytes string
function _checkUniqueSigner(
address _signer,
bytes memory _packedSigners
) private pure returns (bool){
if(_packedSigners.length == 0) return true;
require(_packedSigners.length % 20 == 0, 'invalid packed signers length');
address _tempSigner;
/// @notice loop through every packed signer and check if signer exists in the packed signers
for(uint256 i = 0; i < _packedSigners.length; i += 20) {
assembly {
_tempSigner := mload(add(_packedSigners, add(0x14, i)))
}
if(_tempSigner == _signer) return false;
}
return true;
}
/// @notice Used to get a number's utf8 representation
/// @param i Integer
/// @return utf8 representation of i
function _getBytesStr(uint i) private pure returns (bytes memory) {
if (i == 0) {
return "0";
}
uint j = i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0) {
bstr[k--] = byte(uint8(48 + i % 10));
i /= 10;
}
return bstr;
}
}
pragma solidity 0.6.2;
import 'StorageStructure.sol';
/**
* https://eips.ethereum.org/EIPS/eip-897
* Credits: OpenZeppelin Labs
*/
contract Proxy is StorageStructure {
string public version;
address public implementation;
uint256 public constant proxyType = 2;
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param version representing the version name of the upgraded implementation
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(string version, address indexed implementation);
/**
* @dev constructor that sets the manager address
*/
constructor() public {
manager = msg.sender;
}
/**
* @dev Upgrades the implementation address
* @param _newImplementation address of the new implementation
*/
function upgradeTo(
string calldata _version,
address _newImplementation
) external onlyManager {
require(implementation != _newImplementation);
_setImplementation(_version, _newImplementation);
}
/**
* @dev Fallback function allowing to perform a delegatecall
* to the given implementation. This function will return
* whatever the implementation call returns
*/
fallback () external {
address _impl = implementation;
require(_impl != address(0));
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
/**
* @dev Sets the address of the current implementation
* @param _newImp address of the new implementation
*/
function _setImplementation(string memory _version, address _newImp) internal {
version = _version;
implementation = _newImp;
emit Upgraded(version, implementation);
}
}
/**
* Credits: https://github.com/hamdiallam/Solidity-RLP/blob/master/contracts/RLPReader.sol
*/
pragma solidity ^0.6.2;
library RLP {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint ptr = self.nextPtr;
uint itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
require(isList(self));
uint ptr = self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param item RLP encoded bytes
*/
function rlpLen(RLPItem memory item) internal pure returns (uint) {
return item.len;
}
/*
* @param item RLP encoded bytes
*/
function payloadLen(RLPItem memory item) internal pure returns (uint) {
return item.len - _payloadOffset(item.memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item));
uint items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
if(item.len == 0) return false;
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if(byte0 < LIST_SHORT_START) return false;
return true;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
if (result.length == 0) return result;
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix
require(item.len == 21);
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
require(item.len > 0 && item.len <= 33);
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint result;
uint memPtr = item.memPtr + offset;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint) {
// one byte prefix
require(item.len == 33);
uint result;
uint memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset; // data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint) {
if (item.len == 0) return 0;
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) private pure returns (uint) {
uint itemLen;
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) private pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
pragma solidity 0.6.2;
/// @title Storage Structure for CertiÐApp Certificate Contract
/// @dev This contract is intended to be inherited in Proxy and Implementation contracts.
contract StorageStructure {
enum AuthorityStatus { NotAuthorised, Authorised, Migrated, Suspended }
struct Certificate {
bytes data;
bytes signers;
}
struct CertifyingAuthority {
bytes data;
AuthorityStatus status;
}
mapping(bytes32 => Certificate) public certificates;
mapping(address => CertifyingAuthority) public certifyingAuthorities;
mapping(bytes32 => bytes32) extraData;
address public manager;
bytes constant public PERSONAL_PREFIX = "\x19Ethereum Signed Message:\n";
event ManagerUpdated(
address _newManager
);
event Certified(
bytes32 indexed _certificateHash,
address indexed _certifyingAuthority
);
event AuthorityStatusUpdated(
address indexed _certifyingAuthority,
AuthorityStatus _newStatus
);
event AuthorityMigrated(
address indexed _oldAddress,
address indexed _newAddress
);
modifier onlyManager() {
require(msg.sender == manager, 'only manager can call');
_;
}
modifier onlyAuthorisedCertifier() {
require(
certifyingAuthorities[msg.sender].status == AuthorityStatus.Authorised
, 'only authorised certifier can call'
);
_;
}
}
pragma solidity 0.6.2;
pragma experimental ABIEncoderV2;
import 'RLP.sol';
import 'StorageStructure.sol';
/// @title CertiÐApp Smart Contract
/// @author Soham Zemse from The EraSwap Team
/// @notice This contract accepts certificates signed by multiple authorised signers
contract CertiDApp is StorageStructure {
using RLP for bytes;
using RLP for RLP.RLPItem;
/// @notice Sets up the CertiDApp manager address when deployed
constructor() public {
_changeManager(msg.sender);
}
/// @notice Used by present manager to change the manager wallet address
/// @param _newManagerAddress Address of next manager wallet
function changeManager(address _newManagerAddress) public onlyManager {
_changeManager(_newManagerAddress);
}
/// @notice Used by manager to for to update KYC / verification status of Certifying Authorities
/// @param _authorityAddress Wallet address of certifying authority
/// @param _data RLP encoded KYC details of certifying authority
function updateCertifyingAuthority(
address _authorityAddress,
bytes memory _data,
AuthorityStatus _status
) public onlyManager {
if(_data.length > 0) {
certifyingAuthorities[_authorityAddress].data = _data;
}
certifyingAuthorities[_authorityAddress].status = _status;
emit AuthorityStatusUpdated(_authorityAddress, _status);
}
/// @notice Used by Certifying Authorities to change their wallet (in case of theft).
/// Migrating prevents any new certificate registrations signed by the old wallet.
/// Already registered certificates would be valid.
/// @param _newAuthorityAddress Next wallet address of the same certifying authority
function migrateCertifyingAuthority(
address _newAuthorityAddress
) public onlyAuthorisedCertifier {
require(
certifyingAuthorities[_newAuthorityAddress].status == AuthorityStatus.NotAuthorised
, 'cannot migrate to an already authorised address'
);
certifyingAuthorities[msg.sender].status = AuthorityStatus.Migrated;
emit AuthorityStatusUpdated(msg.sender, AuthorityStatus.Migrated);
certifyingAuthorities[_newAuthorityAddress] = CertifyingAuthority({
data: certifyingAuthorities[msg.sender].data,
status: AuthorityStatus.Authorised
});
emit AuthorityStatusUpdated(_newAuthorityAddress, AuthorityStatus.Authorised);
emit AuthorityMigrated(msg.sender, _newAuthorityAddress);
}
/// @notice Used to submit a signed certificate to smart contract for adding it to storage.
/// Anyone can submit the certificate, the one submitting has to pay the nominal gas fee.
/// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard.
function registerCertificate(
bytes memory _signedCertificate
) public returns (
bytes32
) {
(Certificate memory _certificateObj, bytes32 _certificateHash) = parseSignedCertificate(_signedCertificate, true);
/// @notice Signers in this transaction
bytes memory _newSigners = _certificateObj.signers;
/// @notice If certificate already registered then signers can be updated.
/// Initializing _updatedSigners with existing signers on blockchain if any.
/// More signers would be appended to this in next 'for' loop.
bytes memory _updatedSigners = certificates[_certificateHash].signers;
/// @notice Check with every the new signer if it is not already included in storage.
/// This is helpful when a same certificate is submitted again with more signatures,
/// the contract will consider only new signers in that case.
for(uint256 i = 0; i < _newSigners.length; i += 20) {
address _signer;
assembly {
_signer := mload(add(_newSigners, add(0x14, i)))
}
if(_checkUniqueSigner(_signer, certificates[_certificateHash].signers)) {
_updatedSigners = abi.encodePacked(_updatedSigners, _signer);
emit Certified(
_certificateHash,
_signer
);
}
}
/// @notice check whether the certificate is freshly being registered.
/// For new certificates, directly proceed with adding it.
/// For existing certificates only update the signers if there are any new.
if(certificates[_certificateHash].signers.length > 0) {
require(_updatedSigners.length > certificates[_certificateHash].signers.length, 'need new signers');
certificates[_certificateHash].signers = _updatedSigners;
} else {
certificates[_certificateHash] = _certificateObj;
}
return _certificateHash;
}
/// @notice Used by contract to seperate signers from certificate data.
/// @param _signedCertificate RLP encoded certificate according to CertiDApp Certificate standard.
/// @param _allowedSignersOnly Should it consider only KYC approved signers ?
/// @return _certificateObj Seperation of certificate data and signers (computed from signatures)
/// @return _certificateHash Unique identifier of the certificate data
function parseSignedCertificate(
bytes memory _signedCertificate,
bool _allowedSignersOnly
) public view returns (
Certificate memory _certificateObj,
bytes32 _certificateHash
) {
RLP.RLPItem[] memory _certificateRLP = _signedCertificate.toRlpItem().toList();
_certificateObj.data = _certificateRLP[0].toRlpBytes();
_certificateHash = keccak256(abi.encodePacked(
PERSONAL_PREFIX,
_getBytesStr(_certificateObj.data.length),
_certificateObj.data
));
/// @notice loop through every signature and use eliptic curves cryptography to recover the
/// address of the wallet used for signing the certificate.
for(uint256 i = 1; i < _certificateRLP.length; i += 1) {
bytes memory _signature = _certificateRLP[i].toBytes();
bytes32 _r;
bytes32 _s;
uint8 _v;
assembly {
let _pointer := add(_signature, 0x20)
_r := mload(_pointer)
_s := mload(add(_pointer, 0x20))
_v := byte(0, mload(add(_pointer, 0x40)))
if lt(_v, 27) { _v := add(_v, 27) }
}
require(_v == 27 || _v == 28, 'invalid recovery value');
address _signer = ecrecover(_certificateHash, _v, _r, _s);
require(_checkUniqueSigner(_signer, _certificateObj.signers), 'each signer should be unique');
if(_allowedSignersOnly) {
require(certifyingAuthorities[_signer].status == AuthorityStatus.Authorised, 'certifier not authorised');
}
/// @dev packing every signer address into a single bytes value
_certificateObj.signers = abi.encodePacked(_certificateObj.signers, _signer);
}
}
/// @notice Used to change the manager
/// @param _newManagerAddress Address of next manager wallet
function _changeManager(address _newManagerAddress) private {
manager = _newManagerAddress;
emit ManagerUpdated(_newManagerAddress);
}
/// @notice Used to check whether an address exists in packed addresses bytes
/// @param _signer Address of the signer wallet
/// @param _packedSigners Bytes string of addressed packed together
/// @return boolean value which means if _signer doesnot exist in _packedSigners bytes string
function _checkUniqueSigner(
address _signer,
bytes memory _packedSigners
) private pure returns (bool){
if(_packedSigners.length == 0) return true;
require(_packedSigners.length % 20 == 0, 'invalid packed signers length');
address _tempSigner;
/// @notice loop through every packed signer and check if signer exists in the packed signers
for(uint256 i = 0; i < _packedSigners.length; i += 20) {
assembly {
_tempSigner := mload(add(_packedSigners, add(0x14, i)))
}
if(_tempSigner == _signer) return false;
}
return true;
}
/// @notice Used to get a number's utf8 representation
/// @param i Integer
/// @return utf8 representation of i
function _getBytesStr(uint i) private pure returns (bytes memory) {
if (i == 0) {
return "0";
}
uint j = i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0) {
bstr[k--] = byte(uint8(48 + i % 10));
i /= 10;
}
return bstr;
}
}
pragma solidity 0.6.2;
import 'StorageStructure.sol';
/**
* https://eips.ethereum.org/EIPS/eip-897
* Credits: OpenZeppelin Labs
*/
contract Proxy is StorageStructure {
string public version;
address public implementation;
uint256 public constant proxyType = 2;
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param version representing the version name of the upgraded implementation
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(string version, address indexed implementation);
/**
* @dev constructor that sets the manager address
*/
constructor() public {
manager = msg.sender;
}
/**
* @dev Upgrades the implementation address
* @param _newImplementation address of the new implementation
*/
function upgradeTo(
string calldata _version,
address _newImplementation
) external onlyManager {
require(implementation != _newImplementation);
_setImplementation(_version, _newImplementation);
}
/**
* @dev Fallback function allowing to perform a delegatecall
* to the given implementation. This function will return
* whatever the implementation call returns
*/
fallback () external {
address _impl = implementation;
require(_impl != address(0));
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
/**
* @dev Sets the address of the current implementation
* @param _newImp address of the new implementation
*/
function _setImplementation(string memory _version, address _newImp) internal {
version = _version;
implementation = _newImp;
emit Upgraded(version, implementation);
}
}
/**
* Credits: https://github.com/hamdiallam/Solidity-RLP/blob/master/contracts/RLPReader.sol
*/
pragma solidity ^0.6.2;
library RLP {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint ptr = self.nextPtr;
uint itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
require(isList(self));
uint ptr = self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param item RLP encoded bytes
*/
function rlpLen(RLPItem memory item) internal pure returns (uint) {
return item.len;
}
/*
* @param item RLP encoded bytes
*/
function payloadLen(RLPItem memory item) internal pure returns (uint) {
return item.len - _payloadOffset(item.memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item));
uint items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
if(item.len == 0) return false;
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if(byte0 < LIST_SHORT_START) return false;
return true;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
if (result.length == 0) return result;
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix
require(item.len == 21);
return address(toUint(item));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
require(item.len > 0 && item.len <= 33);
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint result;
uint memPtr = item.memPtr + offset;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint) {
// one byte prefix
require(item.len == 33);
uint result;
uint memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset; // data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint) {
if (item.len == 0) return 0;
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) private pure returns (uint) {
uint itemLen;
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) private pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
pragma solidity 0.6.2;
/// @title Storage Structure for CertiÐApp Certificate Contract
/// @dev This contract is intended to be inherited in Proxy and Implementation contracts.
contract StorageStructure {
enum AuthorityStatus { NotAuthorised, Authorised, Migrated, Suspended }
struct Certificate {
bytes data;
bytes signers;
}
struct CertifyingAuthority {
bytes data;
AuthorityStatus status;
}
mapping(bytes32 => Certificate) public certificates;
mapping(address => CertifyingAuthority) public certifyingAuthorities;
mapping(bytes32 => bytes32) extraData;
address public manager;
bytes constant public PERSONAL_PREFIX = "\x19Ethereum Signed Message:\n";
event ManagerUpdated(
address _newManager
);
event Certified(
bytes32 indexed _certificateHash,
address indexed _certifyingAuthority
);
event AuthorityStatusUpdated(
address indexed _certifyingAuthority,
AuthorityStatus _newStatus
);
event AuthorityMigrated(
address indexed _oldAddress,
address indexed _newAddress
);
modifier onlyManager() {
require(msg.sender == manager, 'only manager can call');
_;
}
modifier onlyAuthorisedCertifier() {
require(
certifyingAuthorities[msg.sender].status == AuthorityStatus.Authorised
, 'only authorised certifier can call'
);
_;
}
}
|
@dev Returns the next element in the iteration. Reverts if it has not next element. @param self The iterator. @return The next element in the iteration./
|
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint ptr = self.nextPtr;
uint itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
| 6,458,725 |
[
1,
1356,
326,
1024,
930,
316,
326,
6532,
18,
868,
31537,
309,
518,
711,
486,
1024,
930,
18,
225,
365,
1021,
2775,
18,
327,
1021,
1024,
930,
316,
326,
6532,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
1024,
12,
3198,
3778,
365,
13,
2713,
16618,
1135,
261,
54,
48,
1102,
874,
3778,
13,
288,
203,
565,
2583,
12,
5332,
2134,
12,
2890,
10019,
203,
203,
565,
2254,
6571,
273,
365,
18,
4285,
5263,
31,
203,
565,
2254,
761,
1782,
273,
389,
1726,
1782,
12,
6723,
1769,
203,
565,
365,
18,
4285,
5263,
273,
6571,
397,
761,
1782,
31,
203,
203,
565,
327,
534,
48,
1102,
874,
12,
1726,
1782,
16,
6571,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
/**
*
* @author <[email protected]>
*
* RDFDM - Riverdimes Fiat Donation Manager
* Version C
*
* Overview:
* four basic round-up operations are supported:
*
* A) fiatCollected: Record Fiat Donation (collection)
* inputs: charity (C), fiat amount ($XX.XX),
* summary: creates a log of a fiat donation to a specified charity, C.
* message: $XX.XX collected FBO Charity C, internal document #ABC
* - add $XX.XX to chariy's fiatBalanceIn, fiatCollected
*
* B) fiatToEth: Fiat Converted to ETH
* inputs: charity (C), fiat amount ($XX.XX), ETH amount (Z), document reference (ABC)
* summary: deduct $XX.XX from charity C's fiatBalanceIn; credit charity C's ethBalanceIn. this operation is invoked
* when fiat donations are converted to ETH. it includes a deposit of Z ETH.
* message(s): On behalf of Charity C, $XX.XX used to purchase Z ETH
* - $XX.XX deducted from charity C's fiatBalanceIn
* - skims 4% of Z for RD Token holders, and 16% for operational overhead
* - credits charity C with 80% of Z ETH (ethBalance)
*
* C) ethToFiat: ETH Converted to Fiat
* inputs: charity (C), ETH amount (Z), fiat amount ($XX.XX), document reference (ABC)
* summary: withdraw ETH from and convert to fiat
* message(s): Z ETH converted to $XX.XX FBO Charity C
* - deducts Z ETH from charity C's ethBalance
* - adds $XX.XX to charity C's fiatBalanceOut
*
* D) fiatDelivered: Record Fiat Delivery to Specified Charity
* inputs: charity (C), fiat amount ($XX.XX), document reference (ABC)
* summary: creates a log of a fiat delivery to a specified charity, C:
* message: $XX.XX delivered to Charity C, internal document #ABC
* - deducts the dollar amount, $XX.XX from charity's fiatBalanceOut
* - add $XX.XX to charity's totalDelivered
*
* one basic operation, unrelated to round-up
*
* A) ethDonation: Direct ETH Donation to Charity
* inputs: charity (C), ETH amount (Z), document reference (ABC)
* summary: ETH donation to a specified charity, crediting charity's ethBalance. ETH in transaction.
* messages: Z ETH donated to Charity C, internal document #ABC
* - add Z ETH to chariy's ethDonated
* - skims 0.5% of Z for RD Token holders, and 1.5% for operational overhead
* - credits charity C with 98% of Z ETH (ethBalance)
*
* in addition there are shortcut operations (related to round-up):
*
* A) fiatCollectedToEth: Record Fiat Donation (collection) and convert to ETH
* inputs: charity (C), fiat amount ($XX.XX), ETH amount (Z), document reference (ABC)
* summary: creates a log of a fiat donation to a specified charity, C; fiat donation is immediately converted to
* ETH, crediting charity C's ethBalance. the transaction includes a deposit of Z ETH.
* messages: $XX.XX collected FBO Charity C, internal document #ABC
* On behalf of Charity C, $XX.XX used to purchase Z ETH
* - add $XX.XX to chariy's fiatCollected
* - skims 4% of Z for RD Token holders, and 16% for operational overhead
* - credits charity C with 80% of Z ETH (ethBalance)
*
* B) ethToFiatDelivered: Record ETH Conversion to Fiat; and Fiat Delivery to Specified Charity
* inputs: charity (C), ETH amount (Z), fiat amount ($XX.XX), document reference (ABC)
* summary: withdraw ETH from charity C's ethBalance and convert to fiat; log fiat delivery of $XX.XX.
* messages: Z ETH converted to $XX.XX FBO Charity C
* $XX.XX delivered to Charity C, internal document #ABC
* - deducts Z ETH from charity C's ethBalance
* - add $XX.XX to charity's totalDelivered
*
*/
//import './SafeMath.sol';
//contract RDFDM is SafeMath
contract RDFDM {
//events relating to donation operations
//
event FiatCollectedEvent(uint indexed charity, uint usd, string ref);
event FiatToEthEvent(uint indexed charity, uint usd, uint eth);
event EthToFiatEvent(uint indexed charity, uint eth, uint usd);
event FiatDeliveredEvent(uint indexed charity, uint usd, string ref);
event EthDonationEvent(uint indexed charity, uint eth);
//events relating to adding and deleting charities
//
event CharityAddedEvent(uint indexed charity, string name, uint8 currency);
event CharityModifiedEvent(uint indexed charity, string name, uint8 currency);
//currencies
//
uint constant CURRENCY_USD = 0x01;
uint constant CURRENCY_EURO = 0x02;
uint constant CURRENCY_NIS = 0x03;
uint constant CURRENCY_YUAN = 0x04;
struct Charity {
uint fiatBalanceIn; // funds in external acct, collected fbo charity
uint fiatBalanceOut; // funds in external acct, pending delivery to charity
uint fiatCollected; // total collected since dawn of creation
uint fiatDelivered; // total delivered since dawn of creation
uint ethDonated; // total eth donated since dawn of creation
uint ethCredited; // total eth credited to this charity since dawn of creation
uint ethBalance; // current eth balance of this charity
uint fiatToEthPriceAccEth; // keep track of fiat to eth conversion price: total eth
uint fiatToEthPriceAccFiat; // keep track of fiat to eth conversion price: total fiat
uint ethToFiatPriceAccEth; // kkep track of eth to fiat conversion price: total eth
uint ethToFiatPriceAccFiat; // kkep track of eth to fiat conversion price: total fiat
uint8 currency; // fiat amounts are in smallest denomination of currency
string name; // eg. "Salvation Army"
}
uint public charityCount;
address public owner;
address public manager;
address public token; //token-holder fees sent to this address
address public operatorFeeAcct; //operations fees sent to this address
mapping (uint => Charity) public charities;
bool public isLocked;
modifier ownerOnly {
require(msg.sender == owner);
_;
}
modifier managerOnly {
require(msg.sender == owner || msg.sender == manager);
_;
}
modifier unlockedOnly {
require(!isLocked);
_;
}
//
//constructor
//
function RDFDM() public {
owner = msg.sender;
manager = msg.sender;
token = msg.sender;
operatorFeeAcct = msg.sender;
}
function lock() public ownerOnly { isLocked = true; }
function setToken(address _token) public ownerOnly unlockedOnly { token = _token; }
function setOperatorFeeAcct(address _operatorFeeAcct) public ownerOnly { operatorFeeAcct = _operatorFeeAcct; }
function setManager(address _manager) public managerOnly { manager = _manager; }
function deleteManager() public managerOnly { manager = owner; }
function addCharity(string _name, uint8 _currency) public managerOnly {
charities[charityCount].name = _name;
charities[charityCount].currency = _currency;
CharityAddedEvent(charityCount, _name, _currency);
++charityCount;
}
function modifyCharity(uint _charity, string _name, uint8 _currency) public managerOnly {
require(_charity < charityCount);
charities[_charity].name = _name;
charities[_charity].currency = _currency;
CharityModifiedEvent(_charity, _name, _currency);
}
//======== basic operations
function fiatCollected(uint _charity, uint _fiat, string _ref) public managerOnly {
require(_charity < charityCount);
charities[_charity].fiatBalanceIn += _fiat;
charities[_charity].fiatCollected += _fiat;
FiatCollectedEvent(_charity, _fiat, _ref);
}
function fiatToEth(uint _charity, uint _fiat) public managerOnly payable {
require(token != 0);
require(_charity < charityCount);
//keep track of fiat to eth conversion price
charities[_charity].fiatToEthPriceAccFiat += _fiat;
charities[_charity].fiatToEthPriceAccEth += msg.value;
charities[_charity].fiatBalanceIn -= _fiat;
uint _tokenCut = (msg.value * 4) / 100;
uint _operatorCut = (msg.value * 16) / 100;
uint _charityCredit = (msg.value - _operatorCut) - _tokenCut;
operatorFeeAcct.transfer(_operatorCut);
token.transfer(_tokenCut);
charities[_charity].ethBalance += _charityCredit;
charities[_charity].ethCredited += _charityCredit;
FiatToEthEvent(_charity, _fiat, msg.value);
}
function ethToFiat(uint _charity, uint _eth, uint _fiat) public managerOnly {
require(_charity < charityCount);
require(charities[_charity].ethBalance >= _eth);
//keep track of fiat to eth conversion price
charities[_charity].ethToFiatPriceAccFiat += _fiat;
charities[_charity].ethToFiatPriceAccEth += _eth;
charities[_charity].ethBalance -= _eth;
charities[_charity].fiatBalanceOut += _fiat;
//withdraw funds to the caller
msg.sender.transfer(_eth);
EthToFiatEvent(_charity, _eth, _fiat);
}
function fiatDelivered(uint _charity, uint _fiat, string _ref) public managerOnly {
require(_charity < charityCount);
require(charities[_charity].fiatBalanceOut >= _fiat);
charities[_charity].fiatBalanceOut -= _fiat;
charities[_charity].fiatDelivered += _fiat;
FiatDeliveredEvent(_charity, _fiat, _ref);
}
//======== unrelated to round-up
function ethDonation(uint _charity) public payable {
require(token != 0);
require(_charity < charityCount);
uint _tokenCut = (msg.value * 1) / 200;
uint _operatorCut = (msg.value * 3) / 200;
uint _charityCredit = (msg.value - _operatorCut) - _tokenCut;
operatorFeeAcct.transfer(_operatorCut);
token.transfer(_tokenCut);
charities[_charity].ethDonated += _charityCredit;
charities[_charity].ethBalance += _charityCredit;
charities[_charity].ethCredited += _charityCredit;
EthDonationEvent(_charity, msg.value);
}
//======== combo operations
function fiatCollectedToEth(uint _charity, uint _fiat, string _ref) public managerOnly payable {
require(token != 0);
require(_charity < charityCount);
charities[_charity].fiatCollected += _fiat;
//charities[_charity].fiatBalanceIn does not change, since we immediately convert to eth
//keep track of fiat to eth conversion price
charities[_charity].fiatToEthPriceAccFiat += _fiat;
charities[_charity].fiatToEthPriceAccEth += msg.value;
uint _tokenCut = (msg.value * 4) / 100;
uint _operatorCut = (msg.value * 16) / 100;
uint _charityCredit = (msg.value - _operatorCut) - _tokenCut;
operatorFeeAcct.transfer(_operatorCut);
token.transfer(_tokenCut);
charities[_charity].ethBalance += _charityCredit;
charities[_charity].ethCredited += _charityCredit;
FiatCollectedEvent(_charity, _fiat, _ref);
FiatToEthEvent(_charity, _fiat, msg.value);
}
function ethToFiatDelivered(uint _charity, uint _eth, uint _fiat, string _ref) public managerOnly {
require(_charity < charityCount);
require(charities[_charity].ethBalance >= _eth);
//keep track of fiat to eth conversion price
charities[_charity].ethToFiatPriceAccFiat += _fiat;
charities[_charity].ethToFiatPriceAccEth += _eth;
charities[_charity].ethBalance -= _eth;
//charities[_charity].fiatBalanceOut does not change, since we immediately deliver
//withdraw funds to the caller
msg.sender.transfer(_eth);
EthToFiatEvent(_charity, _eth, _fiat);
charities[_charity].fiatDelivered += _fiat;
FiatDeliveredEvent(_charity, _fiat, _ref);
}
//note: constant fcn does not need safe math
function quickAuditEthCredited(uint _charity) public constant returns (uint _fiatCollected,
uint _fiatToEthNotProcessed,
uint _fiatToEthProcessed,
uint _fiatToEthPricePerEth,
uint _fiatToEthCreditedFinney,
uint _fiatToEthAfterFeesFinney,
uint _ethDonatedFinney,
uint _ethDonatedAfterFeesFinney,
uint _totalEthCreditedFinney,
int _quickDiscrepancy) {
require(_charity < charityCount);
_fiatCollected = charities[_charity].fiatCollected; //eg. $450 = 45000
_fiatToEthNotProcessed = charities[_charity].fiatBalanceIn; //eg. 0
_fiatToEthProcessed = _fiatCollected - _fiatToEthNotProcessed; //eg. 45000
if (charities[_charity].fiatToEthPriceAccEth == 0) {
_fiatToEthPricePerEth = 0;
_fiatToEthCreditedFinney = 0;
} else {
_fiatToEthPricePerEth = (charities[_charity].fiatToEthPriceAccFiat * (1 ether)) / //eg. 45000 * 10^18 = 45 * 10^21
charities[_charity].fiatToEthPriceAccEth; //eg 1.5 ETH = 15 * 10^17
// --------------------
// 3 * 10^4 (30000 cents per ether)
_fiatToEthCreditedFinney = _fiatToEthProcessed * (1 ether / 1 finney) / _fiatToEthPricePerEth; //eg. 45000 * 1000 / 30000 = 1500 (finney)
_fiatToEthAfterFeesFinney = _fiatToEthCreditedFinney * 8 / 10; //eg. 1500 * 8 / 10 = 1200 (finney)
}
_ethDonatedFinney = charities[_charity].ethDonated / (1 finney); //eg. 1 ETH = 1 * 10^18 / 10^15 = 1000 (finney)
_ethDonatedAfterFeesFinney = _ethDonatedFinney * 98 / 100; //eg. 1000 * 98/100 = 980 (finney)
_totalEthCreditedFinney = _fiatToEthAfterFeesFinney + _ethDonatedAfterFeesFinney; //eg 1200 + 980 = 2180 (finney)
uint256 tecf = charities[_charity].ethCredited * (1 ether / 1 finney);
_quickDiscrepancy = int256(_totalEthCreditedFinney) - int256(tecf);
}
//note: contant fcn does not need safe math
function quickAuditFiatDelivered(uint _charity) public constant returns (
uint _totalEthCreditedFinney,
uint _ethNotProcessedFinney,
uint _processedEthCreditedFinney,
uint _ethToFiatPricePerEth,
uint _ethToFiatCreditedFiat,
uint _ethToFiatNotProcessed,
uint _ethToFiatProcessed,
uint _fiatDelivered,
int _quickDiscrepancy) {
require(_charity < charityCount);
_totalEthCreditedFinney = charities[_charity].ethCredited * (1 ether / 1 finney);
_ethNotProcessedFinney = charities[_charity].ethBalance / (1 finney); //eg. 1 ETH = 1 * 10^18 / 10^15 = 1000 (finney)
_processedEthCreditedFinney = _totalEthCreditedFinney - _ethNotProcessedFinney; //eg 1180 finney
if (charities[_charity].ethToFiatPriceAccEth == 0) {
_ethToFiatPricePerEth = 0;
_ethToFiatCreditedFiat = 0;
} else {
_ethToFiatPricePerEth = (charities[_charity].ethToFiatPriceAccFiat * (1 ether)) / //eg. 29400 * 10^18 = 2940000 * 10^16
charities[_charity].ethToFiatPriceAccEth; //eg 0.980 ETH = 98 * 10^16
// --------------------
// 30000 (30000 cents per ether)
_ethToFiatCreditedFiat = _processedEthCreditedFinney * _ethToFiatPricePerEth / (1 ether / 1 finney); //eg. 1180 * 30000 / 1000 = 35400
}
_ethToFiatNotProcessed = charities[_charity].fiatBalanceOut;
_ethToFiatProcessed = _ethToFiatCreditedFiat - _ethToFiatNotProcessed;
_fiatDelivered = charities[_charity].fiatDelivered;
_quickDiscrepancy = int256(_ethToFiatProcessed) - int256(_fiatDelivered);
}
//
// default payable function.
//
function () public payable {
revert();
}
//for debug
//only available before the contract is locked
function haraKiri() public ownerOnly unlockedOnly {
selfdestruct(owner);
}
}
|
======== unrelated to round-up
|
function ethDonation(uint _charity) public payable {
require(token != 0);
require(_charity < charityCount);
uint _tokenCut = (msg.value * 1) / 200;
uint _operatorCut = (msg.value * 3) / 200;
uint _charityCredit = (msg.value - _operatorCut) - _tokenCut;
operatorFeeAcct.transfer(_operatorCut);
token.transfer(_tokenCut);
charities[_charity].ethDonated += _charityCredit;
charities[_charity].ethBalance += _charityCredit;
charities[_charity].ethCredited += _charityCredit;
EthDonationEvent(_charity, msg.value);
}
| 12,613,681 |
[
1,
1432,
640,
9243,
358,
3643,
17,
416,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
13750,
22293,
367,
12,
11890,
389,
3001,
560,
13,
1071,
8843,
429,
288,
203,
565,
2583,
12,
2316,
480,
374,
1769,
203,
565,
2583,
24899,
3001,
560,
411,
1149,
560,
1380,
1769,
203,
565,
2254,
389,
2316,
15812,
273,
261,
3576,
18,
1132,
380,
404,
13,
342,
4044,
31,
203,
565,
2254,
389,
9497,
15812,
273,
261,
3576,
18,
1132,
380,
890,
13,
342,
4044,
31,
203,
565,
2254,
389,
3001,
560,
16520,
273,
261,
3576,
18,
1132,
300,
389,
9497,
15812,
13,
300,
389,
2316,
15812,
31,
203,
565,
3726,
14667,
9988,
299,
18,
13866,
24899,
9497,
15812,
1769,
203,
565,
1147,
18,
13866,
24899,
2316,
15812,
1769,
203,
565,
1149,
1961,
63,
67,
3001,
560,
8009,
546,
22293,
690,
1011,
389,
3001,
560,
16520,
31,
203,
565,
1149,
1961,
63,
67,
3001,
560,
8009,
546,
13937,
1011,
389,
3001,
560,
16520,
31,
203,
565,
1149,
1961,
63,
67,
3001,
560,
8009,
546,
16520,
329,
1011,
389,
3001,
560,
16520,
31,
203,
565,
512,
451,
22293,
367,
1133,
24899,
3001,
560,
16,
1234,
18,
1132,
1769,
203,
225,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "./PrizePoolBuilder.sol";
import "../registry/RegistryInterface.sol";
import "../prize-pool/compound/CompoundPrizePoolProxyFactory.sol";
import "../external/compound/CTokenInterface.sol";
/// @title Creates new Compound Prize Pools
/* solium-disable security/no-block-members */
contract CompoundPrizePoolBuilder is PrizePoolBuilder {
using SafeMathUpgradeable for uint256;
using SafeCastUpgradeable for uint256;
/// @notice The configuration used to initialize the Compound Prize Pool
struct CompoundPrizePoolConfig {
CTokenInterface cToken;
uint256 maxExitFeeMantissa;
uint256 maxTimelockDuration;
}
RegistryInterface public reserveRegistry;
CompoundPrizePoolProxyFactory public compoundPrizePoolProxyFactory;
constructor (
RegistryInterface _reserveRegistry,
CompoundPrizePoolProxyFactory _compoundPrizePoolProxyFactory
) public {
require(address(_reserveRegistry) != address(0), "CompoundPrizePoolBuilder/reserveRegistry-not-zero");
require(address(_compoundPrizePoolProxyFactory) != address(0), "CompoundPrizePoolBuilder/compound-prize-pool-builder-not-zero");
reserveRegistry = _reserveRegistry;
compoundPrizePoolProxyFactory = _compoundPrizePoolProxyFactory;
}
/// @notice Creates a new Compound Prize Pool with a preconfigured prize strategy.
/// @param config The config to use to initialize the Compound Prize Pool
/// @return The Compound Prize Pool
function createCompoundPrizePool(
CompoundPrizePoolConfig calldata config
)
external
returns (CompoundPrizePool)
{
CompoundPrizePool prizePool = compoundPrizePoolProxyFactory.create();
ControlledTokenInterface[] memory tokens;
prizePool.initialize(
reserveRegistry,
tokens,
config.maxExitFeeMantissa,
config.maxTimelockDuration,
config.cToken
);
prizePool.transferOwnership(msg.sender);
emit PrizePoolCreated(msg.sender, address(prizePool));
return prizePool;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "../prize-pool/PrizePool.sol";
import "../prize-strategy/PeriodicPrizeStrategy.sol";
contract PrizePoolBuilder {
using SafeCastUpgradeable for uint256;
event PrizePoolCreated (
address indexed creator,
address indexed prizePool
);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@pooltogether/fixed-point/contracts/FixedPoint.sol";
import "../registry/RegistryInterface.sol";
import "../reserve/ReserveInterface.sol";
import "./YieldSource.sol";
import "../token/TokenListenerInterface.sol";
import "../token/TokenListenerLibrary.sol";
import "../token/ControlledToken.sol";
import "../token/TokenControllerInterface.sol";
import "../utils/MappedSinglyLinkedList.sol";
import "./PrizePoolInterface.sol";
/// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool.
/// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract.
/// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens
abstract contract PrizePool is PrizePoolInterface, YieldSource, OwnableUpgradeable, ReentrancyGuardUpgradeable, TokenControllerInterface {
using SafeMathUpgradeable for uint256;
using SafeCastUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping;
using ERC165CheckerUpgradeable for address;
/// @dev Emitted when an instance is initialized
event Initialized(
address reserveRegistry,
uint256 maxExitFeeMantissa,
uint256 maxTimelockDuration
);
/// @dev Event emitted when controlled token is added
event ControlledTokenAdded(
ControlledTokenInterface indexed token
);
/// @dev Emitted when reserve is captured.
event ReserveFeeCaptured(
uint256 amount
);
event AwardCaptured(
uint256 amount
);
/// @dev Event emitted when assets are deposited
event Deposited(
address indexed operator,
address indexed to,
address indexed token,
uint256 amount,
address referrer
);
/// @dev Event emitted when timelocked funds are re-deposited
event TimelockDeposited(
address indexed operator,
address indexed to,
address indexed token,
uint256 amount
);
/// @dev Event emitted when interest is awarded to a winner
event Awarded(
address indexed winner,
address indexed token,
uint256 amount
);
/// @dev Event emitted when external ERC20s are awarded to a winner
event AwardedExternalERC20(
address indexed winner,
address indexed token,
uint256 amount
);
/// @dev Event emitted when external ERC20s are transferred out
event TransferredExternalERC20(
address indexed to,
address indexed token,
uint256 amount
);
/// @dev Event emitted when external ERC721s are awarded to a winner
event AwardedExternalERC721(
address indexed winner,
address indexed token,
uint256[] tokenIds
);
/// @dev Event emitted when assets are withdrawn instantly
event InstantWithdrawal(
address indexed operator,
address indexed from,
address indexed token,
uint256 amount,
uint256 redeemed,
uint256 exitFee
);
/// @dev Event emitted upon a withdrawal with timelock
event TimelockedWithdrawal(
address indexed operator,
address indexed from,
address indexed token,
uint256 amount,
uint256 unlockTimestamp
);
event ReserveWithdrawal(
address indexed to,
uint256 amount
);
/// @dev Event emitted when timelocked funds are swept back to a user
event TimelockedWithdrawalSwept(
address indexed operator,
address indexed from,
uint256 amount,
uint256 redeemed
);
/// @dev Event emitted when the Liquidity Cap is set
event LiquidityCapSet(
uint256 liquidityCap
);
/// @dev Event emitted when the Credit plan is set
event CreditPlanSet(
address token,
uint128 creditLimitMantissa,
uint128 creditRateMantissa
);
/// @dev Event emitted when the Prize Strategy is set
event PrizeStrategySet(
address indexed prizeStrategy
);
/// @dev Emitted when credit is minted
event CreditMinted(
address indexed user,
address indexed token,
uint256 amount
);
/// @dev Emitted when credit is burned
event CreditBurned(
address indexed user,
address indexed token,
uint256 amount
);
struct CreditPlan {
uint128 creditLimitMantissa;
uint128 creditRateMantissa;
}
struct CreditBalance {
uint192 balance;
uint32 timestamp;
bool initialized;
}
/// @dev Reserve to which reserve fees are sent
RegistryInterface public reserveRegistry;
/// @dev A linked list of all the controlled tokens
MappedSinglyLinkedList.Mapping internal _tokens;
/// @dev The Prize Strategy that this Prize Pool is bound to.
TokenListenerInterface public prizeStrategy;
/// @dev The maximum possible exit fee fraction as a fixed point 18 number.
/// For example, if the maxExitFeeMantissa is "0.1 ether", then the maximum exit fee for a withdrawal of 100 Dai will be 10 Dai
uint256 public maxExitFeeMantissa;
/// @dev The maximum possible timelock duration for a timelocked withdrawal (in seconds).
uint256 public maxTimelockDuration;
/// @dev The total funds that are timelocked.
uint256 public timelockTotalSupply;
/// @dev The total funds that have been allocated to the reserve
uint256 public reserveTotalSupply;
/// @dev The total amount of funds that the prize pool can hold.
uint256 public liquidityCap;
/// @dev the The awardable balance
uint256 internal _currentAwardBalance;
/// @dev The timelocked balances for each user
mapping(address => uint256) internal _timelockBalances;
/// @dev The unlock timestamps for each user
mapping(address => uint256) internal _unlockTimestamps;
/// @dev Stores the credit plan for each token.
mapping(address => CreditPlan) internal _tokenCreditPlans;
/// @dev Stores each users balance of credit per token.
mapping(address => mapping(address => CreditBalance)) internal _tokenCreditBalances;
/// @notice Initializes the Prize Pool
/// @param _controlledTokens Array of ControlledTokens that are controlled by this Prize Pool.
/// @param _maxExitFeeMantissa The maximum exit fee size
/// @param _maxTimelockDuration The maximum length of time the withdraw timelock
function initialize (
RegistryInterface _reserveRegistry,
ControlledTokenInterface[] memory _controlledTokens,
uint256 _maxExitFeeMantissa,
uint256 _maxTimelockDuration
)
public
initializer
{
require(address(_reserveRegistry) != address(0), "PrizePool/reserveRegistry-not-zero");
_tokens.initialize();
for (uint256 i = 0; i < _controlledTokens.length; i++) {
_addControlledToken(_controlledTokens[i]);
}
__Ownable_init();
__ReentrancyGuard_init();
_setLiquidityCap(uint256(-1));
reserveRegistry = _reserveRegistry;
maxExitFeeMantissa = _maxExitFeeMantissa;
maxTimelockDuration = _maxTimelockDuration;
emit Initialized(
address(_reserveRegistry),
maxExitFeeMantissa,
maxTimelockDuration
);
}
/// @dev Returns the address of the underlying ERC20 asset
/// @return The address of the asset
function token() external override view returns (address) {
return address(_token());
}
/// @dev Returns the total underlying balance of all assets. This includes both principal and interest.
/// @return The underlying balance of assets
function balance() external returns (uint256) {
return _balance();
}
/// @dev Checks with the Prize Pool if a specific token type may be awarded as an external prize
/// @param _externalToken The address of the token to check
/// @return True if the token may be awarded, false otherwise
function canAwardExternal(address _externalToken) external view returns (bool) {
return _canAwardExternal(_externalToken);
}
/// @notice Deposits timelocked tokens for a user back into the Prize Pool as another asset.
/// @param to The address receiving the tokens
/// @param amount The amount of timelocked assets to re-deposit
/// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship)
function timelockDepositTo(
address to,
uint256 amount,
address controlledToken
)
external
onlyControlledToken(controlledToken)
canAddLiquidity(amount)
nonReentrant
{
address operator = _msgSender();
_mint(to, amount, controlledToken, address(0));
_timelockBalances[operator] = _timelockBalances[operator].sub(amount);
timelockTotalSupply = timelockTotalSupply.sub(amount);
emit TimelockDeposited(operator, to, controlledToken, amount);
}
/// @notice Deposit assets into the Prize Pool in exchange for tokens
/// @param to The address receiving the newly minted tokens
/// @param amount The amount of assets to deposit
/// @param controlledToken The address of the type of token the user is minting
/// @param referrer The referrer of the deposit
function depositTo(
address to,
uint256 amount,
address controlledToken,
address referrer
)
external override
onlyControlledToken(controlledToken)
canAddLiquidity(amount)
nonReentrant
{
address operator = _msgSender();
_mint(to, amount, controlledToken, referrer);
_token().safeTransferFrom(operator, address(this), amount);
_supply(amount);
emit Deposited(operator, to, controlledToken, amount, referrer);
}
/// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit.
/// @param from The address to redeem tokens from.
/// @param amount The amount of tokens to redeem for assets.
/// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship)
/// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn.
/// @return The actual exit fee paid
function withdrawInstantlyFrom(
address from,
uint256 amount,
address controlledToken,
uint256 maximumExitFee
)
external override
nonReentrant
onlyControlledToken(controlledToken)
returns (uint256)
{
(uint256 exitFee, uint256 burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount);
require(exitFee <= maximumExitFee, "PrizePool/exit-fee-exceeds-user-maximum");
// burn the credit
_burnCredit(from, controlledToken, burnedCredit);
// burn the tickets
ControlledToken(controlledToken).controllerBurnFrom(_msgSender(), from, amount);
// redeem the tickets less the fee
uint256 amountLessFee = amount.sub(exitFee);
uint256 redeemed = _redeem(amountLessFee);
_token().safeTransfer(from, redeemed);
emit InstantWithdrawal(_msgSender(), from, controlledToken, amount, redeemed, exitFee);
return exitFee;
}
/// @notice Limits the exit fee to the maximum as hard-coded into the contract
/// @param withdrawalAmount The amount that is attempting to be withdrawn
/// @param exitFee The exit fee to check against the limit
/// @return The passed exit fee if it is less than the maximum, otherwise the maximum fee is returned.
function _limitExitFee(uint256 withdrawalAmount, uint256 exitFee) internal view returns (uint256) {
uint256 maxFee = FixedPoint.multiplyUintByMantissa(withdrawalAmount, maxExitFeeMantissa);
if (exitFee > maxFee) {
exitFee = maxFee;
}
return exitFee;
}
/// @notice Withdraw assets from the Prize Pool by placing them into the timelock.
/// The timelock is used to ensure that the tickets have contributed their fair share of the prize.
/// @dev Note that if the user has previously timelocked funds then this contract will try to sweep them.
/// If the existing timelocked funds are still locked, then the incoming
/// balance is added to their existing balance and the new timelock unlock timestamp will overwrite the old one.
/// @param from The address to withdraw from
/// @param amount The amount to withdraw
/// @param controlledToken The type of token being withdrawn
/// @return The timestamp from which the funds can be swept
function withdrawWithTimelockFrom(
address from,
uint256 amount,
address controlledToken
)
external override
nonReentrant
onlyControlledToken(controlledToken)
returns (uint256)
{
uint256 blockTime = _currentTime();
(uint256 lockDuration, uint256 burnedCredit) = _calculateTimelockDuration(from, controlledToken, amount);
uint256 unlockTimestamp = blockTime.add(lockDuration);
_burnCredit(from, controlledToken, burnedCredit);
ControlledToken(controlledToken).controllerBurnFrom(_msgSender(), from, amount);
_mintTimelock(from, amount, unlockTimestamp);
emit TimelockedWithdrawal(_msgSender(), from, controlledToken, amount, unlockTimestamp);
// return the block at which the funds will be available
return unlockTimestamp;
}
/// @notice Adds to a user's timelock balance. It will attempt to sweep before updating the balance.
/// Note that this will overwrite the previous unlock timestamp.
/// @param user The user whose timelock balance should increase
/// @param amount The amount to increase by
/// @param timestamp The new unlock timestamp
function _mintTimelock(address user, uint256 amount, uint256 timestamp) internal {
// Sweep the old balance, if any
address[] memory users = new address[](1);
users[0] = user;
_sweepTimelockBalances(users);
timelockTotalSupply = timelockTotalSupply.add(amount);
_timelockBalances[user] = _timelockBalances[user].add(amount);
_unlockTimestamps[user] = timestamp;
// if the funds should already be unlocked
if (timestamp <= _currentTime()) {
_sweepTimelockBalances(users);
}
}
/// @notice Updates the Prize Strategy when tokens are transferred between holders.
/// @param from The address the tokens are being transferred from (0 if minting)
/// @param to The address the tokens are being transferred to (0 if burning)
/// @param amount The amount of tokens being trasferred
function beforeTokenTransfer(address from, address to, uint256 amount) external override onlyControlledToken(msg.sender) {
if (from != address(0)) {
uint256 fromBeforeBalance = IERC20Upgradeable(msg.sender).balanceOf(from);
// first accrue credit for their old balance
uint256 newCreditBalance = _calculateCreditBalance(from, msg.sender, fromBeforeBalance, 0);
if (from != to) {
// if they are sending funds to someone else, we need to limit their accrued credit to their new balance
newCreditBalance = _applyCreditLimit(msg.sender, fromBeforeBalance.sub(amount), newCreditBalance);
}
_updateCreditBalance(from, msg.sender, newCreditBalance);
}
if (to != address(0) && to != from) {
_accrueCredit(to, msg.sender, IERC20Upgradeable(msg.sender).balanceOf(to), 0);
}
// if we aren't minting
if (from != address(0) && address(prizeStrategy) != address(0)) {
prizeStrategy.beforeTokenTransfer(from, to, amount, msg.sender);
}
}
/// @notice Returns the balance that is available to award.
/// @dev captureAwardBalance() should be called first
/// @return The total amount of assets to be awarded for the current prize
function awardBalance() external override view returns (uint256) {
return _currentAwardBalance;
}
/// @notice Captures any available interest as award balance.
/// @dev This function also captures the reserve fees.
/// @return The total amount of assets to be awarded for the current prize
function captureAwardBalance() external override nonReentrant returns (uint256) {
uint256 tokenTotalSupply = _tokenTotalSupply();
// it's possible for the balance to be slightly less due to rounding errors in the underlying yield source
uint256 currentBalance = _balance();
uint256 totalInterest = (currentBalance > tokenTotalSupply) ? currentBalance.sub(tokenTotalSupply) : 0;
uint256 unaccountedPrizeBalance = (totalInterest > _currentAwardBalance) ? totalInterest.sub(_currentAwardBalance) : 0;
if (unaccountedPrizeBalance > 0) {
uint256 reserveFee = calculateReserveFee(unaccountedPrizeBalance);
if (reserveFee > 0) {
reserveTotalSupply = reserveTotalSupply.add(reserveFee);
unaccountedPrizeBalance = unaccountedPrizeBalance.sub(reserveFee);
emit ReserveFeeCaptured(reserveFee);
}
_currentAwardBalance = _currentAwardBalance.add(unaccountedPrizeBalance);
emit AwardCaptured(unaccountedPrizeBalance);
}
return _currentAwardBalance;
}
function withdrawReserve(address to) external override onlyReserve returns (uint256) {
uint256 amount = reserveTotalSupply;
reserveTotalSupply = 0;
uint256 redeemed = _redeem(amount);
_token().safeTransfer(address(to), redeemed);
emit ReserveWithdrawal(to, amount);
return redeemed;
}
/// @notice Called by the prize strategy to award prizes.
/// @dev The amount awarded must be less than the awardBalance()
/// @param to The address of the winner that receives the award
/// @param amount The amount of assets to be awarded
/// @param controlledToken The address of the asset token being awarded
function award(
address to,
uint256 amount,
address controlledToken
)
external override
onlyPrizeStrategy
onlyControlledToken(controlledToken)
{
if (amount == 0) {
return;
}
require(amount <= _currentAwardBalance, "PrizePool/award-exceeds-avail");
_currentAwardBalance = _currentAwardBalance.sub(amount);
_mint(to, amount, controlledToken, address(0));
uint256 extraCredit = _calculateEarlyExitFeeNoCredit(controlledToken, amount);
_accrueCredit(to, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(to), extraCredit);
emit Awarded(to, controlledToken, amount);
}
/// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens
/// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything.
/// @param to The address of the winner that receives the award
/// @param amount The amount of external assets to be awarded
/// @param externalToken The address of the external asset token being awarded
function transferExternalERC20(
address to,
address externalToken,
uint256 amount
)
external override
onlyPrizeStrategy
{
if (_transferOut(to, externalToken, amount)) {
emit TransferredExternalERC20(to, externalToken, amount);
}
}
/// @notice Called by the Prize-Strategy to award external ERC20 prizes
/// @dev Used to award any arbitrary tokens held by the Prize Pool
/// @param to The address of the winner that receives the award
/// @param amount The amount of external assets to be awarded
/// @param externalToken The address of the external asset token being awarded
function awardExternalERC20(
address to,
address externalToken,
uint256 amount
)
external override
onlyPrizeStrategy
{
if (_transferOut(to, externalToken, amount)) {
emit AwardedExternalERC20(to, externalToken, amount);
}
}
function _transferOut(
address to,
address externalToken,
uint256 amount
)
internal
returns (bool)
{
require(_canAwardExternal(externalToken), "PrizePool/invalid-external-token");
if (amount == 0) {
return false;
}
IERC20Upgradeable(externalToken).safeTransfer(to, amount);
return true;
}
/// @notice Called to mint controlled tokens. Ensures that token listener callbacks are fired.
/// @param to The user who is receiving the tokens
/// @param amount The amount of tokens they are receiving
/// @param controlledToken The token that is going to be minted
/// @param referrer The user who referred the minting
function _mint(address to, uint256 amount, address controlledToken, address referrer) internal {
if (address(prizeStrategy) != address(0)) {
prizeStrategy.beforeTokenMint(to, amount, controlledToken, referrer);
}
ControlledToken(controlledToken).controllerMint(to, amount);
}
/// @notice Called by the prize strategy to award external ERC721 prizes
/// @dev Used to award any arbitrary NFTs held by the Prize Pool
/// @param to The address of the winner that receives the award
/// @param externalToken The address of the external NFT token being awarded
/// @param tokenIds An array of NFT Token IDs to be transferred
function awardExternalERC721(
address to,
address externalToken,
uint256[] calldata tokenIds
)
external override
onlyPrizeStrategy
{
require(_canAwardExternal(externalToken), "PrizePool/invalid-external-token");
if (tokenIds.length == 0) {
return;
}
for (uint256 i = 0; i < tokenIds.length; i++) {
IERC721Upgradeable(externalToken).transferFrom(address(this), to, tokenIds[i]);
}
emit AwardedExternalERC721(to, externalToken, tokenIds);
}
/// @notice Calculates the reserve portion of the given amount of funds. If there is no reserve address, the portion will be zero.
/// @param amount The prize amount
/// @return The size of the reserve portion of the prize
function calculateReserveFee(uint256 amount) public view returns (uint256) {
ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup());
if (address(reserve) == address(0)) {
return 0;
}
uint256 reserveRateMantissa = reserve.reserveRateMantissa(address(this));
if (reserveRateMantissa == 0) {
return 0;
}
return FixedPoint.multiplyUintByMantissa(amount, reserveRateMantissa);
}
/// @notice Sweep all timelocked balances and transfer unlocked assets to owner accounts
/// @param users An array of account addresses to sweep balances for
/// @return The total amount of assets swept from the Prize Pool
function sweepTimelockBalances(
address[] calldata users
)
external override
nonReentrant
returns (uint256)
{
return _sweepTimelockBalances(users);
}
/// @notice Sweep available timelocked balances to their owners. The full balances will be swept to the owners.
/// @param users An array of owner addresses
/// @return The total amount of assets swept from the Prize Pool
function _sweepTimelockBalances(
address[] memory users
)
internal
returns (uint256)
{
address operator = _msgSender();
uint256[] memory balances = new uint256[](users.length);
uint256 totalWithdrawal;
uint256 i;
for (i = 0; i < users.length; i++) {
address user = users[i];
if (_unlockTimestamps[user] <= _currentTime()) {
totalWithdrawal = totalWithdrawal.add(_timelockBalances[user]);
balances[i] = _timelockBalances[user];
delete _timelockBalances[user];
}
}
// if there is nothing to do, just quit
if (totalWithdrawal == 0) {
return 0;
}
timelockTotalSupply = timelockTotalSupply.sub(totalWithdrawal);
uint256 redeemed = _redeem(totalWithdrawal);
IERC20Upgradeable underlyingToken = IERC20Upgradeable(_token());
for (i = 0; i < users.length; i++) {
if (balances[i] > 0) {
delete _unlockTimestamps[users[i]];
uint256 shareMantissa = FixedPoint.calculateMantissa(balances[i], totalWithdrawal);
uint256 transferAmount = FixedPoint.multiplyUintByMantissa(redeemed, shareMantissa);
underlyingToken.safeTransfer(users[i], transferAmount);
emit TimelockedWithdrawalSwept(operator, users[i], balances[i], transferAmount);
}
}
return totalWithdrawal;
}
/// @notice Calculates a timelocked withdrawal duration and credit consumption.
/// @param from The user who is withdrawing
/// @param amount The amount the user is withdrawing
/// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship)
/// @return durationSeconds The duration of the timelock in seconds
function calculateTimelockDuration(
address from,
address controlledToken,
uint256 amount
)
external override
returns (
uint256 durationSeconds,
uint256 burnedCredit
)
{
return _calculateTimelockDuration(from, controlledToken, amount);
}
/// @dev Calculates a timelocked withdrawal duration and credit consumption.
/// @param from The user who is withdrawing
/// @param amount The amount the user is withdrawing
/// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship)
/// @return durationSeconds The duration of the timelock in seconds
/// @return burnedCredit The credit that was burned
function _calculateTimelockDuration(
address from,
address controlledToken,
uint256 amount
)
internal
returns (
uint256 durationSeconds,
uint256 burnedCredit
)
{
(uint256 exitFee, uint256 _burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount);
uint256 duration = _estimateCreditAccrualTime(controlledToken, amount, exitFee);
if (duration > maxTimelockDuration) {
duration = maxTimelockDuration;
}
return (duration, _burnedCredit);
}
/// @notice Calculates the early exit fee for the given amount
/// @param from The user who is withdrawing
/// @param controlledToken The type of collateral being withdrawn
/// @param amount The amount of collateral to be withdrawn
/// @return exitFee The exit fee
/// @return burnedCredit The user's credit that was burned
function calculateEarlyExitFee(
address from,
address controlledToken,
uint256 amount
)
external override
returns (
uint256 exitFee,
uint256 burnedCredit
)
{
return _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount);
}
/// @dev Calculates the early exit fee for the given amount
/// @param amount The amount of collateral to be withdrawn
/// @return Exit fee
function _calculateEarlyExitFeeNoCredit(address controlledToken, uint256 amount) internal view returns (uint256) {
return _limitExitFee(
amount,
FixedPoint.multiplyUintByMantissa(amount, _tokenCreditPlans[controlledToken].creditLimitMantissa)
);
}
/// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit.
/// @param _principal The principal amount on which interest is accruing
/// @param _interest The amount of interest that must accrue
/// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds.
function estimateCreditAccrualTime(
address _controlledToken,
uint256 _principal,
uint256 _interest
)
external override
view
returns (uint256 durationSeconds)
{
return _estimateCreditAccrualTime(
_controlledToken,
_principal,
_interest
);
}
/// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit
/// @param _principal The principal amount on which interest is accruing
/// @param _interest The amount of interest that must accrue
/// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds.
function _estimateCreditAccrualTime(
address _controlledToken,
uint256 _principal,
uint256 _interest
)
internal
view
returns (uint256 durationSeconds)
{
// interest = credit rate * principal * time
// => time = interest / (credit rate * principal)
uint256 accruedPerSecond = FixedPoint.multiplyUintByMantissa(_principal, _tokenCreditPlans[_controlledToken].creditRateMantissa);
if (accruedPerSecond == 0) {
return 0;
}
return _interest.div(accruedPerSecond);
}
/// @notice Burns a users credit.
/// @param user The user whose credit should be burned
/// @param credit The amount of credit to burn
function _burnCredit(address user, address controlledToken, uint256 credit) internal {
_tokenCreditBalances[controlledToken][user].balance = uint256(_tokenCreditBalances[controlledToken][user].balance).sub(credit).toUint128();
emit CreditBurned(user, controlledToken, credit);
}
/// @notice Accrues ticket credit for a user assuming their current balance is the passed balance. May burn credit if they exceed their limit.
/// @param user The user for whom to accrue credit
/// @param controlledToken The controlled token whose balance we are checking
/// @param controlledTokenBalance The balance to use for the user
/// @param extra Additional credit to be added
function _accrueCredit(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal {
_updateCreditBalance(
user,
controlledToken,
_calculateCreditBalance(user, controlledToken, controlledTokenBalance, extra)
);
}
function _calculateCreditBalance(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal view returns (uint256) {
uint256 newBalance;
CreditBalance storage creditBalance = _tokenCreditBalances[controlledToken][user];
if (!creditBalance.initialized) {
newBalance = 0;
} else {
uint256 credit = _calculateAccruedCredit(user, controlledToken, controlledTokenBalance);
newBalance = _applyCreditLimit(controlledToken, controlledTokenBalance, uint256(creditBalance.balance).add(credit).add(extra));
}
return newBalance;
}
function _updateCreditBalance(address user, address controlledToken, uint256 newBalance) internal {
uint256 oldBalance = _tokenCreditBalances[controlledToken][user].balance;
_tokenCreditBalances[controlledToken][user] = CreditBalance({
balance: newBalance.toUint128(),
timestamp: _currentTime().toUint32(),
initialized: true
});
if (oldBalance < newBalance) {
emit CreditMinted(user, controlledToken, newBalance.sub(oldBalance));
} else {
emit CreditBurned(user, controlledToken, oldBalance.sub(newBalance));
}
}
/// @notice Applies the credit limit to a credit balance. The balance cannot exceed the credit limit.
/// @param controlledToken The controlled token that the user holds
/// @param controlledTokenBalance The users ticket balance (used to calculate credit limit)
/// @param creditBalance The new credit balance to be checked
/// @return The users new credit balance. Will not exceed the credit limit.
function _applyCreditLimit(address controlledToken, uint256 controlledTokenBalance, uint256 creditBalance) internal view returns (uint256) {
uint256 creditLimit = FixedPoint.multiplyUintByMantissa(
controlledTokenBalance,
_tokenCreditPlans[controlledToken].creditLimitMantissa
);
if (creditBalance > creditLimit) {
creditBalance = creditLimit;
}
return creditBalance;
}
/// @notice Calculates the accrued interest for a user
/// @param user The user whose credit should be calculated.
/// @param controlledToken The controlled token that the user holds
/// @param controlledTokenBalance The user's current balance of the controlled tokens.
/// @return The credit that has accrued since the last credit update.
function _calculateAccruedCredit(address user, address controlledToken, uint256 controlledTokenBalance) internal view returns (uint256) {
uint256 userTimestamp = _tokenCreditBalances[controlledToken][user].timestamp;
if (!_tokenCreditBalances[controlledToken][user].initialized) {
return 0;
}
uint256 deltaTime = _currentTime().sub(userTimestamp);
uint256 creditPerSecond = FixedPoint.multiplyUintByMantissa(controlledTokenBalance, _tokenCreditPlans[controlledToken].creditRateMantissa);
return deltaTime.mul(creditPerSecond);
}
/// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit.
/// @param user The user whose credit balance should be returned
/// @return The balance of the users credit
function balanceOfCredit(address user, address controlledToken) external override onlyControlledToken(controlledToken) returns (uint256) {
_accrueCredit(user, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(user), 0);
return _tokenCreditBalances[controlledToken][user].balance;
}
/// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether).
/// @param _controlledToken The controlled token for whom to set the credit plan
/// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether).
/// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether).
function setCreditPlanOf(
address _controlledToken,
uint128 _creditRateMantissa,
uint128 _creditLimitMantissa
)
external override
onlyControlledToken(_controlledToken)
onlyOwner
{
_tokenCreditPlans[_controlledToken] = CreditPlan({
creditLimitMantissa: _creditLimitMantissa,
creditRateMantissa: _creditRateMantissa
});
emit CreditPlanSet(_controlledToken, _creditLimitMantissa, _creditRateMantissa);
}
/// @notice Returns the credit rate of a controlled token
/// @param controlledToken The controlled token to retrieve the credit rates for
/// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee.
/// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second.
function creditPlanOf(
address controlledToken
)
external override
view
returns (
uint128 creditLimitMantissa,
uint128 creditRateMantissa
)
{
creditLimitMantissa = _tokenCreditPlans[controlledToken].creditLimitMantissa;
creditRateMantissa = _tokenCreditPlans[controlledToken].creditRateMantissa;
}
/// @notice Calculate the early exit for a user given a withdrawal amount. The user's credit is taken into account.
/// @param from The user who is withdrawing
/// @param controlledToken The token they are withdrawing
/// @param amount The amount of funds they are withdrawing
/// @return earlyExitFee The additional exit fee that should be charged.
/// @return creditBurned The amount of credit that will be burned
function _calculateEarlyExitFeeLessBurnedCredit(
address from,
address controlledToken,
uint256 amount
)
internal
returns (
uint256 earlyExitFee,
uint256 creditBurned
)
{
uint256 controlledTokenBalance = IERC20Upgradeable(controlledToken).balanceOf(from);
require(controlledTokenBalance >= amount, "PrizePool/insuff-funds");
_accrueCredit(from, controlledToken, controlledTokenBalance, 0);
/*
The credit is used *last*. Always charge the fees up-front.
How to calculate:
Calculate their remaining exit fee. I.e. full exit fee of their balance less their credit.
If the exit fee on their withdrawal is greater than the remaining exit fee, then they'll have to pay the difference.
*/
// Determine available usable credit based on withdraw amount
uint256 remainingExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, controlledTokenBalance.sub(amount));
uint256 availableCredit;
if (_tokenCreditBalances[controlledToken][from].balance >= remainingExitFee) {
availableCredit = uint256(_tokenCreditBalances[controlledToken][from].balance).sub(remainingExitFee);
}
// Determine amount of credit to burn and amount of fees required
uint256 totalExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, amount);
creditBurned = (availableCredit > totalExitFee) ? totalExitFee : availableCredit;
earlyExitFee = totalExitFee.sub(creditBurned);
return (earlyExitFee, creditBurned);
}
/// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold
/// @param _liquidityCap The new liquidity cap for the prize pool
function setLiquidityCap(uint256 _liquidityCap) external override onlyOwner {
_setLiquidityCap(_liquidityCap);
}
function _setLiquidityCap(uint256 _liquidityCap) internal {
liquidityCap = _liquidityCap;
emit LiquidityCapSet(_liquidityCap);
}
/// @notice Allows the Governor to add Controlled Tokens to the Prize Pool
/// @param _controlledToken The address of the Controlled Token to add
function addControlledToken(ControlledTokenInterface _controlledToken) external override onlyOwner {
_addControlledToken(_controlledToken);
}
/// @notice Adds a new controlled token
/// @param _controlledToken The controlled token to add. Cannot be a duplicate.
function _addControlledToken(ControlledTokenInterface _controlledToken) internal {
require(_controlledToken.controller() == this, "PrizePool/token-ctrlr-mismatch");
_tokens.addAddress(address(_controlledToken));
emit ControlledTokenAdded(_controlledToken);
}
/// @notice Sets the prize strategy of the prize pool. Only callable by the owner.
/// @param _prizeStrategy The new prize strategy
function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external override onlyOwner {
_setPrizeStrategy(_prizeStrategy);
}
/// @notice Sets the prize strategy of the prize pool. Only callable by the owner.
/// @param _prizeStrategy The new prize strategy
function _setPrizeStrategy(TokenListenerInterface _prizeStrategy) internal {
require(address(_prizeStrategy) != address(0), "PrizePool/prizeStrategy-not-zero");
require(address(_prizeStrategy).supportsInterface(TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER), "PrizePool/prizeStrategy-invalid");
prizeStrategy = _prizeStrategy;
emit PrizeStrategySet(address(_prizeStrategy));
}
/// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship)
/// @return An array of controlled token addresses
function tokens() external override view returns (address[] memory) {
return _tokens.addressArray();
}
/// @dev Gets the current time as represented by the current block
/// @return The timestamp of the current block
function _currentTime() internal virtual view returns (uint256) {
return block.timestamp;
}
/// @notice The timestamp at which an account's timelocked balance will be made available to sweep
/// @param user The address of an account with timelocked assets
/// @return The timestamp at which the locked assets will be made available
function timelockBalanceAvailableAt(address user) external override view returns (uint256) {
return _unlockTimestamps[user];
}
/// @notice The balance of timelocked assets for an account
/// @param user The address of an account with timelocked assets
/// @return The amount of assets that have been timelocked
function timelockBalanceOf(address user) external override view returns (uint256) {
return _timelockBalances[user];
}
/// @notice The total of all controlled tokens and timelock.
/// @return The current total of all tokens and timelock.
function accountedBalance() external override view returns (uint256) {
return _tokenTotalSupply();
}
/// @notice The total of all controlled tokens and timelock.
/// @return The current total of all tokens and timelock.
function _tokenTotalSupply() internal view returns (uint256) {
uint256 total = timelockTotalSupply.add(reserveTotalSupply);
address currentToken = _tokens.start();
while (currentToken != address(0) && currentToken != _tokens.end()) {
total = total.add(IERC20Upgradeable(currentToken).totalSupply());
currentToken = _tokens.next(currentToken);
}
return total;
}
/// @dev Checks if the Prize Pool can receive liquidity based on the current cap
/// @param _amount The amount of liquidity to be added to the Prize Pool
/// @return True if the Prize Pool can receive the specified amount of liquidity
function _canAddLiquidity(uint256 _amount) internal view returns (bool) {
uint256 tokenTotalSupply = _tokenTotalSupply();
return (tokenTotalSupply.add(_amount) <= liquidityCap);
}
/// @dev Checks if a specific token is controlled by the Prize Pool
/// @param controlledToken The address of the token to check
/// @return True if the token is a controlled token, false otherwise
function _isControlled(address controlledToken) internal view returns (bool) {
return _tokens.contains(controlledToken);
}
/// @dev Function modifier to ensure usage of tokens controlled by the Prize Pool
/// @param controlledToken The address of the token to check
modifier onlyControlledToken(address controlledToken) {
require(_isControlled(controlledToken), "PrizePool/unknown-token");
_;
}
/// @dev Function modifier to ensure caller is the prize-strategy
modifier onlyPrizeStrategy() {
require(_msgSender() == address(prizeStrategy), "PrizePool/only-prizeStrategy");
_;
}
/// @dev Function modifier to ensure the deposit amount does not exceed the liquidity cap (if set)
modifier canAddLiquidity(uint256 _amount) {
require(_canAddLiquidity(_amount), "PrizePool/exceeds-liquidity-cap");
_;
}
modifier onlyReserve() {
ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup());
require(address(reserve) == msg.sender, "PrizePool/only-reserve");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// 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;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCastUpgradeable {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/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.6.2 <0.8.0;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165CheckerUpgradeable {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool, bool)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return (false, false);
return (success, abi.decode(result, (bool)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether 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 under version 3 of the License.
PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.0 <0.8.0;
import "./external/openzeppelin/OpenZeppelinSafeMath_V3_3_0.sol";
/**
* @author Brendan Asselstine
* @notice Provides basic fixed point math calculations.
*
* This library calculates integer fractions by scaling values by 1e18 then performing standard integer math.
*/
library FixedPoint {
using OpenZeppelinSafeMath_V3_3_0 for uint256;
// The scale to use for fixed point numbers. Same as Ether for simplicity.
uint256 internal constant SCALE = 1e18;
/**
* Calculates a Fixed18 mantissa given the numerator and denominator
*
* The mantissa = (numerator * 1e18) / denominator
*
* @param numerator The mantissa numerator
* @param denominator The mantissa denominator
* @return The mantissa of the fraction
*/
function calculateMantissa(uint256 numerator, uint256 denominator) internal pure returns (uint256) {
uint256 mantissa = numerator.mul(SCALE);
mantissa = mantissa.div(denominator);
return mantissa;
}
/**
* Multiplies a Fixed18 number by an integer.
*
* @param b The whole integer to multiply
* @param mantissa The Fixed18 number
* @return An integer that is the result of multiplying the params.
*/
function multiplyUintByMantissa(uint256 b, uint256 mantissa) internal pure returns (uint256) {
uint256 result = mantissa.mul(b);
result = result.div(SCALE);
return result;
}
/**
* Divides an integer by a fixed point 18 mantissa
*
* @param dividend The integer to divide
* @param mantissa The fixed point 18 number to serve as the divisor
* @return An integer that is the result of dividing an integer by a fixed point 18 mantissa
*/
function divideUintByMantissa(uint256 dividend, uint256 mantissa) internal pure returns (uint256) {
uint256 result = SCALE.mul(dividend);
result = result.div(mantissa);
return result;
}
}
// SPDX-License-Identifier: MIT
// NOTE: Copied from OpenZeppelin Contracts version 3.3.0
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 OpenZeppelinSafeMath_V3_3_0 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
/// @title Interface that allows a user to draw an address using an index
interface RegistryInterface {
function lookup() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
/// @title Interface that allows a user to draw an address using an index
interface ReserveInterface {
function reserveRateMantissa(address prizePool) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title Defines the functions used to interact with a yield source. The Prize Pool inherits this contract.
/// @notice Prize Pools subclasses need to implement this interface so that yield can be generated.
abstract contract YieldSource {
/// @notice Determines whether the passed token can be transferred out as an external award.
/// @dev Different yield sources will hold the deposits as another kind of token: such a Compound's cToken. The
/// prize strategy should not be allowed to move those tokens.
/// @param _externalToken The address of the token to check
/// @return True if the token may be awarded, false otherwise
function _canAwardExternal(address _externalToken) internal virtual view returns (bool);
/// @notice Returns the ERC20 asset token used for deposits.
/// @return The ERC20 asset token
function _token() internal virtual view returns (IERC20Upgradeable);
/// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.
/// @return The underlying balance of asset tokens
function _balance() internal virtual returns (uint256);
/// @notice Supplies asset tokens to the yield source.
/// @param mintAmount The amount of asset tokens to be supplied
function _supply(uint256 mintAmount) internal virtual;
/// @notice Redeems asset tokens from the yield source.
/// @param redeemAmount The amount of yield-bearing tokens to be redeemed
/// @return The actual amount of tokens that were redeemed.
function _redeem(uint256 redeemAmount) internal virtual returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
/// @title An interface that allows a contract to listen to token mint, transfer and burn events.
interface TokenListenerInterface is IERC165Upgradeable {
/// @notice Called when tokens are minted.
/// @param to The address of the receiver of the minted tokens.
/// @param amount The amount of tokens being minted
/// @param controlledToken The address of the token that is being minted
/// @param referrer The address that referred the minting.
function beforeTokenMint(address to, uint256 amount, address controlledToken, address referrer) external;
/// @notice Called when tokens are transferred or burned.
/// @param from The address of the sender of the token transfer
/// @param to The address of the receiver of the token transfer. Will be the zero address if burning.
/// @param amount The amount of tokens transferred
/// @param controlledToken The address of the token that was transferred
function beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external;
}
pragma solidity ^0.6.12;
library TokenListenerLibrary {
/*
* bytes4(keccak256('beforeTokenMint(address,uint256,address,address)')) == 0x4d7f3db0
* bytes4(keccak256('beforeTokenTransfer(address,address,uint256,address)')) == 0xb2210957
*
* => 0x4d7f3db0 ^ 0xb2210957 == 0xff5e34e7
*/
bytes4 public constant ERC165_INTERFACE_ID_TOKEN_LISTENER = 0xff5e34e7;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "./TokenControllerInterface.sol";
import "./ControlledTokenInterface.sol";
/// @title Controlled ERC20 Token
/// @notice ERC20 Tokens with a controller for minting & burning
contract ControlledToken is ERC20Upgradeable, ControlledTokenInterface {
/// @notice Interface to the contract responsible for controlling mint/burn
TokenControllerInterface public override controller;
/// @notice Initializes the Controlled Token with Token Details and the Controller
/// @param _name The name of the Token
/// @param _symbol The symbol for the Token
/// @param _decimals The number of decimals for the Token
/// @param _controller Address of the Controller contract for minting & burning
function initialize(
string memory _name,
string memory _symbol,
uint8 _decimals,
TokenControllerInterface _controller
)
public
virtual
initializer
{
__ERC20_init(_name, _symbol);
controller = _controller;
_setupDecimals(_decimals);
}
/// @notice Allows the controller to mint tokens for a user account
/// @dev May be overridden to provide more granular control over minting
/// @param _user Address of the receiver of the minted tokens
/// @param _amount Amount of tokens to mint
function controllerMint(address _user, uint256 _amount) external virtual override onlyController {
_mint(_user, _amount);
}
/// @notice Allows the controller to burn tokens from a user account
/// @dev May be overridden to provide more granular control over burning
/// @param _user Address of the holder account to burn tokens from
/// @param _amount Amount of tokens to burn
function controllerBurn(address _user, uint256 _amount) external virtual override onlyController {
_burn(_user, _amount);
}
/// @notice Allows an operator via the controller to burn tokens on behalf of a user account
/// @dev May be overridden to provide more granular control over operator-burning
/// @param _operator Address of the operator performing the burn action via the controller contract
/// @param _user Address of the holder account to burn tokens from
/// @param _amount Amount of tokens to burn
function controllerBurnFrom(address _operator, address _user, uint256 _amount) external virtual override onlyController {
if (_operator != _user) {
uint256 decreasedAllowance = allowance(_user, _operator).sub(_amount, "ControlledToken/exceeds-allowance");
_approve(_user, _operator, decreasedAllowance);
}
_burn(_user, _amount);
}
/// @dev Function modifier to ensure that the caller is the controller contract
modifier onlyController {
require(_msgSender() == address(controller), "ControlledToken/only-controller");
_;
}
/// @dev Controller hook to provide notifications & rule validations on token transfers to the controller.
/// This includes minting and burning.
/// May be overridden to provide more granular control over operator-burning
/// @param from Address of the account sending the tokens (address(0x0) on minting)
/// @param to Address of the account receiving the tokens (address(0x0) on burning)
/// @param amount Amount of tokens being transferred
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
controller.beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
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_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
/// @title Controlled ERC20 Token Interface
/// @notice Required interface for Controlled ERC20 Tokens linked to a Prize Pool
/// @dev Defines the spec required to be implemented by a Controlled ERC20 Token
interface TokenControllerInterface {
/// @dev Controller hook to provide notifications & rule validations on token transfers to the controller.
/// This includes minting and burning.
/// @param from Address of the account sending the tokens (address(0x0) on minting)
/// @param to Address of the account receiving the tokens (address(0x0) on burning)
/// @param amount Amount of tokens being transferred
function beforeTokenTransfer(address from, address to, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./TokenControllerInterface.sol";
/// @title Controlled ERC20 Token
/// @notice ERC20 Tokens with a controller for minting & burning
interface ControlledTokenInterface is IERC20Upgradeable {
/// @notice Interface to the contract responsible for controlling mint/burn
function controller() external view returns (TokenControllerInterface);
/// @notice Allows the controller to mint tokens for a user account
/// @dev May be overridden to provide more granular control over minting
/// @param _user Address of the receiver of the minted tokens
/// @param _amount Amount of tokens to mint
function controllerMint(address _user, uint256 _amount) external;
/// @notice Allows the controller to burn tokens from a user account
/// @dev May be overridden to provide more granular control over burning
/// @param _user Address of the holder account to burn tokens from
/// @param _amount Amount of tokens to burn
function controllerBurn(address _user, uint256 _amount) external;
/// @notice Allows an operator via the controller to burn tokens on behalf of a user account
/// @dev May be overridden to provide more granular control over operator-burning
/// @param _operator Address of the operator performing the burn action via the controller contract
/// @param _user Address of the holder account to burn tokens from
/// @param _amount Amount of tokens to burn
function controllerBurnFrom(address _operator, address _user, uint256 _amount) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
/// @notice An efficient implementation of a singly linked list of addresses
/// @dev A mapping(address => address) tracks the 'next' pointer. A special address called the SENTINEL is used to denote the beginning and end of the list.
library MappedSinglyLinkedList {
/// @notice The special value address used to denote the end of the list
address public constant SENTINEL = address(0x1);
/// @notice The data structure to use for the list.
struct Mapping {
uint256 count;
mapping(address => address) addressMap;
}
/// @notice Initializes the list.
/// @dev It is important that this is called so that the SENTINEL is correctly setup.
function initialize(Mapping storage self) internal {
require(self.count == 0, "Already init");
self.addressMap[SENTINEL] = SENTINEL;
}
function start(Mapping storage self) internal view returns (address) {
return self.addressMap[SENTINEL];
}
function next(Mapping storage self, address current) internal view returns (address) {
return self.addressMap[current];
}
function end(Mapping storage) internal pure returns (address) {
return SENTINEL;
}
function addAddresses(Mapping storage self, address[] memory addresses) internal {
for (uint256 i = 0; i < addresses.length; i++) {
addAddress(self, addresses[i]);
}
}
/// @notice Adds an address to the front of the list.
/// @param self The Mapping struct that this function is attached to
/// @param newAddress The address to shift to the front of the list
function addAddress(Mapping storage self, address newAddress) internal {
require(newAddress != SENTINEL && newAddress != address(0), "Invalid address");
require(self.addressMap[newAddress] == address(0), "Already added");
self.addressMap[newAddress] = self.addressMap[SENTINEL];
self.addressMap[SENTINEL] = newAddress;
self.count = self.count + 1;
}
/// @notice Removes an address from the list
/// @param self The Mapping struct that this function is attached to
/// @param prevAddress The address that precedes the address to be removed. This may be the SENTINEL if at the start.
/// @param addr The address to remove from the list.
function removeAddress(Mapping storage self, address prevAddress, address addr) internal {
require(addr != SENTINEL && addr != address(0), "Invalid address");
require(self.addressMap[prevAddress] == addr, "Invalid prevAddress");
self.addressMap[prevAddress] = self.addressMap[addr];
delete self.addressMap[addr];
self.count = self.count - 1;
}
/// @notice Determines whether the list contains the given address
/// @param self The Mapping struct that this function is attached to
/// @param addr The address to check
/// @return True if the address is contained, false otherwise.
function contains(Mapping storage self, address addr) internal view returns (bool) {
return addr != SENTINEL && addr != address(0) && self.addressMap[addr] != address(0);
}
/// @notice Returns an address array of all the addresses in this list
/// @dev Contains a for loop, so complexity is O(n) wrt the list size
/// @param self The Mapping struct that this function is attached to
/// @return An array of all the addresses
function addressArray(Mapping storage self) internal view returns (address[] memory) {
address[] memory array = new address[](self.count);
uint256 count;
address currentAddress = self.addressMap[SENTINEL];
while (currentAddress != address(0) && currentAddress != SENTINEL) {
array[count] = currentAddress;
currentAddress = self.addressMap[currentAddress];
count++;
}
return array;
}
/// @notice Removes every address from the list
/// @param self The Mapping struct that this function is attached to
function clearAll(Mapping storage self) internal {
address currentAddress = self.addressMap[SENTINEL];
while (currentAddress != address(0) && currentAddress != SENTINEL) {
address nextAddress = self.addressMap[currentAddress];
delete self.addressMap[currentAddress];
currentAddress = nextAddress;
}
self.addressMap[SENTINEL] = SENTINEL;
self.count = 0;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "../token/TokenListenerInterface.sol";
import "../token/ControlledTokenInterface.sol";
/// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool.
/// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract.
/// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens
interface PrizePoolInterface {
/// @notice Deposit assets into the Prize Pool in exchange for tokens
/// @param to The address receiving the newly minted tokens
/// @param amount The amount of assets to deposit
/// @param controlledToken The address of the type of token the user is minting
/// @param referrer The referrer of the deposit
function depositTo(
address to,
uint256 amount,
address controlledToken,
address referrer
)
external;
/// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit.
/// @param from The address to redeem tokens from.
/// @param amount The amount of tokens to redeem for assets.
/// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship)
/// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn.
/// @return The actual exit fee paid
function withdrawInstantlyFrom(
address from,
uint256 amount,
address controlledToken,
uint256 maximumExitFee
) external returns (uint256);
/// @notice Withdraw assets from the Prize Pool by placing them into the timelock.
/// The timelock is used to ensure that the tickets have contributed their fair share of the prize.
/// @dev Note that if the user has previously timelocked funds then this contract will try to sweep them.
/// If the existing timelocked funds are still locked, then the incoming
/// balance is added to their existing balance and the new timelock unlock timestamp will overwrite the old one.
/// @param from The address to withdraw from
/// @param amount The amount to withdraw
/// @param controlledToken The type of token being withdrawn
/// @return The timestamp from which the funds can be swept
function withdrawWithTimelockFrom(
address from,
uint256 amount,
address controlledToken
) external returns (uint256);
function withdrawReserve(address to) external returns (uint256);
/// @notice Returns the balance that is available to award.
/// @dev captureAwardBalance() should be called first
/// @return The total amount of assets to be awarded for the current prize
function awardBalance() external view returns (uint256);
/// @notice Captures any available interest as award balance.
/// @dev This function also captures the reserve fees.
/// @return The total amount of assets to be awarded for the current prize
function captureAwardBalance() external returns (uint256);
/// @notice Called by the prize strategy to award prizes.
/// @dev The amount awarded must be less than the awardBalance()
/// @param to The address of the winner that receives the award
/// @param amount The amount of assets to be awarded
/// @param controlledToken The address of the asset token being awarded
function award(
address to,
uint256 amount,
address controlledToken
)
external;
/// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens
/// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything.
/// @param to The address of the winner that receives the award
/// @param amount The amount of external assets to be awarded
/// @param externalToken The address of the external asset token being awarded
function transferExternalERC20(
address to,
address externalToken,
uint256 amount
)
external;
/// @notice Called by the Prize-Strategy to award external ERC20 prizes
/// @dev Used to award any arbitrary tokens held by the Prize Pool
/// @param to The address of the winner that receives the award
/// @param amount The amount of external assets to be awarded
/// @param externalToken The address of the external asset token being awarded
function awardExternalERC20(
address to,
address externalToken,
uint256 amount
)
external;
/// @notice Called by the prize strategy to award external ERC721 prizes
/// @dev Used to award any arbitrary NFTs held by the Prize Pool
/// @param to The address of the winner that receives the award
/// @param externalToken The address of the external NFT token being awarded
/// @param tokenIds An array of NFT Token IDs to be transferred
function awardExternalERC721(
address to,
address externalToken,
uint256[] calldata tokenIds
)
external;
/// @notice Sweep all timelocked balances and transfer unlocked assets to owner accounts
/// @param users An array of account addresses to sweep balances for
/// @return The total amount of assets swept from the Prize Pool
function sweepTimelockBalances(
address[] calldata users
)
external
returns (uint256);
/// @notice Calculates a timelocked withdrawal duration and credit consumption.
/// @param from The user who is withdrawing
/// @param amount The amount the user is withdrawing
/// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship)
/// @return durationSeconds The duration of the timelock in seconds
function calculateTimelockDuration(
address from,
address controlledToken,
uint256 amount
)
external
returns (
uint256 durationSeconds,
uint256 burnedCredit
);
/// @notice Calculates the early exit fee for the given amount
/// @param from The user who is withdrawing
/// @param controlledToken The type of collateral being withdrawn
/// @param amount The amount of collateral to be withdrawn
/// @return exitFee The exit fee
/// @return burnedCredit The user's credit that was burned
function calculateEarlyExitFee(
address from,
address controlledToken,
uint256 amount
)
external
returns (
uint256 exitFee,
uint256 burnedCredit
);
/// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit.
/// @param _principal The principal amount on which interest is accruing
/// @param _interest The amount of interest that must accrue
/// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds.
function estimateCreditAccrualTime(
address _controlledToken,
uint256 _principal,
uint256 _interest
)
external
view
returns (uint256 durationSeconds);
/// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit.
/// @param user The user whose credit balance should be returned
/// @return The balance of the users credit
function balanceOfCredit(address user, address controlledToken) external returns (uint256);
/// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether).
/// @param _controlledToken The controlled token for whom to set the credit plan
/// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether).
/// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether).
function setCreditPlanOf(
address _controlledToken,
uint128 _creditRateMantissa,
uint128 _creditLimitMantissa
)
external;
/// @notice Returns the credit rate of a controlled token
/// @param controlledToken The controlled token to retrieve the credit rates for
/// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee.
/// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second.
function creditPlanOf(
address controlledToken
)
external
view
returns (
uint128 creditLimitMantissa,
uint128 creditRateMantissa
);
/// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold
/// @param _liquidityCap The new liquidity cap for the prize pool
function setLiquidityCap(uint256 _liquidityCap) external;
/// @notice Allows the Governor to add Controlled Tokens to the Prize Pool
/// @param _controlledToken The address of the Controlled Token to add
function addControlledToken(ControlledTokenInterface _controlledToken) external;
/// @notice Sets the prize strategy of the prize pool. Only callable by the owner.
/// @param _prizeStrategy The new prize strategy. Must implement TokenListenerInterface
function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external;
/// @dev Returns the address of the underlying ERC20 asset
/// @return The address of the asset
function token() external view returns (address);
/// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship)
/// @return An array of controlled token addresses
function tokens() external view returns (address[] memory);
/// @notice The timestamp at which an account's timelocked balance will be made available to sweep
/// @param user The address of an account with timelocked assets
/// @return The timestamp at which the locked assets will be made available
function timelockBalanceAvailableAt(address user) external view returns (uint256);
/// @notice The balance of timelocked assets for an account
/// @param user The address of an account with timelocked assets
/// @return The amount of assets that have been timelocked
function timelockBalanceOf(address user) external view returns (uint256);
/// @notice The total of all controlled tokens and timelock.
/// @return The current total of all tokens and timelock.
function accountedBalance() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@pooltogether/pooltogether-rng-contracts/contracts/RNGInterface.sol";
import "../token/TokenListener.sol";
import "@pooltogether/fixed-point/contracts/FixedPoint.sol";
import "../token/TokenControllerInterface.sol";
import "../token/ControlledToken.sol";
import "../token/TicketInterface.sol";
import "../prize-pool/PrizePool.sol";
import "../Constants.sol";
import "./PeriodicPrizeStrategyListenerInterface.sol";
import "./PeriodicPrizeStrategyListenerLibrary.sol";
/* solium-disable security/no-block-members */
abstract contract PeriodicPrizeStrategy is Initializable,
OwnableUpgradeable,
TokenListener {
using SafeMathUpgradeable for uint256;
using SafeCastUpgradeable for uint256;
using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping;
using AddressUpgradeable for address;
using ERC165CheckerUpgradeable for address;
uint256 internal constant ETHEREUM_BLOCK_TIME_ESTIMATE_MANTISSA = 13.4 ether;
event PrizePoolOpened(
address indexed operator,
uint256 indexed prizePeriodStartedAt
);
event RngRequestFailed();
event PrizePoolAwardStarted(
address indexed operator,
address indexed prizePool,
uint32 indexed rngRequestId,
uint32 rngLockBlock
);
event PrizePoolAwardCancelled(
address indexed operator,
address indexed prizePool,
uint32 indexed rngRequestId,
uint32 rngLockBlock
);
event PrizePoolAwarded(
address indexed operator,
uint256 randomNumber
);
event RngServiceUpdated(
RNGInterface indexed rngService
);
event TokenListenerUpdated(
TokenListenerInterface indexed tokenListener
);
event RngRequestTimeoutSet(
uint32 rngRequestTimeout
);
event PeriodicPrizeStrategyListenerSet(
PeriodicPrizeStrategyListenerInterface indexed periodicPrizeStrategyListener
);
event ExternalErc721AwardAdded(
IERC721Upgradeable indexed externalErc721,
uint256[] tokenIds
);
event ExternalErc20AwardAdded(
IERC20Upgradeable indexed externalErc20
);
event ExternalErc721AwardRemoved(
IERC721Upgradeable indexed externalErc721Award
);
event ExternalErc20AwardRemoved(
IERC20Upgradeable indexed externalErc20Award
);
event Initialized(
uint256 prizePeriodStart,
uint256 prizePeriodSeconds,
PrizePool indexed prizePool,
TicketInterface ticket,
IERC20Upgradeable sponsorship,
RNGInterface rng,
IERC20Upgradeable[] externalErc20Awards
);
struct RngRequest {
uint32 id;
uint32 lockBlock;
uint32 requestedAt;
}
// Comptroller
TokenListenerInterface public tokenListener;
// Contract Interfaces
PrizePool public prizePool;
TicketInterface public ticket;
IERC20Upgradeable public sponsorship;
RNGInterface public rng;
// Current RNG Request
RngRequest internal rngRequest;
/// @notice RNG Request Timeout. In fact, this is really a "complete award" timeout.
/// If the rng completes the award can still be cancelled.
uint32 public rngRequestTimeout;
// Prize period
uint256 public prizePeriodSeconds;
uint256 public prizePeriodStartedAt;
// External tokens awarded as part of prize
MappedSinglyLinkedList.Mapping internal externalErc20s;
MappedSinglyLinkedList.Mapping internal externalErc721s;
// External NFT token IDs to be awarded
// NFT Address => TokenIds
mapping (IERC721Upgradeable => uint256[]) internal externalErc721TokenIds;
/// @notice A listener that receives callbacks before certain events
PeriodicPrizeStrategyListenerInterface public periodicPrizeStrategyListener;
/// @notice Initializes a new strategy
/// @param _prizePeriodStart The starting timestamp of the prize period.
/// @param _prizePeriodSeconds The duration of the prize period in seconds
/// @param _prizePool The prize pool to award
/// @param _ticket The ticket to use to draw winners
/// @param _sponsorship The sponsorship token
/// @param _rng The RNG service to use
function initialize (
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;
__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();
// 30 min timeout
_setRngRequestTimeout(1800);
emit Initialized(
_prizePeriodStart,
_prizePeriodSeconds,
_prizePool,
_ticket,
_sponsorship,
_rng,
externalErc20Awards
);
emit PrizePoolOpened(_msgSender(), prizePeriodStartedAt);
}
function _distribute(uint256 randomNumber) internal virtual;
/// @notice Calculates and returns the currently accrued prize
/// @return The current prize size
function currentPrize() public view returns (uint256) {
return prizePool.awardBalance();
}
/// @notice Allows the owner to set the token listener
/// @param _tokenListener A contract that implements the token listener interface.
function setTokenListener(TokenListenerInterface _tokenListener) external onlyOwner requireAwardNotInProgress {
require(address(0) == address(_tokenListener) || address(_tokenListener).supportsInterface(TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER), "PeriodicPrizeStrategy/token-listener-invalid");
tokenListener = _tokenListener;
emit TokenListenerUpdated(tokenListener);
}
/// @notice Estimates the remaining blocks until the prize given a number of seconds per block
/// @param secondsPerBlockMantissa The number of seconds per block to use for the calculation. Should be a fixed point 18 number like Ether.
/// @return The estimated number of blocks remaining until the prize can be awarded.
function estimateRemainingBlocksToPrize(uint256 secondsPerBlockMantissa) public view returns (uint256) {
return FixedPoint.divideUintByMantissa(
_prizePeriodRemainingSeconds(),
secondsPerBlockMantissa
);
}
/// @notice Returns the number of seconds remaining until the prize can be awarded.
/// @return The number of seconds remaining until the prize can be awarded.
function prizePeriodRemainingSeconds() external view returns (uint256) {
return _prizePeriodRemainingSeconds();
}
/// @notice Returns the number of seconds remaining until the prize can be awarded.
/// @return The number of seconds remaining until the prize can be awarded.
function _prizePeriodRemainingSeconds() internal view returns (uint256) {
uint256 endAt = _prizePeriodEndAt();
uint256 time = _currentTime();
if (time > endAt) {
return 0;
}
return endAt.sub(time);
}
/// @notice Returns whether the prize period is over
/// @return True if the prize period is over, false otherwise
function isPrizePeriodOver() external view returns (bool) {
return _isPrizePeriodOver();
}
/// @notice Returns whether the prize period is over
/// @return True if the prize period is over, false otherwise
function _isPrizePeriodOver() internal view returns (bool) {
return _currentTime() >= _prizePeriodEndAt();
}
/// @notice Awards collateral as tickets to a user
/// @param user The user to whom the tickets are minted
/// @param amount The amount of interest to mint as tickets.
function _awardTickets(address user, uint256 amount) internal {
prizePool.award(user, amount, address(ticket));
}
/// @notice Awards all external tokens with non-zero balances to the given user. The external tokens must be held by the PrizePool contract.
/// @param winner The user to transfer the tokens to
function _awardAllExternalTokens(address winner) internal {
_awardExternalErc20s(winner);
_awardExternalErc721s(winner);
}
/// @notice Awards all external ERC20 tokens with non-zero balances to the given user.
/// The external tokens must be held by the PrizePool contract.
/// @param winner The user to transfer the tokens to
function _awardExternalErc20s(address winner) internal {
address currentToken = externalErc20s.start();
while (currentToken != address(0) && currentToken != externalErc20s.end()) {
uint256 balance = IERC20Upgradeable(currentToken).balanceOf(address(prizePool));
if (balance > 0) {
prizePool.awardExternalERC20(winner, currentToken, balance);
}
currentToken = externalErc20s.next(currentToken);
}
}
/// @notice Awards all external ERC721 tokens to the given user.
/// The external tokens must be held by the PrizePool contract.
/// @dev The list of ERC721s is reset after every award
/// @param winner The user to transfer the tokens to
function _awardExternalErc721s(address winner) internal {
address currentToken = externalErc721s.start();
while (currentToken != address(0) && currentToken != externalErc721s.end()) {
uint256 balance = IERC721Upgradeable(currentToken).balanceOf(address(prizePool));
if (balance > 0) {
prizePool.awardExternalERC721(winner, currentToken, externalErc721TokenIds[IERC721Upgradeable(currentToken)]);
_removeExternalErc721AwardTokens(IERC721Upgradeable(currentToken));
}
currentToken = externalErc721s.next(currentToken);
}
externalErc721s.clearAll();
}
/// @notice Returns the timestamp at which the prize period ends
/// @return The timestamp at which the prize period ends.
function prizePeriodEndAt() external view returns (uint256) {
// current prize started at is non-inclusive, so add one
return _prizePeriodEndAt();
}
/// @notice Returns the timestamp at which the prize period ends
/// @return The timestamp at which the prize period ends.
function _prizePeriodEndAt() internal view returns (uint256) {
// current prize started at is non-inclusive, so add one
return prizePeriodStartedAt.add(prizePeriodSeconds);
}
/// @notice Called by the PrizePool for transfers of controlled tokens
/// @dev Note that this is only for *transfers*, not mints or burns
/// @param controlledToken The type of collateral that is being sent
function beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external override onlyPrizePool {
require(from != to, "PeriodicPrizeStrategy/transfer-to-self");
if (controlledToken == address(ticket)) {
_requireAwardNotInProgress();
}
if (address(tokenListener) != address(0)) {
tokenListener.beforeTokenTransfer(from, to, amount, controlledToken);
}
}
/// @notice Called by the PrizePool when minting controlled tokens
/// @param controlledToken The type of collateral that is being minted
function beforeTokenMint(
address to,
uint256 amount,
address controlledToken,
address referrer
)
external
override
onlyPrizePool
{
if (controlledToken == address(ticket)) {
_requireAwardNotInProgress();
}
if (address(tokenListener) != address(0)) {
tokenListener.beforeTokenMint(to, amount, controlledToken, referrer);
}
}
/// @notice returns the current time. Used for testing.
/// @return The current time (block.timestamp)
function _currentTime() internal virtual view returns (uint256) {
return block.timestamp;
}
/// @notice returns the current time. Used for testing.
/// @return The current time (block.timestamp)
function _currentBlock() internal virtual view returns (uint256) {
return block.number;
}
/// @notice Starts the award process by starting random number request. The prize period must have ended.
/// @dev The RNG-Request-Fee is expected to be held within this contract before calling this function
function startAward() external requireCanStartAward {
(address feeToken, uint256 requestFee) = rng.getRequestFee();
if (feeToken != address(0) && requestFee > 0) {
IERC20Upgradeable(feeToken).approve(address(rng), requestFee);
}
(uint32 requestId, uint32 lockBlock) = rng.requestRandomNumber();
rngRequest.id = requestId;
rngRequest.lockBlock = lockBlock;
rngRequest.requestedAt = _currentTime().toUint32();
emit PrizePoolAwardStarted(_msgSender(), address(prizePool), requestId, lockBlock);
}
/// @notice Can be called by anyone to unlock the tickets if the RNG has timed out.
function cancelAward() public {
require(isRngTimedOut(), "PeriodicPrizeStrategy/rng-not-timedout");
uint32 requestId = rngRequest.id;
uint32 lockBlock = rngRequest.lockBlock;
delete rngRequest;
emit RngRequestFailed();
emit PrizePoolAwardCancelled(msg.sender, address(prizePool), requestId, lockBlock);
}
/// @notice Completes the award process and awards the winners. The random number must have been requested and is now available.
function completeAward() external requireCanCompleteAward {
uint256 randomNumber = rng.randomNumber(rngRequest.id);
delete rngRequest;
_distribute(randomNumber);
if (address(periodicPrizeStrategyListener) != address(0)) {
periodicPrizeStrategyListener.afterPrizePoolAwarded(randomNumber, prizePeriodStartedAt);
}
// to avoid clock drift, we should calculate the start time based on the previous period start time.
prizePeriodStartedAt = _calculateNextPrizePeriodStartTime(_currentTime());
emit PrizePoolAwarded(_msgSender(), randomNumber);
emit PrizePoolOpened(_msgSender(), prizePeriodStartedAt);
}
/// @notice Allows the owner to set a listener for prize strategy callbacks.
/// @param _periodicPrizeStrategyListener The address of the listener contract
function setPeriodicPrizeStrategyListener(PeriodicPrizeStrategyListenerInterface _periodicPrizeStrategyListener) external onlyOwner requireAwardNotInProgress {
require(
address(0) == address(_periodicPrizeStrategyListener) || address(_periodicPrizeStrategyListener).supportsInterface(PeriodicPrizeStrategyListenerLibrary.ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER),
"PeriodicPrizeStrategy/prizeStrategyListener-invalid"
);
periodicPrizeStrategyListener = _periodicPrizeStrategyListener;
emit PeriodicPrizeStrategyListenerSet(_periodicPrizeStrategyListener);
}
function _calculateNextPrizePeriodStartTime(uint256 currentTime) internal view returns (uint256) {
uint256 elapsedPeriods = currentTime.sub(prizePeriodStartedAt).div(prizePeriodSeconds);
return prizePeriodStartedAt.add(elapsedPeriods.mul(prizePeriodSeconds));
}
/// @notice Calculates when the next prize period will start
/// @param currentTime The timestamp to use as the current time
/// @return The timestamp at which the next prize period would start
function calculateNextPrizePeriodStartTime(uint256 currentTime) external view returns (uint256) {
return _calculateNextPrizePeriodStartTime(currentTime);
}
/// @notice Returns whether an award process can be started
/// @return True if an award can be started, false otherwise.
function canStartAward() external view returns (bool) {
return _isPrizePeriodOver() && !isRngRequested();
}
/// @notice Returns whether an award process can be completed
/// @return True if an award can be completed, false otherwise.
function canCompleteAward() external view returns (bool) {
return isRngRequested() && isRngCompleted();
}
/// @notice Returns whether a random number has been requested
/// @return True if a random number has been requested, false otherwise.
function isRngRequested() public view returns (bool) {
return rngRequest.id != 0;
}
/// @notice Returns whether the random number request has completed.
/// @return True if a random number request has completed, false otherwise.
function isRngCompleted() public view returns (bool) {
return rng.isRequestComplete(rngRequest.id);
}
/// @notice Returns the block number that the current RNG request has been locked to
/// @return The block number that the RNG request is locked to
function getLastRngLockBlock() external view returns (uint32) {
return rngRequest.lockBlock;
}
/// @notice Returns the current RNG Request ID
/// @return The current Request ID
function getLastRngRequestId() external view returns (uint32) {
return rngRequest.id;
}
/// @notice Sets the RNG service that the Prize Strategy is connected to
/// @param rngService The address of the new RNG service interface
function setRngService(RNGInterface rngService) external onlyOwner requireAwardNotInProgress {
require(!isRngRequested(), "PeriodicPrizeStrategy/rng-in-flight");
rng = rngService;
emit RngServiceUpdated(rngService);
}
function setRngRequestTimeout(uint32 _rngRequestTimeout) external onlyOwner requireAwardNotInProgress {
_setRngRequestTimeout(_rngRequestTimeout);
}
function _setRngRequestTimeout(uint32 _rngRequestTimeout) internal {
require(_rngRequestTimeout > 60, "PeriodicPrizeStrategy/rng-timeout-gt-60-secs");
rngRequestTimeout = _rngRequestTimeout;
emit RngRequestTimeoutSet(rngRequestTimeout);
}
/// @notice Gets the current list of External ERC20 tokens that will be awarded with the current prize
/// @return An array of External ERC20 token addresses
function getExternalErc20Awards() external view returns (address[] memory) {
return externalErc20s.addressArray();
}
/// @notice Adds an external ERC20 token type as an additional prize that can be awarded
/// @dev Only the Prize-Strategy owner/creator can assign external tokens,
/// and they must be approved by the Prize-Pool
/// @param _externalErc20 The address of an ERC20 token to be awarded
function addExternalErc20Award(IERC20Upgradeable _externalErc20) external onlyOwnerOrListener requireAwardNotInProgress {
_addExternalErc20Award(_externalErc20);
}
function _addExternalErc20Award(IERC20Upgradeable _externalErc20) internal {
require(address(_externalErc20).isContract(), "PeriodicPrizeStrategy/erc20-null");
require(prizePool.canAwardExternal(address(_externalErc20)), "PeriodicPrizeStrategy/cannot-award-external");
(bool succeeded, bytes memory returnValue) = address(_externalErc20).staticcall(abi.encodeWithSignature("totalSupply()"));
require(succeeded, "PeriodicPrizeStrategy/erc20-invalid");
externalErc20s.addAddress(address(_externalErc20));
emit ExternalErc20AwardAdded(_externalErc20);
}
function addExternalErc20Awards(IERC20Upgradeable[] calldata _externalErc20s) external onlyOwnerOrListener requireAwardNotInProgress {
for (uint256 i = 0; i < _externalErc20s.length; i++) {
_addExternalErc20Award(_externalErc20s[i]);
}
}
/// @notice Removes an external ERC20 token type as an additional prize that can be awarded
/// @dev Only the Prize-Strategy owner/creator can remove external tokens
/// @param _externalErc20 The address of an ERC20 token to be removed
/// @param _prevExternalErc20 The address of the previous ERC20 token in the `externalErc20s` list.
/// If the ERC20 is the first address, then the previous address is the SENTINEL address: 0x0000000000000000000000000000000000000001
function removeExternalErc20Award(IERC20Upgradeable _externalErc20, IERC20Upgradeable _prevExternalErc20) external onlyOwner requireAwardNotInProgress {
externalErc20s.removeAddress(address(_prevExternalErc20), address(_externalErc20));
emit ExternalErc20AwardRemoved(_externalErc20);
}
/// @notice Gets the current list of External ERC721 tokens that will be awarded with the current prize
/// @return An array of External ERC721 token addresses
function getExternalErc721Awards() external view returns (address[] memory) {
return externalErc721s.addressArray();
}
/// @notice Gets the current list of External ERC721 tokens that will be awarded with the current prize
/// @return An array of External ERC721 token addresses
function getExternalErc721AwardTokenIds(IERC721Upgradeable _externalErc721) external view returns (uint256[] memory) {
return externalErc721TokenIds[_externalErc721];
}
/// @notice Adds an external ERC721 token as an additional prize that can be awarded
/// @dev Only the Prize-Strategy owner/creator can assign external tokens,
/// and they must be approved by the Prize-Pool
/// NOTE: The NFT must already be owned by the Prize-Pool
/// @param _externalErc721 The address of an ERC721 token to be awarded
/// @param _tokenIds An array of token IDs of the ERC721 to be awarded
function addExternalErc721Award(IERC721Upgradeable _externalErc721, uint256[] calldata _tokenIds) external onlyOwnerOrListener requireAwardNotInProgress {
require(prizePool.canAwardExternal(address(_externalErc721)), "PeriodicPrizeStrategy/cannot-award-external");
require(address(_externalErc721).supportsInterface(Constants.ERC165_INTERFACE_ID_ERC721), "PeriodicPrizeStrategy/erc721-invalid");
if (!externalErc721s.contains(address(_externalErc721))) {
externalErc721s.addAddress(address(_externalErc721));
}
for (uint256 i = 0; i < _tokenIds.length; i++) {
_addExternalErc721Award(_externalErc721, _tokenIds[i]);
}
emit ExternalErc721AwardAdded(_externalErc721, _tokenIds);
}
function _addExternalErc721Award(IERC721Upgradeable _externalErc721, uint256 _tokenId) internal {
require(IERC721Upgradeable(_externalErc721).ownerOf(_tokenId) == address(prizePool), "PeriodicPrizeStrategy/unavailable-token");
for (uint256 i = 0; i < externalErc721TokenIds[_externalErc721].length; i++) {
if (externalErc721TokenIds[_externalErc721][i] == _tokenId) {
revert("PeriodicPrizeStrategy/erc721-duplicate");
}
}
externalErc721TokenIds[_externalErc721].push(_tokenId);
}
/// @notice Removes an external ERC721 token as an additional prize that can be awarded
/// @dev Only the Prize-Strategy owner/creator can remove external tokens
/// @param _externalErc721 The address of an ERC721 token to be removed
/// @param _prevExternalErc721 The address of the previous ERC721 token in the list.
/// If no previous, then pass the SENTINEL address: 0x0000000000000000000000000000000000000001
function removeExternalErc721Award(
IERC721Upgradeable _externalErc721,
IERC721Upgradeable _prevExternalErc721
)
external
onlyOwner
requireAwardNotInProgress
{
externalErc721s.removeAddress(address(_prevExternalErc721), address(_externalErc721));
_removeExternalErc721AwardTokens(_externalErc721);
}
function _removeExternalErc721AwardTokens(
IERC721Upgradeable _externalErc721
)
internal
{
delete externalErc721TokenIds[_externalErc721];
emit ExternalErc721AwardRemoved(_externalErc721);
}
/// @notice Allows the owner to transfer out external ERC20 tokens
/// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything.
/// @param to The address that receives the tokens
/// @param externalToken The address of the external asset token being transferred
/// @param amount The amount of external assets to be transferred
function transferExternalERC20(
address to,
address externalToken,
uint256 amount
)
external
onlyOwner
requireAwardNotInProgress
{
prizePool.transferExternalERC20(to, externalToken, amount);
}
function _requireAwardNotInProgress() internal view {
uint256 currentBlock = _currentBlock();
require(rngRequest.lockBlock == 0 || currentBlock < rngRequest.lockBlock, "PeriodicPrizeStrategy/rng-in-flight");
}
function isRngTimedOut() public view returns (bool) {
if (rngRequest.requestedAt == 0) {
return false;
} else {
return _currentTime() > uint256(rngRequestTimeout).add(rngRequest.requestedAt);
}
}
modifier onlyOwnerOrListener() {
require(_msgSender() == owner() || _msgSender() == address(periodicPrizeStrategyListener), "PeriodicPrizeStrategy/only-owner-or-listener");
_;
}
modifier requireAwardNotInProgress() {
_requireAwardNotInProgress();
_;
}
modifier requireCanStartAward() {
require(_isPrizePeriodOver(), "PeriodicPrizeStrategy/prize-period-not-over");
require(!isRngRequested(), "PeriodicPrizeStrategy/rng-already-requested");
_;
}
modifier requireCanCompleteAward() {
require(isRngRequested(), "PeriodicPrizeStrategy/rng-not-requested");
require(isRngCompleted(), "PeriodicPrizeStrategy/rng-not-complete");
_;
}
modifier onlyPrizePool() {
require(_msgSender() == address(prizePool), "PeriodicPrizeStrategy/only-prize-pool");
_;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0;
/// @title Random Number Generator Interface
/// @notice Provides an interface for requesting random numbers from 3rd-party RNG services (Chainlink VRF, Starkware VDF, etc..)
interface RNGInterface {
/// @notice Emitted when a new request for a random number has been submitted
/// @param requestId The indexed ID of the request used to get the results of the RNG service
/// @param sender The indexed address of the sender of the request
event RandomNumberRequested(uint32 indexed requestId, address indexed sender);
/// @notice Emitted when an existing request for a random number has been completed
/// @param requestId The indexed ID of the request used to get the results of the RNG service
/// @param randomNumber The random number produced by the 3rd-party service
event RandomNumberCompleted(uint32 indexed requestId, uint256 randomNumber);
/// @notice Gets the last request id used by the RNG service
/// @return requestId The last request id used in the last request
function getLastRequestId() external view returns (uint32 requestId);
/// @notice Gets the Fee for making a Request against an RNG service
/// @return feeToken The address of the token that is used to pay fees
/// @return requestFee The fee required to be paid to make a request
function getRequestFee() external view returns (address feeToken, uint256 requestFee);
/// @notice Sends a request for a random number to the 3rd-party service
/// @dev Some services will complete the request immediately, others may have a time-delay
/// @dev Some services require payment in the form of a token, such as $LINK for Chainlink VRF
/// @return requestId The ID of the request used to get the results of the RNG service
/// @return lockBlock The block number at which the RNG service will start generating time-delayed randomness. The calling contract
/// should "lock" all activity until the result is available via the `requestId`
function requestRandomNumber() external returns (uint32 requestId, uint32 lockBlock);
/// @notice Checks if the request for randomness from the 3rd-party service has completed
/// @dev For time-delayed requests, this function is used to check/confirm completion
/// @param requestId The ID of the request used to get the results of the RNG service
/// @return isCompleted True if the request has completed and a random number is available, false otherwise
function isRequestComplete(uint32 requestId) external view returns (bool isCompleted);
/// @notice Gets the random number produced by the 3rd-party service
/// @param requestId The ID of the request used to get the results of the RNG service
/// @return randomNum The random number
function randomNumber(uint32 requestId) external returns (uint256 randomNum);
}
pragma solidity ^0.6.4;
import "./TokenListenerInterface.sol";
import "./TokenListenerLibrary.sol";
import "../Constants.sol";
abstract contract TokenListener is TokenListenerInterface {
function supportsInterface(bytes4 interfaceId) external override view returns (bool) {
return (
interfaceId == Constants.ERC165_INTERFACE_ID_ERC165 ||
interfaceId == TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER
);
}
}
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/introspection/IERC1820RegistryUpgradeable.sol";
library Constants {
IERC1820RegistryUpgradeable public constant REGISTRY = IERC1820RegistryUpgradeable(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// keccak256("ERC777TokensSender")
bytes32 public constant TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 public constant TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC"));
bytes32 public constant ACCEPT_MAGIC =
0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4;
bytes4 public constant ERC165_INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 public constant ERC165_INTERFACE_ID_ERC721 = 0x80ac58cd;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820RegistryUpgradeable {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
/// @title Interface that allows a user to draw an address using an index
interface TicketInterface {
/// @notice Selects a user using a random number. The random number will be uniformly bounded to the ticket totalSupply.
/// @param randomNumber The random number to use to select a user.
/// @return The winner
function draw(uint256 randomNumber) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
/* solium-disable security/no-block-members */
interface PeriodicPrizeStrategyListenerInterface is IERC165Upgradeable {
function afterPrizePoolAwarded(uint256 randomNumber, uint256 prizePeriodStartedAt) external;
}
pragma solidity ^0.6.12;
library PeriodicPrizeStrategyListenerLibrary {
/*
* bytes4(keccak256('afterPrizePoolAwarded(uint256,uint256)')) == 0x575072c6
*/
bytes4 public constant ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER = 0x575072c6;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "./CompoundPrizePool.sol";
import "../../external/openzeppelin/ProxyFactory.sol";
/// @title Compound Prize Pool Proxy Factory
/// @notice Minimal proxy pattern for creating new Compound Prize Pools
contract CompoundPrizePoolProxyFactory is ProxyFactory {
/// @notice Contract template for deploying proxied Prize Pools
CompoundPrizePool public instance;
/// @notice Initializes the Factory with an instance of the Compound Prize Pool
constructor () public {
instance = new CompoundPrizePool();
}
/// @notice Creates a new Compound Prize Pool as a proxy of the template instance
/// @return A reference to the new proxied Compound Prize Pool
function create() external returns (CompoundPrizePool) {
return CompoundPrizePool(deployMinimal(address(instance), ""));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@pooltogether/fixed-point/contracts/FixedPoint.sol";
import "../../external/compound/CTokenInterface.sol";
import "../PrizePool.sol";
/// @title Prize Pool with Compound's cToken
/// @notice Manages depositing and withdrawing assets from the Prize Pool
contract CompoundPrizePool is PrizePool {
using SafeMathUpgradeable for uint256;
event CompoundPrizePoolInitialized(address indexed cToken);
/// @notice Interface for the Yield-bearing cToken by Compound
CTokenInterface public cToken;
/// @notice Initializes the Prize Pool and Yield Service with the required contract connections
/// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool
/// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount
/// @param _maxTimelockDuration The maximum length of time the withdraw timelock could be
/// @param _cToken Address of the Compound cToken interface
function initialize (
RegistryInterface _reserveRegistry,
ControlledTokenInterface[] memory _controlledTokens,
uint256 _maxExitFeeMantissa,
uint256 _maxTimelockDuration,
CTokenInterface _cToken
)
public
initializer
{
PrizePool.initialize(
_reserveRegistry,
_controlledTokens,
_maxExitFeeMantissa,
_maxTimelockDuration
);
cToken = _cToken;
emit CompoundPrizePoolInitialized(address(cToken));
}
/// @dev Gets the balance of the underlying assets held by the Yield Service
/// @return The underlying balance of asset tokens
function _balance() internal override returns (uint256) {
return cToken.balanceOfUnderlying(address(this));
}
/// @dev Allows a user to supply asset tokens in exchange for yield-bearing tokens
/// to be held in escrow by the Yield Service
/// @param amount The amount of asset tokens to be supplied
function _supply(uint256 amount) internal override {
_token().approve(address(cToken), amount);
require(cToken.mint(amount) == 0, "CompoundPrizePool/mint-failed");
}
/// @dev Checks with the Prize Pool if a specific token type may be awarded as a prize enhancement
/// @param _externalToken The address of the token to check
/// @return True if the token may be awarded, false otherwise
function _canAwardExternal(address _externalToken) internal override view returns (bool) {
return _externalToken != address(cToken);
}
/// @dev Allows a user to redeem yield-bearing tokens in exchange for the underlying
/// asset tokens held in escrow by the Yield Service
/// @param amount The amount of underlying tokens to be redeemed
/// @return The actual amount of tokens transferred
function _redeem(uint256 amount) internal override returns (uint256) {
IERC20Upgradeable assetToken = _token();
uint256 before = assetToken.balanceOf(address(this));
require(cToken.redeemUnderlying(amount) == 0, "CompoundPrizePool/redeem-failed");
uint256 diff = assetToken.balanceOf(address(this)).sub(before);
return diff;
}
/// @dev Gets the underlying asset token used by the Yield Service
/// @return A reference to the interface of the underling asset token
function _token() internal override view returns (IERC20Upgradeable) {
return IERC20Upgradeable(cToken.underlying());
}
}
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface CTokenInterface is IERC20Upgradeable {
function decimals() external view returns (uint8);
function totalSupply() external override view returns (uint256);
function underlying() external view returns (address);
function balanceOfUnderlying(address owner) external returns (uint256);
function supplyRatePerBlock() external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
function balanceOf(address user) external override view returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
}
pragma solidity >=0.6.0 <0.7.0;
// solium-disable security/no-inline-assembly
// solium-disable security/no-low-level-calls
contract ProxyFactory {
event ProxyCreated(address proxy);
function deployMinimal(address _logic, bytes memory _data) public returns (address proxy) {
// Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol
bytes20 targetBytes = bytes20(_logic);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
emit ProxyCreated(address(proxy));
if(_data.length > 0) {
(bool success,) = proxy.call(_data);
require(success, "ProxyFactory/constructor-call-failed");
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "../token/ControlledTokenProxyFactory.sol";
import "../token/TicketProxyFactory.sol";
/* solium-disable security/no-block-members */
contract ControlledTokenBuilder {
event CreatedControlledToken(address indexed token);
event CreatedTicket(address indexed token);
ControlledTokenProxyFactory public controlledTokenProxyFactory;
TicketProxyFactory public ticketProxyFactory;
struct ControlledTokenConfig {
string name;
string symbol;
uint8 decimals;
TokenControllerInterface controller;
}
constructor (
ControlledTokenProxyFactory _controlledTokenProxyFactory,
TicketProxyFactory _ticketProxyFactory
) public {
require(address(_controlledTokenProxyFactory) != address(0), "ControlledTokenBuilder/controlledTokenProxyFactory-not-zero");
require(address(_ticketProxyFactory) != address(0), "ControlledTokenBuilder/ticketProxyFactory-not-zero");
controlledTokenProxyFactory = _controlledTokenProxyFactory;
ticketProxyFactory = _ticketProxyFactory;
}
function createControlledToken(
ControlledTokenConfig calldata config
) external returns (ControlledToken) {
ControlledToken token = controlledTokenProxyFactory.create();
token.initialize(
config.name,
config.symbol,
config.decimals,
config.controller
);
emit CreatedControlledToken(address(token));
return token;
}
function createTicket(
ControlledTokenConfig calldata config
) external returns (Ticket) {
Ticket token = ticketProxyFactory.create();
token.initialize(
config.name,
config.symbol,
config.decimals,
config.controller
);
emit CreatedTicket(address(token));
return token;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "./ControlledToken.sol";
import "../external/openzeppelin/ProxyFactory.sol";
/// @title Controlled ERC20 Token Factory
/// @notice Minimal proxy pattern for creating new Controlled ERC20 Tokens
contract ControlledTokenProxyFactory is ProxyFactory {
/// @notice Contract template for deploying proxied tokens
ControlledToken public instance;
/// @notice Initializes the Factory with an instance of the Controlled ERC20 Token
constructor () public {
instance = new ControlledToken();
}
/// @notice Creates a new Controlled ERC20 Token as a proxy of the template instance
/// @return A reference to the new proxied Controlled ERC20 Token
function create() external returns (ControlledToken) {
return ControlledToken(deployMinimal(address(instance), ""));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "./Ticket.sol";
import "../external/openzeppelin/ProxyFactory.sol";
/// @title Controlled ERC20 Token Factory
/// @notice Minimal proxy pattern for creating new Controlled ERC20 Tokens
contract TicketProxyFactory is ProxyFactory {
/// @notice Contract template for deploying proxied tokens
Ticket public instance;
/// @notice Initializes the Factory with an instance of the Controlled ERC20 Token
constructor () public {
instance = new Ticket();
}
/// @notice Creates a new Controlled ERC20 Token as a proxy of the template instance
/// @return A reference to the new proxied Controlled ERC20 Token
function create() external returns (Ticket) {
return Ticket(deployMinimal(address(instance), ""));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "sortition-sum-tree-factory/contracts/SortitionSumTreeFactory.sol";
import "@pooltogether/uniform-random-number/contracts/UniformRandomNumber.sol";
import "./ControlledToken.sol";
import "./TicketInterface.sol";
contract Ticket is ControlledToken, TicketInterface {
using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees;
bytes32 constant private TREE_KEY = keccak256("PoolTogether/Ticket");
uint256 constant private MAX_TREE_LEAVES = 5;
// Ticket-weighted odds
SortitionSumTreeFactory.SortitionSumTrees internal sortitionSumTrees;
/// @notice Initializes the Controlled Token with Token Details and the Controller
/// @param _name The name of the Token
/// @param _symbol The symbol for the Token
/// @param _decimals The number of decimals for the Token
/// @param _controller Address of the Controller contract for minting & burning
function initialize(
string memory _name,
string memory _symbol,
uint8 _decimals,
TokenControllerInterface _controller
)
public
virtual
override
initializer
{
super.initialize(_name, _symbol, _decimals, _controller);
sortitionSumTrees.createTree(TREE_KEY, MAX_TREE_LEAVES);
}
/// @notice Returns the user's chance of winning.
function chanceOf(address user) external view returns (uint256) {
return sortitionSumTrees.stakeOf(TREE_KEY, bytes32(uint256(user)));
}
/// @notice Selects a user using a random number. The random number will be uniformly bounded to the ticket totalSupply.
/// @param randomNumber The random number to use to select a user.
/// @return The winner
function draw(uint256 randomNumber) external view override returns (address) {
uint256 bound = totalSupply();
address selected;
if (bound == 0) {
selected = address(0);
} else {
uint256 token = UniformRandomNumber.uniform(randomNumber, bound);
selected = address(uint256(sortitionSumTrees.draw(TREE_KEY, token)));
}
return selected;
}
/// @dev Controller hook to provide notifications & rule validations on token transfers to the controller.
/// This includes minting and burning.
/// May be overridden to provide more granular control over operator-burning
/// @param from Address of the account sending the tokens (address(0x0) on minting)
/// @param to Address of the account receiving the tokens (address(0x0) on burning)
/// @param amount Amount of tokens being transferred
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
// optimize: ignore transfers to self
if (from == to) {
return;
}
if (from != address(0)) {
uint256 fromBalance = balanceOf(from).sub(amount);
sortitionSumTrees.set(TREE_KEY, fromBalance, bytes32(uint256(from)));
}
if (to != address(0)) {
uint256 toBalance = balanceOf(to).add(amount);
sortitionSumTrees.set(TREE_KEY, toBalance, bytes32(uint256(to)));
}
}
}
/**
* @reviewers: [@clesaege, @unknownunknown1, @ferittuncer]
* @auditors: []
* @bounties: [<14 days 10 ETH max payout>]
* @deployments: []
*/
pragma solidity ^0.6.0;
/**
* @title SortitionSumTreeFactory
* @author Enrique Piqueras - <[email protected]>
* @dev A factory of trees that keep track of staked values for sortition.
*/
library SortitionSumTreeFactory {
/* Structs */
struct SortitionSumTree {
uint K; // The maximum number of childs per node.
// We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around.
uint[] stack;
uint[] nodes;
// Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node.
mapping(bytes32 => uint) IDsToNodeIndexes;
mapping(uint => bytes32) nodeIndexesToIDs;
}
/* Storage */
struct SortitionSumTrees {
mapping(bytes32 => SortitionSumTree) sortitionSumTrees;
}
/* internal */
/**
* @dev Create a sortition sum tree at the specified key.
* @param _key The key of the new tree.
* @param _K The number of children each node in the tree should have.
*/
function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
require(tree.K == 0, "Tree already exists.");
require(_K > 1, "K must be greater than one.");
tree.K = _K;
tree.stack = new uint[](0);
tree.nodes = new uint[](0);
tree.nodes.push(0);
}
/**
* @dev Set a value of a tree.
* @param _key The key of the tree.
* @param _value The new value.
* @param _ID The ID of the value.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) { // No existing node.
if (_value != 0) { // Non zero value.
// Append.
// Add node.
if (tree.stack.length == 0) { // No vacant spots.
// Get the index and append the value.
treeIndex = tree.nodes.length;
tree.nodes.push(_value);
// Potentially append a new node and make the parent a sum node.
if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child.
uint parentIndex = treeIndex / tree.K;
bytes32 parentID = tree.nodeIndexesToIDs[parentIndex];
uint newIndex = treeIndex + 1;
tree.nodes.push(tree.nodes[parentIndex]);
delete tree.nodeIndexesToIDs[parentIndex];
tree.IDsToNodeIndexes[parentID] = newIndex;
tree.nodeIndexesToIDs[newIndex] = parentID;
}
} else { // Some vacant spot.
// Pop the stack and append the value.
treeIndex = tree.stack[tree.stack.length - 1];
tree.stack.pop();
tree.nodes[treeIndex] = _value;
}
// Add label.
tree.IDsToNodeIndexes[_ID] = treeIndex;
tree.nodeIndexesToIDs[treeIndex] = _ID;
updateParents(self, _key, treeIndex, true, _value);
}
} else { // Existing node.
if (_value == 0) { // Zero value.
// Remove.
// Remember value and set to 0.
uint value = tree.nodes[treeIndex];
tree.nodes[treeIndex] = 0;
// Push to stack.
tree.stack.push(treeIndex);
// Clear label.
delete tree.IDsToNodeIndexes[_ID];
delete tree.nodeIndexesToIDs[treeIndex];
updateParents(self, _key, treeIndex, false, value);
} else if (_value != tree.nodes[treeIndex]) { // New, non zero value.
// Set.
bool plusOrMinus = tree.nodes[treeIndex] <= _value;
uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value;
tree.nodes[treeIndex] = _value;
updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue);
}
}
}
/* internal Views */
/**
* @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned.
* @param _key The key of the tree to get the leaves from.
* @param _cursor The pagination cursor.
* @param _count The number of items to return.
* @return startIndex The index at which leaves start
* @return values The values of the returned leaves
* @return hasMore Whether there are more for pagination.
* `O(n)` where
* `n` is the maximum number of nodes ever appended.
*/
function queryLeafs(
SortitionSumTrees storage self,
bytes32 _key,
uint _cursor,
uint _count
) internal view returns(uint startIndex, uint[] memory values, bool hasMore) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
// Find the start index.
for (uint i = 0; i < tree.nodes.length; i++) {
if ((tree.K * i) + 1 >= tree.nodes.length) {
startIndex = i;
break;
}
}
// Get the values.
uint loopStartIndex = startIndex + _cursor;
values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count);
uint valuesIndex = 0;
for (uint j = loopStartIndex; j < tree.nodes.length; j++) {
if (valuesIndex < _count) {
values[valuesIndex] = tree.nodes[j];
valuesIndex++;
} else {
hasMore = true;
break;
}
}
}
/**
* @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0.
* @param _key The key of the tree.
* @param _drawnNumber The drawn number.
* @return ID The drawn ID.
* `O(k * log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = 0;
uint currentDrawnNumber = _drawnNumber % tree.nodes[0];
while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children.
for (uint i = 1; i <= tree.K; i++) { // Loop over children.
uint nodeIndex = (tree.K * treeIndex) + i;
uint nodeValue = tree.nodes[nodeIndex];
if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child.
else { // Pick this child.
treeIndex = nodeIndex;
break;
}
}
ID = tree.nodeIndexesToIDs[treeIndex];
}
/** @dev Gets a specified ID's associated value.
* @param _key The key of the tree.
* @param _ID The ID of the value.
* @return value The associated value.
*/
function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) value = 0;
else value = tree.nodes[treeIndex];
}
function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
if (tree.nodes.length == 0) {
return 0;
} else {
return tree.nodes[0];
}
}
/* Private */
/**
* @dev Update all the parents of a node.
* @param _key The key of the tree to update.
* @param _treeIndex The index of the node to start from.
* @param _plusOrMinus Wether to add (true) or substract (false).
* @param _value The value to add or substract.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint parentIndex = _treeIndex;
while (parentIndex != 0) {
parentIndex = (parentIndex - 1) / tree.K;
tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value;
}
}
}
/**
Copyright 2019 PoolTogether LLC
This file is part of PoolTogether.
PoolTogether 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 under version 3 of the License.
PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.0 <0.8.0;
/**
* @author Brendan Asselstine
* @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias.
* @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94
*/
library UniformRandomNumber {
/// @notice Select a random number without modulo bias using a random seed and upper bound
/// @param _entropy The seed for randomness
/// @param _upperBound The upper bound of the desired number
/// @return A random number less than the _upperBound
function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) {
require(_upperBound > 0, "UniformRand/min-bound");
uint256 min = -_upperBound % _upperBound;
uint256 random = _entropy;
while (true) {
if (random >= min) {
break;
}
random = uint256(keccak256(abi.encodePacked(random)));
}
return random % _upperBound;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "./ControlledTokenBuilder.sol";
import "../prize-strategy/multiple-winners/MultipleWinnersProxyFactory.sol";
/* solium-disable security/no-block-members */
contract MultipleWinnersBuilder {
event MultipleWinnersCreated(address indexed prizeStrategy);
struct MultipleWinnersConfig {
RNGInterface rngService;
uint256 prizePeriodStart;
uint256 prizePeriodSeconds;
string ticketName;
string ticketSymbol;
string sponsorshipName;
string sponsorshipSymbol;
uint256 ticketCreditLimitMantissa;
uint256 ticketCreditRateMantissa;
uint256 numberOfWinners;
bool splitExternalErc20Awards;
}
MultipleWinnersProxyFactory public multipleWinnersProxyFactory;
ControlledTokenBuilder public controlledTokenBuilder;
constructor (
MultipleWinnersProxyFactory _multipleWinnersProxyFactory,
ControlledTokenBuilder _controlledTokenBuilder
) public {
require(address(_multipleWinnersProxyFactory) != address(0), "MultipleWinnersBuilder/multipleWinnersProxyFactory-not-zero");
require(address(_controlledTokenBuilder) != address(0), "MultipleWinnersBuilder/token-builder-not-zero");
multipleWinnersProxyFactory = _multipleWinnersProxyFactory;
controlledTokenBuilder = _controlledTokenBuilder;
}
function createMultipleWinners(
PrizePool prizePool,
MultipleWinnersConfig memory prizeStrategyConfig,
uint8 decimals,
address owner
) external returns (MultipleWinners) {
MultipleWinners mw = multipleWinnersProxyFactory.create();
Ticket ticket = _createTicket(
prizeStrategyConfig.ticketName,
prizeStrategyConfig.ticketSymbol,
decimals,
prizePool
);
ControlledToken sponsorship = _createSponsorship(
prizeStrategyConfig.sponsorshipName,
prizeStrategyConfig.sponsorshipSymbol,
decimals,
prizePool
);
mw.initializeMultipleWinners(
prizeStrategyConfig.prizePeriodStart,
prizeStrategyConfig.prizePeriodSeconds,
prizePool,
ticket,
sponsorship,
prizeStrategyConfig.rngService,
prizeStrategyConfig.numberOfWinners
);
if (prizeStrategyConfig.splitExternalErc20Awards) {
mw.setSplitExternalErc20Awards(true);
}
mw.transferOwnership(owner);
emit MultipleWinnersCreated(address(mw));
return mw;
}
function createMultipleWinnersFromExistingPrizeStrategy(
PeriodicPrizeStrategy prizeStrategy,
uint256 numberOfWinners
) external returns (MultipleWinners) {
MultipleWinners mw = multipleWinnersProxyFactory.create();
mw.initializeMultipleWinners(
prizeStrategy.prizePeriodStartedAt(),
prizeStrategy.prizePeriodSeconds(),
prizeStrategy.prizePool(),
prizeStrategy.ticket(),
prizeStrategy.sponsorship(),
prizeStrategy.rng(),
numberOfWinners
);
mw.transferOwnership(msg.sender);
emit MultipleWinnersCreated(address(mw));
return mw;
}
function _createTicket(
string memory name,
string memory token,
uint8 decimals,
PrizePool prizePool
) internal returns (Ticket) {
return controlledTokenBuilder.createTicket(
ControlledTokenBuilder.ControlledTokenConfig(
name,
token,
decimals,
prizePool
)
);
}
function _createSponsorship(
string memory name,
string memory token,
uint8 decimals,
PrizePool prizePool
) internal returns (ControlledToken) {
return controlledTokenBuilder.createControlledToken(
ControlledTokenBuilder.ControlledTokenConfig(
name,
token,
decimals,
prizePool
)
);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "./MultipleWinners.sol";
import "../../external/openzeppelin/ProxyFactory.sol";
/// @title Creates a minimal proxy to the MultipleWinners prize strategy. Very cheap to deploy.
contract MultipleWinnersProxyFactory is ProxyFactory {
MultipleWinners public instance;
constructor () public {
instance = new MultipleWinners();
}
function create() external returns (MultipleWinners) {
return MultipleWinners(deployMinimal(address(instance), ""));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "../PeriodicPrizeStrategy.sol";
contract MultipleWinners is PeriodicPrizeStrategy {
uint256 internal __numberOfWinners;
bool public splitExternalErc20Awards;
event SplitExternalErc20AwardsSet(bool splitExternalErc20Awards);
event NumberOfWinnersSet(uint256 numberOfWinners);
event NoWinners();
function initializeMultipleWinners (
uint256 _prizePeriodStart,
uint256 _prizePeriodSeconds,
PrizePool _prizePool,
TicketInterface _ticket,
IERC20Upgradeable _sponsorship,
RNGInterface _rng,
uint256 _numberOfWinners
) public initializer {
IERC20Upgradeable[] memory _externalErc20Awards;
PeriodicPrizeStrategy.initialize(
_prizePeriodStart,
_prizePeriodSeconds,
_prizePool,
_ticket,
_sponsorship,
_rng,
_externalErc20Awards
);
_setNumberOfWinners(_numberOfWinners);
}
function setSplitExternalErc20Awards(bool _splitExternalErc20Awards) external onlyOwner requireAwardNotInProgress {
splitExternalErc20Awards = _splitExternalErc20Awards;
emit SplitExternalErc20AwardsSet(splitExternalErc20Awards);
}
function setNumberOfWinners(uint256 count) external onlyOwner requireAwardNotInProgress {
_setNumberOfWinners(count);
}
function _setNumberOfWinners(uint256 count) internal {
require(count > 0, "MultipleWinners/winners-gte-one");
__numberOfWinners = count;
emit NumberOfWinnersSet(count);
}
function numberOfWinners() external view returns (uint256) {
return __numberOfWinners;
}
function _distribute(uint256 randomNumber) internal override {
uint256 prize = prizePool.captureAwardBalance();
// main winner is simply the first that is drawn
address mainWinner = ticket.draw(randomNumber);
// If drawing yields no winner, then there is no one to pick
if (mainWinner == address(0)) {
emit NoWinners();
return;
}
// main winner gets all external ERC721 tokens
_awardExternalErc721s(mainWinner);
address[] memory winners = new address[](__numberOfWinners);
winners[0] = mainWinner;
uint256 nextRandom = randomNumber;
for (uint256 winnerCount = 1; winnerCount < __numberOfWinners; winnerCount++) {
// add some arbitrary numbers to the previous random number to ensure no matches with the UniformRandomNumber lib
bytes32 nextRandomHash = keccak256(abi.encodePacked(nextRandom + 499 + winnerCount*521));
nextRandom = uint256(nextRandomHash);
winners[winnerCount] = ticket.draw(nextRandom);
}
// yield prize is split up among all winners
uint256 prizeShare = prize.div(winners.length);
if (prizeShare > 0) {
for (uint i = 0; i < winners.length; i++) {
_awardTickets(winners[i], prizeShare);
}
}
if (splitExternalErc20Awards) {
address currentToken = externalErc20s.start();
while (currentToken != address(0) && currentToken != externalErc20s.end()) {
uint256 balance = IERC20Upgradeable(currentToken).balanceOf(address(prizePool));
uint256 split = balance.div(__numberOfWinners);
if (split > 0) {
for (uint256 i = 0; i < winners.length; i++) {
prizePool.awardExternalERC20(winners[i], currentToken, split);
}
}
currentToken = externalErc20s.next(currentToken);
}
} else {
_awardExternalErc20s(mainWinner);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol";
import "@nomiclabs/buidler/console.sol";
import "./CompoundPrizePoolBuilder.sol";
import "./VaultPrizePoolBuilder.sol";
import "./StakePrizePoolBuilder.sol";
import "./MultipleWinnersBuilder.sol";
contract PoolWithMultipleWinnersBuilder {
using SafeCastUpgradeable for uint256;
event CompoundPrizePoolWithMultipleWinnersCreated(address indexed prizePool, address indexed prizeStrategy);
event StakePrizePoolWithMultipleWinnersCreated(address indexed prizePool, address indexed prizeStrategy);
event VaultPrizePoolWithMultipleWinnersCreated(address indexed prizePool, address indexed prizeStrategy);
CompoundPrizePoolBuilder public compoundPrizePoolBuilder;
VaultPrizePoolBuilder public vaultPrizePoolBuilder;
StakePrizePoolBuilder public stakePrizePoolBuilder;
MultipleWinnersBuilder public multipleWinnersBuilder;
constructor (
CompoundPrizePoolBuilder _compoundPrizePoolBuilder,
VaultPrizePoolBuilder _vaultPrizePoolBuilder,
StakePrizePoolBuilder _stakePrizePoolBuilder,
MultipleWinnersBuilder _multipleWinnersBuilder
) public {
require(address(_compoundPrizePoolBuilder) != address(0), "GlobalBuilder/compoundPrizePoolBuilder-not-zero");
require(address(_vaultPrizePoolBuilder) != address(0), "GlobalBuilder/vaultPrizePoolBuilder-not-zero");
require(address(_stakePrizePoolBuilder) != address(0), "GlobalBuilder/stakePrizePoolBuilder-not-zero");
require(address(_multipleWinnersBuilder) != address(0), "GlobalBuilder/multipleWinnersBuilder-not-zero");
compoundPrizePoolBuilder = _compoundPrizePoolBuilder;
vaultPrizePoolBuilder = _vaultPrizePoolBuilder;
stakePrizePoolBuilder = _stakePrizePoolBuilder;
multipleWinnersBuilder = _multipleWinnersBuilder;
}
function createCompoundMultipleWinners(
CompoundPrizePoolBuilder.CompoundPrizePoolConfig memory prizePoolConfig,
MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig,
uint8 decimals
) external returns (CompoundPrizePool) {
CompoundPrizePool prizePool = compoundPrizePoolBuilder.createCompoundPrizePool(prizePoolConfig);
MultipleWinners prizeStrategy = _createMultipleWinnersAndTransferPrizePool(prizePool, prizeStrategyConfig, decimals);
emit CompoundPrizePoolWithMultipleWinnersCreated(address(prizePool), address(prizeStrategy));
return prizePool;
}
function createStakeMultipleWinners(
StakePrizePoolBuilder.StakePrizePoolConfig memory prizePoolConfig,
MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig,
uint8 decimals
) external returns (StakePrizePool) {
StakePrizePool prizePool = stakePrizePoolBuilder.createStakePrizePool(prizePoolConfig);
MultipleWinners prizeStrategy = _createMultipleWinnersAndTransferPrizePool(prizePool, prizeStrategyConfig, decimals);
emit StakePrizePoolWithMultipleWinnersCreated(address(prizePool), address(prizeStrategy));
return prizePool;
}
function createVaultMultipleWinners(
VaultPrizePoolBuilder.VaultPrizePoolConfig memory prizePoolConfig,
MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig,
uint8 decimals
) external returns (yVaultPrizePool) {
yVaultPrizePool prizePool = vaultPrizePoolBuilder.createVaultPrizePool(prizePoolConfig);
MultipleWinners prizeStrategy = _createMultipleWinnersAndTransferPrizePool(prizePool, prizeStrategyConfig, decimals);
emit VaultPrizePoolWithMultipleWinnersCreated(address(prizePool), address(prizeStrategy));
return prizePool;
}
function _createMultipleWinnersAndTransferPrizePool(
PrizePool prizePool,
MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig,
uint8 decimals
) internal returns (MultipleWinners) {
MultipleWinners periodicPrizeStrategy = multipleWinnersBuilder.createMultipleWinners(
prizePool,
prizeStrategyConfig,
decimals,
msg.sender
);
address ticket = address(periodicPrizeStrategy.ticket());
prizePool.setPrizeStrategy(periodicPrizeStrategy);
prizePool.addControlledToken(Ticket(ticket));
prizePool.addControlledToken(ControlledTokenInterface(address(periodicPrizeStrategy.sponsorship())));
prizePool.setCreditPlanOf(
ticket,
prizeStrategyConfig.ticketCreditRateMantissa.toUint128(),
prizeStrategyConfig.ticketCreditLimitMantissa.toUint128()
);
prizePool.transferOwnership(msg.sender);
return periodicPrizeStrategy;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.8.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logByte(byte p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(byte)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "../registry/RegistryInterface.sol";
import "./PrizePoolBuilder.sol";
import "../prize-pool/yearn/yVaultPrizePoolProxyFactory.sol";
import "../external/yearn/yVaultInterface.sol";
import "../external/openzeppelin/OpenZeppelinProxyFactoryInterface.sol";
/* solium-disable security/no-block-members */
contract VaultPrizePoolBuilder is PrizePoolBuilder {
using SafeMathUpgradeable for uint256;
using SafeCastUpgradeable for uint256;
struct VaultPrizePoolConfig {
yVaultInterface vault;
uint256 reserveRateMantissa;
uint256 maxExitFeeMantissa;
uint256 maxTimelockDuration;
}
RegistryInterface public reserveRegistry;
yVaultPrizePoolProxyFactory public vaultPrizePoolProxyFactory;
constructor (
RegistryInterface _reserveRegistry,
yVaultPrizePoolProxyFactory _vaultPrizePoolProxyFactory
) public {
require(address(_reserveRegistry) != address(0), "VaultPrizePoolBuilder/reserveRegistry-not-zero");
require(address(_vaultPrizePoolProxyFactory) != address(0), "VaultPrizePoolBuilder/compound-prize-pool-builder-not-zero");
reserveRegistry = _reserveRegistry;
vaultPrizePoolProxyFactory = _vaultPrizePoolProxyFactory;
}
function createVaultPrizePool(
VaultPrizePoolConfig calldata config
)
external
returns (yVaultPrizePool)
{
yVaultPrizePool prizePool = vaultPrizePoolProxyFactory.create();
ControlledTokenInterface[] memory tokens;
prizePool.initialize(
reserveRegistry,
tokens,
config.maxExitFeeMantissa,
config.maxTimelockDuration,
config.vault,
config.reserveRateMantissa
);
prizePool.transferOwnership(msg.sender);
emit PrizePoolCreated(msg.sender, address(prizePool));
return prizePool;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "./yVaultPrizePool.sol";
import "../../external/openzeppelin/ProxyFactory.sol";
/// @title yVault Prize Pool Proxy Factory
/// @notice Minimal proxy pattern for creating new yVault Prize Pools
contract yVaultPrizePoolProxyFactory is ProxyFactory {
/// @notice Contract template for deploying proxied Prize Pools
yVaultPrizePool public instance;
/// @notice Initializes the Factory with an instance of the yVault Prize Pool
constructor () public {
instance = new yVaultPrizePool();
}
/// @notice Creates a new yVault Prize Pool as a proxy of the template instance
/// @return A reference to the new proxied yVault Prize Pool
function create() external returns (yVaultPrizePool) {
return yVaultPrizePool(deployMinimal(address(instance), ""));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../../external/yearn/yVaultInterface.sol";
import "../PrizePool.sol";
/// @title Prize Pool for yEarn's yVaults
contract yVaultPrizePool is PrizePool {
using SafeMathUpgradeable for uint256;
event yVaultPrizePoolInitialized(address indexed vault);
event ReserveRateMantissaSet(uint256 reserveRateMantissa);
/// @notice Interface for the yEarn yVault
yVaultInterface public vault;
/// Amount that is never exposed to the prize
uint256 public reserveRateMantissa;
/// @notice Initializes the Prize Pool and Yield Service with the required contract connections
/// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool
/// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount
/// @param _maxTimelockDuration The maximum length of time the withdraw timelock could be
/// @param _vault Address of the yEarn yVaultInterface
function initialize (
RegistryInterface _reserveRegistry,
ControlledTokenInterface[] memory _controlledTokens,
uint256 _maxExitFeeMantissa,
uint256 _maxTimelockDuration,
yVaultInterface _vault,
uint256 _reserveRateMantissa
)
public
initializer
{
PrizePool.initialize(
_reserveRegistry,
_controlledTokens,
_maxExitFeeMantissa,
_maxTimelockDuration
);
vault = _vault;
_setReserveRateMantissa(_reserveRateMantissa);
emit yVaultPrizePoolInitialized(address(vault));
}
function setReserveRateMantissa(uint256 _reserveRateMantissa) external onlyOwner {
_setReserveRateMantissa(_reserveRateMantissa);
}
function _setReserveRateMantissa(uint256 _reserveRateMantissa) internal {
require(_reserveRateMantissa < 1 ether, "yVaultPrizePool/reserve-rate-lt-one");
reserveRateMantissa = _reserveRateMantissa;
emit ReserveRateMantissaSet(reserveRateMantissa);
}
/// @dev Gets the balance of the underlying assets held by the Yield Service
/// @return The underlying balance of asset tokens
function _balance() internal override returns (uint256) {
uint256 total = _sharesToToken(vault.balanceOf(address(this)));
uint256 reserve = FixedPoint.multiplyUintByMantissa(total, reserveRateMantissa);
return total.sub(reserve);
}
/// @dev Allows a user to supply asset tokens in exchange for yield-bearing tokens
/// to be held in escrow by the Yield Service
function _supply(uint256) internal override {
IERC20Upgradeable assetToken = _token();
uint256 total = assetToken.balanceOf(address(this));
assetToken.approve(address(vault), total);
vault.deposit(total);
}
/// @dev Allows a user to supply asset tokens in exchange for yield-bearing tokens
/// to be held in escrow by the Yield Service
function _supplySpecific(uint256 amount) internal {
_token().approve(address(vault), amount);
vault.deposit(amount);
}
/// @dev The external token cannot be yDai or Dai
/// @param _externalToken The address of the token to check
/// @return True if the token may be awarded, false otherwise
function _canAwardExternal(address _externalToken) internal override view returns (bool) {
return _externalToken != address(vault) && _externalToken != address(vault.token());
}
/// @dev Allows a user to redeem yield-bearing tokens in exchange for the underlying
/// asset tokens held in escrow by the Yield Service
/// @param amount The amount of underlying tokens to be redeemed
/// @return The actual amount of tokens transferred
function _redeem(uint256 amount) internal override returns (uint256) {
IERC20Upgradeable token = _token();
require(_balance() >= amount, "yVaultPrizePool/insuff-liquidity");
// yVault will try to over-withdraw so that amount is always available
// we want: amount = X - X*feeRate
// amount = X(1 - feeRate)
// amount / (1 - feeRate) = X
// calculate possible fee
uint256 withdrawal;
if (reserveRateMantissa > 0) {
withdrawal = FixedPoint.divideUintByMantissa(amount, uint256(1e18).sub(reserveRateMantissa));
} else {
withdrawal = amount;
}
uint256 sharesToWithdraw = _tokenToShares(withdrawal);
uint256 preBalance = token.balanceOf(address(this));
vault.withdraw(sharesToWithdraw);
uint256 postBalance = token.balanceOf(address(this));
uint256 amountWithdrawn = postBalance.sub(preBalance);
uint256 amountRedeemable = (amountWithdrawn < amount) ? amountWithdrawn : amount;
// Redeposit any asset funds that were removed preemptively for fees
if (postBalance > amountRedeemable) {
_supplySpecific(postBalance.sub(amountRedeemable));
}
return amountRedeemable;
}
function _tokenToShares(uint256 tokens) internal view returns (uint256) {
/**
ex. rate = tokens / shares
=> shares = shares_total * (tokens / tokens total)
*/
return vault.totalSupply().mul(tokens).div(vault.balance());
}
function _sharesToToken(uint256 shares) internal view returns (uint256) {
uint256 ts = vault.totalSupply();
if (ts == 0 || shares == 0) {
return 0;
}
return (vault.balance().mul(shares)).div(ts);
}
/// @dev Gets the underlying asset token used by the Yield Service
/// @return A reference to the interface of the underling asset token
function _token() internal override view returns (IERC20Upgradeable) {
return IERC20Upgradeable(vault.token());
}
}
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface yVaultInterface is IERC20Upgradeable {
function token() external view returns (IERC20Upgradeable);
function balance() external view returns (uint256);
function deposit(uint256 _amount) external;
function withdraw(uint256 _shares) external;
function getPricePerFullShare() external view returns (uint256);
}
pragma solidity >=0.6.0 <0.7.0;
interface OpenZeppelinProxyFactoryInterface {
function deploy(uint256 _salt, address _logic, address _admin, bytes calldata _data) external returns (address);
function getDeploymentAddress(uint256 _salt, address _sender) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "./PrizePoolBuilder.sol";
import "../registry/RegistryInterface.sol";
import "../builders/MultipleWinnersBuilder.sol";
import "../prize-pool/stake/StakePrizePoolProxyFactory.sol";
/* solium-disable security/no-block-members */
contract StakePrizePoolBuilder is PrizePoolBuilder {
using SafeMathUpgradeable for uint256;
using SafeCastUpgradeable for uint256;
struct StakePrizePoolConfig {
IERC20Upgradeable token;
uint256 maxExitFeeMantissa;
uint256 maxTimelockDuration;
}
RegistryInterface public reserveRegistry;
StakePrizePoolProxyFactory public stakePrizePoolProxyFactory;
constructor (
RegistryInterface _reserveRegistry,
StakePrizePoolProxyFactory _stakePrizePoolProxyFactory
) public {
require(address(_reserveRegistry) != address(0), "StakePrizePoolBuilder/reserveRegistry-not-zero");
require(address(_stakePrizePoolProxyFactory) != address(0), "StakePrizePoolBuilder/stake-prize-pool-proxy-factory-not-zero");
reserveRegistry = _reserveRegistry;
stakePrizePoolProxyFactory = _stakePrizePoolProxyFactory;
}
function createStakePrizePool(
StakePrizePoolConfig calldata config
)
external
returns (StakePrizePool)
{
StakePrizePool prizePool = stakePrizePoolProxyFactory.create();
ControlledTokenInterface[] memory tokens;
prizePool.initialize(
reserveRegistry,
tokens,
config.maxExitFeeMantissa,
config.maxTimelockDuration,
config.token
);
prizePool.transferOwnership(msg.sender);
emit PrizePoolCreated(msg.sender, address(prizePool));
return prizePool;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "./StakePrizePool.sol";
import "../../external/openzeppelin/ProxyFactory.sol";
/// @title Stake Prize Pool Proxy Factory
/// @notice Minimal proxy pattern for creating new yVault Prize Pools
contract StakePrizePoolProxyFactory is ProxyFactory {
/// @notice Contract template for deploying proxied Prize Pools
StakePrizePool public instance;
/// @notice Initializes the Factory with an instance of the yVault Prize Pool
constructor () public {
instance = new StakePrizePool();
}
/// @notice Creates a new Stake Prize Pool as a proxy of the template instance
/// @return A reference to the new proxied Stake Prize Pool
function create() external returns (StakePrizePool) {
return StakePrizePool(deployMinimal(address(instance), ""));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../PrizePool.sol";
contract StakePrizePool is PrizePool {
IERC20Upgradeable private stakeToken;
event StakePrizePoolInitialized(address indexed stakeToken);
/// @notice Initializes the Prize Pool and Yield Service with the required contract connections
/// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool
/// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount
/// @param _maxTimelockDuration The maximum length of time the withdraw timelock could be
/// @param _stakeToken Address of the stake token
function initialize (
RegistryInterface _reserveRegistry,
ControlledTokenInterface[] memory _controlledTokens,
uint256 _maxExitFeeMantissa,
uint256 _maxTimelockDuration,
IERC20Upgradeable _stakeToken
)
public
initializer
{
PrizePool.initialize(
_reserveRegistry,
_controlledTokens,
_maxExitFeeMantissa,
_maxTimelockDuration
);
stakeToken = _stakeToken;
emit StakePrizePoolInitialized(address(stakeToken));
}
/// @notice Determines whether the passed token can be transferred out as an external award.
/// @dev Different yield sources will hold the deposits as another kind of token: such a Compound's cToken. The
/// prize strategy should not be allowed to move those tokens.
/// @param _externalToken The address of the token to check
/// @return True if the token may be awarded, false otherwise
function _canAwardExternal(address _externalToken) internal override view returns (bool) {
return address(stakeToken) != _externalToken;
}
/// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.
/// @return The underlying balance of asset tokens
function _balance() internal override returns (uint256) {
return stakeToken.balanceOf(address(this));
}
function _token() internal override view returns (IERC20Upgradeable) {
return stakeToken;
}
/// @notice Supplies asset tokens to the yield source.
/// @param mintAmount The amount of asset tokens to be supplied
function _supply(uint256 mintAmount) internal override {
// no-op because nothing else needs to be done
}
/// @notice Redeems asset tokens from the yield source.
/// @param redeemAmount The amount of yield-bearing tokens to be redeemed
/// @return The actual amount of tokens that were redeemed.
function _redeem(uint256 redeemAmount) internal override returns (uint256) {
return redeemAmount;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol";
import "../utils/UInt256Array.sol";
import "./ComptrollerStorage.sol";
import "../token/TokenListener.sol";
/// @title The Comptroller disburses rewards to pool users
/* solium-disable security/no-block-members */
contract Comptroller is ComptrollerStorage, TokenListener {
using SafeMathUpgradeable for uint256;
using SafeCastUpgradeable for uint256;
using UInt256Array for uint256[];
using ExtendedSafeCast for uint256;
using BalanceDrip for BalanceDrip.State;
using VolumeDrip for VolumeDrip.State;
using BalanceDripManager for BalanceDripManager.State;
using VolumeDripManager for VolumeDripManager.State;
using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping;
/// @notice Emitted when a balance drip is actived
event BalanceDripActivated(
address indexed source,
address indexed measure,
address indexed dripToken,
uint256 dripRatePerSecond
);
/// @notice Emitted when a balance drip is deactivated
event BalanceDripDeactivated(
address indexed source,
address indexed measure,
address indexed dripToken
);
/// @notice Emitted when a balance drip rate is updated
event BalanceDripRateSet(
address indexed source,
address indexed measure,
address indexed dripToken,
uint256 dripRatePerSecond
);
/// @notice Emitted when a balance drip drips tokens
event BalanceDripDripped(
address indexed source,
address indexed measure,
address indexed dripToken,
address user,
uint256 amount
);
event DripTokenDripped(
address indexed dripToken,
address indexed user,
uint256 amount
);
/// @notice Emitted when a volue drip drips tokens
event VolumeDripDripped(
address indexed source,
address indexed measure,
address indexed dripToken,
bool isReferral,
address user,
uint256 amount
);
/// @notice Emitted when a user claims drip tokens
event DripTokenClaimed(
address indexed operator,
address indexed dripToken,
address indexed user,
uint256 amount
);
/// @notice Emitted when a volume drip is activated
event VolumeDripActivated(
address indexed source,
address indexed measure,
address indexed dripToken,
bool isReferral,
uint256 periodSeconds,
uint256 dripAmount
);
event TransferredOut(
address indexed token,
address indexed to,
uint256 amount
);
/// @notice Emitted when a new volume drip period has started
event VolumeDripPeriodStarted(
address indexed source,
address indexed measure,
address indexed dripToken,
bool isReferral,
uint32 period,
uint256 dripAmount,
uint256 endTime
);
/// @notice Emitted when a volume drip period has ended
event VolumeDripPeriodEnded(
address indexed source,
address indexed measure,
address indexed dripToken,
bool isReferral,
uint32 period,
uint256 totalSupply,
uint256 drippedTokens
);
/// @notice Emitted when a volume drip is updated
event VolumeDripSet(
address indexed source,
address indexed measure,
address indexed dripToken,
bool isReferral,
uint256 periodSeconds,
uint256 dripAmount
);
/// @notice Emitted when a volume drip is deactivated.
event VolumeDripDeactivated(
address indexed source,
address indexed measure,
address indexed dripToken,
bool isReferral
);
/// @notice Convenience struct used when updating drips
struct UpdatePair {
address source;
address measure;
}
/// @notice Convenience struct used to retrieve balances after updating drips
struct DripTokenBalance {
address dripToken;
uint256 balance;
}
/// @notice Initializes a new Comptroller.
constructor () public {
__Ownable_init();
}
function transferOut(address token, address to, uint256 amount) external onlyOwner {
IERC20Upgradeable(token).transfer(to, amount);
emit TransferredOut(token, to, amount);
}
/// @notice Activates a balance drip. Only callable by the owner.
/// @param source The balance drip "source"; i.e. a Prize Pool address.
/// @param measure The ERC20 token whose balances determines user's share of the drip rate.
/// @param dripToken The token that is dripped to users.
/// @param dripRatePerSecond The amount of drip tokens that are awarded each second to the total supply of measure.
function activateBalanceDrip(address source, address measure, address dripToken, uint256 dripRatePerSecond) external onlyOwner {
balanceDrips[source].activateDrip(measure, dripToken, dripRatePerSecond);
emit BalanceDripActivated(
source,
measure,
dripToken,
dripRatePerSecond
);
}
/// @notice Deactivates a balance drip. Only callable by the owner.
/// @param source The balance drip "source"; i.e. a Prize Pool address.
/// @param measure The ERC20 token whose balances determines user's share of the drip rate.
/// @param dripToken The token that is dripped to users.
/// @param prevDripToken The previous drip token in the balance drip list. If the dripToken is the first address,
/// then the previous address is the SENTINEL address: 0x0000000000000000000000000000000000000001
function deactivateBalanceDrip(address source, address measure, address dripToken, address prevDripToken) external onlyOwner {
_deactivateBalanceDrip(source, measure, dripToken, prevDripToken);
}
/// @notice Deactivates a balance drip. Only callable by the owner.
/// @param source The balance drip "source"; i.e. a Prize Pool address.
/// @param measure The ERC20 token whose balances determines user's share of the drip rate.
/// @param dripToken The token that is dripped to users.
/// @param prevDripToken The previous drip token in the balance drip list. If the dripToken is the first address,
/// then the previous address is the SENTINEL address: 0x0000000000000000000000000000000000000001
function _deactivateBalanceDrip(address source, address measure, address dripToken, address prevDripToken) internal {
balanceDrips[source].deactivateDrip(measure, dripToken, prevDripToken, _currentTime().toUint32(), _availableDripTokenBalance(dripToken));
emit BalanceDripDeactivated(source, measure, dripToken);
}
/// @notice Gets a list of active balance drip tokens
/// @param source The balance drip "source"; i.e. a Prize Pool address.
/// @param measure The ERC20 token whose balances determines user's share of the drip rate.
/// @return An array of active Balance Drip token addresses
function getActiveBalanceDripTokens(address source, address measure) external view returns (address[] memory) {
return balanceDrips[source].getActiveBalanceDrips(measure);
}
/// @notice Returns the state of a balance drip.
/// @param source The balance drip "source"; i.e. Prize Pool
/// @param measure The token that measure's a users share of the drip
/// @param dripToken The token that is being dripped to users
/// @return dripRatePerSecond The current drip rate of the balance drip.
/// @return exchangeRateMantissa The current exchange rate from measure to dripTokens
/// @return timestamp The timestamp at which the balance drip was last updated.
function getBalanceDrip(
address source,
address measure,
address dripToken
)
external
view
returns (
uint256 dripRatePerSecond,
uint128 exchangeRateMantissa,
uint32 timestamp
)
{
BalanceDrip.State storage balanceDrip = balanceDrips[source].getDrip(measure, dripToken);
dripRatePerSecond = balanceDrip.dripRatePerSecond;
exchangeRateMantissa = balanceDrip.exchangeRateMantissa;
timestamp = balanceDrip.timestamp;
}
/// @notice Sets the drip rate for a balance drip. The drip rate is the number of drip tokens given to the
/// entire supply of measure tokens. Only callable by the owner.
/// @param source The balance drip "source"; i.e. Prize Pool
/// @param measure The token to use to measure a user's share of the drip rate
/// @param dripToken The token that is dripped to the user
/// @param dripRatePerSecond The new drip rate per second
function setBalanceDripRate(address source, address measure, address dripToken, uint256 dripRatePerSecond) external onlyOwner {
balanceDrips[source].setDripRate(measure, dripToken, dripRatePerSecond, _currentTime().toUint32(), _availableDripTokenBalance(dripToken));
emit BalanceDripRateSet(
source,
measure,
dripToken,
dripRatePerSecond
);
}
/// @notice Activates a volume drip. Volume drips distribute tokens to users based on their share of the activity within a period.
/// @param source The Prize Pool for which to bind to
/// @param measure The Prize Pool controlled token whose volume should be measured
/// @param dripToken The token that is being disbursed
/// @param isReferral Whether this volume drip is for referrals
/// @param periodSeconds The period of the volume drip, in seconds
/// @param dripAmount The amount of dripTokens disbursed each period.
/// @param endTime The time at which the first period ends.
function activateVolumeDrip(
address source,
address measure,
address dripToken,
bool isReferral,
uint32 periodSeconds,
uint112 dripAmount,
uint32 endTime
)
external
onlyOwner
{
uint32 period;
if (isReferral) {
period = referralVolumeDrips[source].activate(measure, dripToken, periodSeconds, dripAmount, endTime);
} else {
period = volumeDrips[source].activate(measure, dripToken, periodSeconds, dripAmount, endTime);
}
emit VolumeDripActivated(
source,
measure,
dripToken,
isReferral,
periodSeconds,
dripAmount
);
emit VolumeDripPeriodStarted(
source,
measure,
dripToken,
isReferral,
period,
dripAmount,
endTime
);
}
/// @notice Deactivates a volume drip. Volume drips distribute tokens to users based on their share of the activity within a period.
/// @param source The Prize Pool for which to bind to
/// @param measure The Prize Pool controlled token whose volume should be measured
/// @param dripToken The token that is being disbursed
/// @param isReferral Whether this volume drip is for referrals
/// @param prevDripToken The previous drip token in the volume drip list. Is different for referrals vs non-referral volume drips.
function deactivateVolumeDrip(
address source,
address measure,
address dripToken,
bool isReferral,
address prevDripToken
)
external
onlyOwner
{
_deactivateVolumeDrip(source, measure, dripToken, isReferral, prevDripToken);
}
/// @notice Deactivates a volume drip. Volume drips distribute tokens to users based on their share of the activity within a period.
/// @param source The Prize Pool for which to bind to
/// @param measure The Prize Pool controlled token whose volume should be measured
/// @param dripToken The token that is being disbursed
/// @param isReferral Whether this volume drip is for referrals
/// @param prevDripToken The previous drip token in the volume drip list. Is different for referrals vs non-referral volume drips.
function _deactivateVolumeDrip(
address source,
address measure,
address dripToken,
bool isReferral,
address prevDripToken
)
internal
{
if (isReferral) {
referralVolumeDrips[source].deactivate(measure, dripToken, prevDripToken);
} else {
volumeDrips[source].deactivate(measure, dripToken, prevDripToken);
}
emit VolumeDripDeactivated(
source,
measure,
dripToken,
isReferral
);
}
/// @notice Sets the parameters for the *next* volume drip period. The source, measure, dripToken and isReferral combined
/// are used to uniquely identify a volume drip. Only callable by the owner.
/// @param source The Prize Pool of the volume drip
/// @param measure The token whose volume is being measured
/// @param dripToken The token that is being disbursed
/// @param isReferral Whether this volume drip is a referral
/// @param periodSeconds The length to use for the next period
/// @param dripAmount The amount of tokens to drip for the next period
function setVolumeDrip(
address source,
address measure,
address dripToken,
bool isReferral,
uint32 periodSeconds,
uint112 dripAmount
)
external
onlyOwner
{
if (isReferral) {
referralVolumeDrips[source].set(measure, dripToken, periodSeconds, dripAmount);
} else {
volumeDrips[source].set(measure, dripToken, periodSeconds, dripAmount);
}
emit VolumeDripSet(
source,
measure,
dripToken,
isReferral,
periodSeconds,
dripAmount
);
}
function getVolumeDrip(
address source,
address measure,
address dripToken,
bool isReferral
)
external
view
returns (
uint256 periodSeconds,
uint256 dripAmount,
uint256 periodCount
)
{
VolumeDrip.State memory drip;
if (isReferral) {
drip = referralVolumeDrips[source].volumeDrips[measure][dripToken];
} else {
drip = volumeDrips[source].volumeDrips[measure][dripToken];
}
return (
drip.nextPeriodSeconds,
drip.nextDripAmount,
drip.periodCount
);
}
/// @notice Gets a list of active volume drip tokens
/// @param source The volume drip "source"; i.e. a Prize Pool address.
/// @param measure The ERC20 token whose volume determines user's share of the drip rate.
/// @param isReferral Whether this volume drip is a referral
/// @return An array of active Volume Drip token addresses
function getActiveVolumeDripTokens(address source, address measure, bool isReferral) external view returns (address[] memory) {
if (isReferral) {
return referralVolumeDrips[source].getActiveVolumeDrips(measure);
} else {
return volumeDrips[source].getActiveVolumeDrips(measure);
}
}
function isVolumeDripActive(
address source,
address measure,
address dripToken,
bool isReferral
)
external
view
returns (bool)
{
if (isReferral) {
return referralVolumeDrips[source].isActive(measure, dripToken);
} else {
return volumeDrips[source].isActive(measure, dripToken);
}
}
function getVolumeDripPeriod(
address source,
address measure,
address dripToken,
bool isReferral,
uint16 period
)
external
view
returns (
uint112 totalSupply,
uint112 dripAmount,
uint32 endTime
)
{
VolumeDrip.Period memory periodState;
if (isReferral) {
periodState = referralVolumeDrips[source].volumeDrips[measure][dripToken].periods[period];
} else {
periodState = volumeDrips[source].volumeDrips[measure][dripToken].periods[period];
}
return (
periodState.totalSupply,
periodState.dripAmount,
periodState.endTime
);
}
/// @notice Returns a users claimable balance of drip tokens. This is the combination of all balance and volume drips.
/// @param dripToken The token that is being disbursed
/// @param user The user whose balance should be checked.
/// @return The claimable balance of the dripToken by the user.
function balanceOfDrip(address user, address dripToken) external view returns (uint256) {
return dripTokenBalances[dripToken][user];
}
/// @notice Claims a drip token on behalf of a user. If the passed amount is less than or equal to the users drip balance, then
/// they will be transferred that amount. Otherwise, it fails.
/// @param user The user for whom to claim the drip tokens
/// @param dripToken The drip token to claim
/// @param amount The amount of drip token to claim
function claimDrip(address user, address dripToken, uint256 amount) public {
address sender = _msgSender();
dripTokenTotalSupply[dripToken] = dripTokenTotalSupply[dripToken].sub(amount);
dripTokenBalances[dripToken][user] = dripTokenBalances[dripToken][user].sub(amount);
require(IERC20Upgradeable(dripToken).transfer(user, amount), "Comptroller/claim-transfer-failed");
emit DripTokenClaimed(sender, dripToken, user, amount);
}
function claimDrips(address user, address[] memory dripTokens) public {
for (uint i = 0; i < dripTokens.length; i++) {
claimDrip(user, dripTokens[i], dripTokenBalances[dripTokens[i]][user]);
}
}
function updateActiveBalanceDripsForPairs(
UpdatePair[] memory pairs
) public {
uint256 currentTime = _currentTime();
uint256 i;
for (i = 0; i < pairs.length; i++) {
UpdatePair memory pair = pairs[i];
_updateActiveBalanceDrips(
balanceDrips[pair.source],
pair.source,
pair.measure,
IERC20Upgradeable(pair.measure).totalSupply(),
currentTime
);
}
}
function updateActiveVolumeDripsForPairs(
UpdatePair[] memory pairs
) public {
uint256 i;
for (i = 0; i < pairs.length; i++) {
UpdatePair memory pair = pairs[i];
_updateActiveVolumeDrips(
volumeDrips[pair.source],
pair.source,
pair.measure,
false
);
_updateActiveVolumeDrips(
referralVolumeDrips[pair.source],
pair.source,
pair.measure,
true
);
}
}
function mintAndCaptureVolumeDripsForPairs(
UpdatePair[] memory pairs,
address user,
uint256 amount,
address[] memory dripTokens
) public {
uint256 i;
for (i = 0; i < pairs.length; i++) {
UpdatePair memory pair = pairs[i];
_mintAndCaptureForVolumeDrips(pair.source, pair.measure, user, amount, dripTokens);
_mintAndCaptureReferralVolumeDrips(pair.source, pair.measure, user, amount, dripTokens);
}
}
function _mintAndCaptureForVolumeDrips(
address source,
address measure,
address user,
uint256 amount,
address[] memory dripTokens
) internal {
uint i;
for (i = 0; i < dripTokens.length; i++) {
address dripToken = dripTokens[i];
VolumeDrip.State storage state = volumeDrips[source].volumeDrips[measure][dripToken];
_captureClaimForVolumeDrip(state, source, measure, dripToken, false, user, amount);
}
}
function _mintAndCaptureReferralVolumeDrips(
address source,
address measure,
address user,
uint256 amount,
address[] memory dripTokens
) internal {
uint i;
for (i = 0; i < dripTokens.length; i++) {
address dripToken = dripTokens[i];
VolumeDrip.State storage referralState = referralVolumeDrips[source].volumeDrips[measure][dripToken];
_captureClaimForVolumeDrip(referralState, source, measure, dripToken, true, user, amount);
}
}
function _captureClaimForVolumeDrip(
VolumeDrip.State storage dripState,
address source,
address measure,
address dripToken,
bool isReferral,
address user,
uint256 amount
) internal {
uint256 newUserTokens = dripState.mint(
user,
amount
);
if (newUserTokens > 0) {
_addDripBalance(dripToken, user, newUserTokens);
emit VolumeDripDripped(source, measure, dripToken, isReferral, user, newUserTokens);
}
}
/// @param pairs The (source, measure) pairs to update. For each pair all of the balance drips, volume drips, and referral volume drips will be updated.
/// @param user The user whose drips and balances will be updated.
/// @param dripTokens The drip tokens to retrieve claim balances for.
function captureClaimsForBalanceDripsForPairs(
UpdatePair[] memory pairs,
address user,
address[] memory dripTokens
)
public
{
uint256 i;
for (i = 0; i < pairs.length; i++) {
UpdatePair memory pair = pairs[i];
uint256 measureBalance = IERC20Upgradeable(pair.measure).balanceOf(user);
_captureClaimsForBalanceDrips(pair.source, pair.measure, user, measureBalance, dripTokens);
}
}
function _captureClaimsForBalanceDrips(
address source,
address measure,
address user,
uint256 userMeasureBalance,
address[] memory dripTokens
) internal {
uint i;
for (i = 0; i < dripTokens.length; i++) {
address dripToken = dripTokens[i];
BalanceDrip.State storage state = balanceDrips[source].balanceDrips[measure][dripToken];
if (state.exchangeRateMantissa > 0) {
_captureClaimForBalanceDrip(state, source, measure, dripToken, user, userMeasureBalance);
}
}
}
function _captureClaimForBalanceDrip(
BalanceDrip.State storage dripState,
address source,
address measure,
address dripToken,
address user,
uint256 measureBalance
) internal {
uint256 newUserTokens = dripState.captureNewTokensForUser(
user,
measureBalance
);
if (newUserTokens > 0) {
_addDripBalance(dripToken, user, newUserTokens);
emit BalanceDripDripped(source, measure, dripToken, user, newUserTokens);
}
}
function balanceOfClaims(
address user,
address[] memory dripTokens
) public view returns (DripTokenBalance[] memory) {
DripTokenBalance[] memory balances = new DripTokenBalance[](dripTokens.length);
uint256 i;
for (i = 0; i < dripTokens.length; i++) {
balances[i] = DripTokenBalance({
dripToken: dripTokens[i],
balance: dripTokenBalances[dripTokens[i]][user]
});
}
return balances;
}
/// @notice Updates the given drips for a user and then claims the given drip tokens. This call will
/// poke all of the drips and update the claim balances for the given user.
/// @dev This function will be useful to check the *current* claim balances for a user.
/// Just need to run this as a constant function to see the latest balances.
/// in order to claim the values, this function needs to be run alongside a claimDrip function.
/// @param pairs The (source, measure) pairs of drips to update for the given user
/// @param user The user for whom to update and claim tokens
/// @param dripTokens The drip tokens whose entire balance will be claimed after the update.
/// @return The claimable balance of each of the passed drip tokens for the user. These are the post-update balances, and therefore the most accurate.
function updateDrips(
UpdatePair[] memory pairs,
address user,
address[] memory dripTokens
)
public returns (DripTokenBalance[] memory)
{
updateActiveBalanceDripsForPairs(pairs);
captureClaimsForBalanceDripsForPairs(pairs, user, dripTokens);
updateActiveVolumeDripsForPairs(pairs);
mintAndCaptureVolumeDripsForPairs(pairs, user, 0, dripTokens);
DripTokenBalance[] memory balances = balanceOfClaims(user, dripTokens);
return balances;
}
/// @notice Updates the given drips for a user and then claims the given drip tokens. This call will
/// poke all of the drips and update the claim balances for the given user.
/// @dev This function will be useful to check the *current* claim balances for a user.
/// Just need to run this as a constant function to see the latest balances.
/// in order to claim the values, this function needs to be run alongside a claimDrip function.
/// @param pairs The (source, measure) pairs of drips to update for the given user
/// @param user The user for whom to update and claim tokens
/// @param dripTokens The drip tokens whose entire balance will be claimed after the update.
/// @return The claimable balance of each of the passed drip tokens for the user. These are the post-update balances, and therefore the most accurate.
function updateAndClaimDrips(
UpdatePair[] calldata pairs,
address user,
address[] calldata dripTokens
)
external returns (DripTokenBalance[] memory)
{
DripTokenBalance[] memory balances = updateDrips(pairs, user, dripTokens);
claimDrips(user, dripTokens);
return balances;
}
function _activeBalanceDripTokens(address source, address measure) internal view returns (address[] memory) {
return balanceDrips[source].activeBalanceDrips[measure].addressArray();
}
function _activeVolumeDripTokens(address source, address measure) internal view returns (address[] memory) {
return volumeDrips[source].activeVolumeDrips[measure].addressArray();
}
function _activeReferralVolumeDripTokens(address source, address measure) internal view returns (address[] memory) {
return referralVolumeDrips[source].activeVolumeDrips[measure].addressArray();
}
/// @notice Updates the balance drips
/// @param source The Prize Pool of the balance drip
/// @param manager The BalanceDripManager whose drips should be updated
/// @param measure The measure token whose balance is changing
/// @param measureTotalSupply The last total supply of the measure tokens
/// @param currentTime The current
function _updateActiveBalanceDrips(
BalanceDripManager.State storage manager,
address source,
address measure,
uint256 measureTotalSupply,
uint256 currentTime
) internal {
address prevDripToken = manager.activeBalanceDrips[measure].end();
address currentDripToken = manager.activeBalanceDrips[measure].start();
while (currentDripToken != address(0) && currentDripToken != manager.activeBalanceDrips[measure].end()) {
BalanceDrip.State storage dripState = manager.balanceDrips[measure][currentDripToken];
uint256 limit = _availableDripTokenBalance(currentDripToken);
uint256 newTokens = dripState.drip(
measureTotalSupply,
currentTime,
limit
);
// if we've hit the limit, then kill it.
bool isDripComplete = newTokens == limit;
if (isDripComplete) {
_deactivateBalanceDrip(source, measure, currentDripToken, prevDripToken);
}
prevDripToken = currentDripToken;
currentDripToken = manager.activeBalanceDrips[measure].next(currentDripToken);
}
}
/// @notice Records a deposit for a volume drip
/// @param source The Prize Pool of the volume drip
/// @param manager The VolumeDripManager containing the drips that need to be iterated through.
/// @param isReferral Whether the passed manager contains referral volume drip
/// @param measure The token that was deposited
function _updateActiveVolumeDrips(
VolumeDripManager.State storage manager,
address source,
address measure,
bool isReferral
)
internal
{
address prevDripToken = manager.activeVolumeDrips[measure].end();
uint256 currentTime = _currentTime();
address currentDripToken = manager.activeVolumeDrips[measure].start();
while (currentDripToken != address(0) && currentDripToken != manager.activeVolumeDrips[measure].end()) {
VolumeDrip.State storage dripState = manager.volumeDrips[measure][currentDripToken];
uint256 limit = _availableDripTokenBalance(currentDripToken);
uint32 lastPeriod = dripState.periodCount;
uint256 newTokens = dripState.drip(
currentTime,
limit
);
if (lastPeriod != dripState.periodCount) {
emit VolumeDripPeriodEnded(
source,
measure,
currentDripToken,
isReferral,
lastPeriod,
dripState.periods[lastPeriod].totalSupply,
newTokens
);
emit VolumeDripPeriodStarted(
source,
measure,
currentDripToken,
isReferral,
dripState.periodCount,
dripState.periods[dripState.periodCount].dripAmount,
dripState.periods[dripState.periodCount].endTime
);
}
// if we've hit the limit, then kill it.
bool isDripComplete = newTokens == limit;
if (isDripComplete) {
_deactivateVolumeDrip(source, measure, currentDripToken, isReferral, prevDripToken);
}
prevDripToken = currentDripToken;
currentDripToken = manager.activeVolumeDrips[measure].next(currentDripToken);
}
}
function _addDripBalance(address dripToken, address user, uint256 amount) internal returns (uint256) {
uint256 amountAvailable = _availableDripTokenBalance(dripToken);
uint256 actualAmount = (amount > amountAvailable) ? amountAvailable : amount;
dripTokenTotalSupply[dripToken] = dripTokenTotalSupply[dripToken].add(actualAmount);
dripTokenBalances[dripToken][user] = dripTokenBalances[dripToken][user].add(actualAmount);
emit DripTokenDripped(dripToken, user, actualAmount);
return actualAmount;
}
function _availableDripTokenBalance(address dripToken) internal view returns (uint256) {
uint256 comptrollerBalance = IERC20Upgradeable(dripToken).balanceOf(address(this));
uint256 totalClaimable = dripTokenTotalSupply[dripToken];
return (totalClaimable < comptrollerBalance) ? comptrollerBalance.sub(totalClaimable) : 0;
}
/// @notice Called by a "source" (i.e. Prize Pool) when a user mints new "measure" tokens.
/// @param to The user who is minting the tokens
/// @param amount The amount of tokens they are minting
/// @param measure The measure token they are minting
/// @param referrer The user who referred the minting.
function beforeTokenMint(
address to,
uint256 amount,
address measure,
address referrer
)
external
override
{
address source = _msgSender();
uint256 balance = IERC20Upgradeable(measure).balanceOf(to);
uint256 totalSupply = IERC20Upgradeable(measure).totalSupply();
address[] memory balanceDripTokens = _activeBalanceDripTokens(source, measure);
_updateActiveBalanceDrips(
balanceDrips[source],
source,
measure,
totalSupply,
_currentTime()
);
_captureClaimsForBalanceDrips(source, measure, to, balance, balanceDripTokens);
address[] memory volumeDripTokens = _activeVolumeDripTokens(source, measure);
_updateActiveVolumeDrips(
volumeDrips[source],
source,
measure,
false
);
_mintAndCaptureForVolumeDrips(source, measure, to, amount, volumeDripTokens);
if (referrer != address(0)) {
address[] memory referralVolumeDripTokens = _activeReferralVolumeDripTokens(source, measure);
_updateActiveVolumeDrips(
referralVolumeDrips[source],
source,
measure,
true
);
_mintAndCaptureReferralVolumeDrips(source, measure, referrer, amount, referralVolumeDripTokens);
}
}
/// @notice Called by a "source" (i.e. Prize Pool) when tokens change hands or are burned
/// @param from The user who is sending the tokens
/// @param to The user who is receiving the tokens
/// @param measure The measure token they are burning
function beforeTokenTransfer(
address from,
address to,
uint256,
address measure
)
external
override
{
if (from == address(0)) {
// ignore minting
return;
}
address source = _msgSender();
uint256 totalSupply = IERC20Upgradeable(measure).totalSupply();
uint256 fromBalance = IERC20Upgradeable(measure).balanceOf(from);
address[] memory balanceDripTokens = _activeBalanceDripTokens(source, measure);
_updateActiveBalanceDrips(
balanceDrips[source],
source,
measure,
totalSupply,
_currentTime()
);
_captureClaimsForBalanceDrips(source, measure, from, fromBalance, balanceDripTokens);
if (to != address(0)) {
uint256 toBalance = IERC20Upgradeable(measure).balanceOf(to);
_captureClaimsForBalanceDrips(source, measure, to, toBalance, balanceDripTokens);
}
}
/// @notice returns the current time. Allows for override in testing.
/// @return The current time (block.timestamp)
function _currentTime() internal virtual view returns (uint256) {
return block.timestamp;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
library UInt256Array {
function remove(uint256[] storage self, uint256 index) internal {
require(index < self.length, "UInt256Array/unknown-index");
self[index] = self[self.length-1];
delete self[self.length-1];
self.pop();
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../drip/BalanceDripManager.sol";
import "../drip/VolumeDripManager.sol";
contract ComptrollerStorage is OwnableUpgradeable {
mapping(address => VolumeDripManager.State) internal volumeDrips;
mapping(address => VolumeDripManager.State) internal referralVolumeDrips;
mapping(address => BalanceDripManager.State) internal balanceDrips;
mapping(address => uint256) internal dripTokenTotalSupply;
mapping(address => mapping(address => uint256)) internal dripTokenBalances;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../utils/MappedSinglyLinkedList.sol";
import "./BalanceDrip.sol";
/// @title Manages the lifecycle of a set of Balance Drips.
library BalanceDripManager {
using SafeMathUpgradeable for uint256;
using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping;
using BalanceDrip for BalanceDrip.State;
struct State {
mapping(address => MappedSinglyLinkedList.Mapping) activeBalanceDrips;
mapping(address => mapping(address => BalanceDrip.State)) balanceDrips;
}
/// @notice Activates a drip by setting it's state and adding it to the active balance drips list.
/// @param self The BalanceDripManager state
/// @param measure The measure token
/// @param dripToken The drip token
/// @param dripRatePerSecond The amount of the drip token to be dripped per second
function activateDrip(
State storage self,
address measure,
address dripToken,
uint256 dripRatePerSecond
)
internal
{
require(!self.activeBalanceDrips[measure].contains(dripToken), "BalanceDripManager/drip-active");
if (self.activeBalanceDrips[measure].count == 0) {
self.activeBalanceDrips[measure].initialize();
}
self.activeBalanceDrips[measure].addAddress(dripToken);
self.balanceDrips[measure][dripToken].resetTotalDripped();
self.balanceDrips[measure][dripToken].dripRatePerSecond = dripRatePerSecond;
}
/// @notice Deactivates an active balance drip. The balance drip is removed from the active balance drips list.
/// The drip rate for the balance drip will be set to zero to ensure it's "frozen".
/// @param measure The measure token
/// @param dripToken The drip token
/// @param prevDripToken The previous drip token previous in the list.
/// If no previous, then pass the SENTINEL address: 0x0000000000000000000000000000000000000001
/// @param currentTime The current time
function deactivateDrip(
State storage self,
address measure,
address dripToken,
address prevDripToken,
uint32 currentTime,
uint256 maxNewTokens
)
internal
{
self.activeBalanceDrips[measure].removeAddress(prevDripToken, dripToken);
self.balanceDrips[measure][dripToken].drip(IERC20Upgradeable(measure).totalSupply(), currentTime, maxNewTokens);
self.balanceDrips[measure][dripToken].dripRatePerSecond = 0;
}
/// @notice Gets a list of active balance drip tokens
/// @param self The BalanceDripManager state
/// @param measure The measure token
/// @return An array of Balance Drip token addresses
function getActiveBalanceDrips(State storage self, address measure) internal view returns (address[] memory) {
return self.activeBalanceDrips[measure].addressArray();
}
/// @notice Sets the drip rate for an active balance drip.
/// @param self The BalanceDripManager state
/// @param measure The measure token
/// @param dripToken The drip token
/// @param dripRatePerSecond The amount to drip of the token each second
/// @param currentTime The current time.
function setDripRate(
State storage self,
address measure,
address dripToken,
uint256 dripRatePerSecond,
uint32 currentTime,
uint256 maxNewTokens
) internal {
require(self.activeBalanceDrips[measure].contains(dripToken), "BalanceDripManager/drip-not-active");
self.balanceDrips[measure][dripToken].drip(IERC20Upgradeable(measure).totalSupply(), currentTime, maxNewTokens);
self.balanceDrips[measure][dripToken].dripRatePerSecond = dripRatePerSecond;
}
/// @notice Returns whether or not a drip is active for the given measure, dripToken pair
/// @param self The BalanceDripManager state
/// @param measure The measure token
/// @param dripToken The drip token
/// @return True if there is an active balance drip for the pair, false otherwise
function isDripActive(State storage self, address measure, address dripToken) internal view returns (bool) {
return self.activeBalanceDrips[measure].contains(dripToken);
}
/// @notice Returns the BalanceDrip.State for the given measure, dripToken pair
/// @param self The BalanceDripManager state
/// @param measure The measure token
/// @param dripToken The drip token
/// @return The BalanceDrip.State for the pair
function getDrip(State storage self, address measure, address dripToken) internal view returns (BalanceDrip.State storage) {
return self.balanceDrips[measure][dripToken];
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol";
import "../utils/ExtendedSafeCast.sol";
import "@pooltogether/fixed-point/contracts/FixedPoint.sol";
/// @title Calculates a users share of a token faucet.
/// @notice The tokens are dripped at a "drip rate per second". This is the number of tokens that
/// are dripped each second to the entire supply of a "measure" token. A user's share of ownership
/// of the measure token corresponds to the share of the drip tokens per second.
library BalanceDrip {
using SafeMathUpgradeable for uint256;
using SafeCastUpgradeable for uint256;
using ExtendedSafeCast for uint256;
struct UserState {
uint128 lastExchangeRateMantissa;
}
struct State {
uint256 dripRatePerSecond;
uint112 exchangeRateMantissa;
uint112 totalDripped;
uint32 timestamp;
mapping(address => UserState) userStates;
}
/// @notice Captures new tokens for a user
/// @dev This must be called before changes to the user's balance (i.e. before mint, transfer or burns)
/// @param self The balance drip state
/// @param user The user to capture tokens for
/// @param userMeasureBalance The current balance of the user's measure tokens
/// @return The number of new tokens
function captureNewTokensForUser(
State storage self,
address user,
uint256 userMeasureBalance
) internal returns (uint128) {
return _captureNewTokensForUser(
self,
user,
userMeasureBalance
);
}
function resetTotalDripped(State storage self) internal {
self.totalDripped = 0;
}
/// @notice Drips new tokens.
/// @dev Should be called immediately before a change to the measure token's total supply
/// @param self The balance drip state
/// @param measureTotalSupply The measure token's last total supply (prior to any change)
/// @param timestamp The current time
/// @param maxNewTokens Maximum new tokens that can be dripped
/// @return The number of new tokens dripped.
function drip(
State storage self,
uint256 measureTotalSupply,
uint256 timestamp,
uint256 maxNewTokens
) internal returns (uint256) {
// this should only run once per block.
if (self.timestamp == uint32(timestamp)) {
return 0;
}
uint256 lastTime = self.timestamp == 0 ? timestamp : self.timestamp;
uint256 newSeconds = timestamp.sub(lastTime);
uint112 exchangeRateMantissa = self.exchangeRateMantissa == 0 ? FixedPoint.SCALE.toUint112() : self.exchangeRateMantissa;
uint256 newTokens;
if (newSeconds > 0 && self.dripRatePerSecond > 0) {
newTokens = newSeconds.mul(self.dripRatePerSecond);
if (newTokens > maxNewTokens) {
newTokens = maxNewTokens;
}
uint256 indexDeltaMantissa = measureTotalSupply > 0 ? FixedPoint.calculateMantissa(newTokens, measureTotalSupply) : 0;
exchangeRateMantissa = uint256(exchangeRateMantissa).add(indexDeltaMantissa).toUint112();
}
self.exchangeRateMantissa = exchangeRateMantissa;
self.totalDripped = uint256(self.totalDripped).add(newTokens).toUint112();
self.timestamp = timestamp.toUint32();
return newTokens;
}
function _captureNewTokensForUser(
State storage self,
address user,
uint256 userMeasureBalance
) private returns (uint128) {
UserState storage userState = self.userStates[user];
uint256 lastExchangeRateMantissa = userState.lastExchangeRateMantissa;
if (lastExchangeRateMantissa == 0) {
// if the index is not intialized
lastExchangeRateMantissa = FixedPoint.SCALE.toUint112();
}
uint256 deltaExchangeRateMantissa = uint256(self.exchangeRateMantissa).sub(lastExchangeRateMantissa);
uint128 newTokens = FixedPoint.multiplyUintByMantissa(userMeasureBalance, deltaExchangeRateMantissa).toUint128();
self.userStates[user] = UserState({
lastExchangeRateMantissa: self.exchangeRateMantissa
});
return newTokens;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
library ExtendedSafeCast {
/**
* @dev Converts an unsigned uint256 into a unsigned uint112.
*
* Requirements:
*
* - input must be less than or equal to maxUint112.
*/
function toUint112(uint256 value) internal pure returns (uint112) {
require(value < 2**112, "SafeCast: value doesn't fit in an uint112");
return uint112(value);
}
/**
* @dev Converts an unsigned uint256 into a unsigned uint96.
*
* Requirements:
*
* - input must be less than or equal to maxUint96.
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value < 2**96, "SafeCast: value doesn't fit in an uint96");
return uint96(value);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../utils/MappedSinglyLinkedList.sol";
import "./VolumeDrip.sol";
/// @title Manages the active set of Volume Drips.
library VolumeDripManager {
using SafeMathUpgradeable for uint256;
using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping;
using VolumeDrip for VolumeDrip.State;
struct State {
mapping(address => MappedSinglyLinkedList.Mapping) activeVolumeDrips;
mapping(address => mapping(address => VolumeDrip.State)) volumeDrips;
}
/// @notice Activates a volume drip for the given (measure,dripToken) pair.
/// @param self The VolumeDripManager state
/// @param measure The measure token
/// @param dripToken The drip token
/// @param periodSeconds The period of the volume drip in seconds
/// @param dripAmount The amount of tokens to drip each period
/// @param endTime The end time to set for the current period.
function activate(
State storage self,
address measure,
address dripToken,
uint32 periodSeconds,
uint112 dripAmount,
uint32 endTime
)
internal
returns (uint32)
{
require(!self.activeVolumeDrips[measure].contains(dripToken), "VolumeDripManager/drip-active");
if (self.activeVolumeDrips[measure].count == 0) {
self.activeVolumeDrips[measure].initialize();
}
self.activeVolumeDrips[measure].addAddress(dripToken);
self.volumeDrips[measure][dripToken].setNewPeriod(periodSeconds, dripAmount, endTime);
return self.volumeDrips[measure][dripToken].periodCount;
}
/// @notice Deactivates the volume drip for the given (measure, dripToken) pair.
/// @param self The VolumeDripManager state
/// @param measure The measure token
/// @param dripToken The drip token
/// @param prevDripToken The active drip token previous to the passed on in the list.
function deactivate(
State storage self,
address measure,
address dripToken,
address prevDripToken
)
internal
{
self.activeVolumeDrips[measure].removeAddress(prevDripToken, dripToken);
}
/// @notice Gets a list of active balance drip tokens
/// @param self The BalanceDripManager state
/// @param measure The measure token
/// @return An array of Balance Drip token addresses
function getActiveVolumeDrips(State storage self, address measure) internal view returns (address[] memory) {
return self.activeVolumeDrips[measure].addressArray();
}
/// @notice Sets the parameters for the next period of an active volume drip
/// @param self The VolumeDripManager state
/// @param measure The measure token
/// @param dripToken The drip token
/// @param periodSeconds The length in seconds to use for the next period
/// @param dripAmount The amount of tokens to be dripped in the next period
function set(State storage self, address measure, address dripToken, uint32 periodSeconds, uint112 dripAmount) internal {
require(self.activeVolumeDrips[measure].contains(dripToken), "VolumeDripManager/drip-not-active");
self.volumeDrips[measure][dripToken].setNextPeriod(periodSeconds, dripAmount);
}
/// @notice Returns whether or not an active volume drip exists for the given (measure, dripToken) pair
/// @param self The VolumeDripManager state
/// @param measure The measure token
/// @param dripToken The drip token
function isActive(State storage self, address measure, address dripToken) internal view returns (bool) {
return self.activeVolumeDrips[measure].contains(dripToken);
}
/// @notice Returns the VolumeDrip.State for the given (measure, dripToken) pair.
/// @param self The VolumeDripManager state
/// @param measure The measure token
/// @param dripToken The drip token
function getDrip(State storage self, address measure, address dripToken) internal view returns (VolumeDrip.State storage) {
return self.volumeDrips[measure][dripToken];
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol";
import "@pooltogether/fixed-point/contracts/FixedPoint.sol";
import "../utils/ExtendedSafeCast.sol";
library VolumeDrip {
using SafeMathUpgradeable for uint256;
using SafeCastUpgradeable for uint256;
using ExtendedSafeCast for uint256;
struct Deposit {
uint112 balance;
uint32 period;
}
struct Period {
uint112 totalSupply;
uint112 dripAmount;
uint32 endTime;
}
struct State {
mapping(address => Deposit) deposits;
mapping(uint32 => Period) periods;
uint32 nextPeriodSeconds;
uint112 nextDripAmount;
uint112 __gap;
uint112 totalDripped;
uint32 periodCount;
}
function setNewPeriod(
State storage self,
uint32 _periodSeconds,
uint112 dripAmount,
uint32 endTime
)
internal
minPeriod(_periodSeconds)
{
self.nextPeriodSeconds = _periodSeconds;
self.nextDripAmount = dripAmount;
self.totalDripped = 0;
self.periodCount = uint256(self.periodCount).add(1).toUint16();
self.periods[self.periodCount] = Period({
totalSupply: 0,
dripAmount: dripAmount,
endTime: endTime
});
}
function setNextPeriod(
State storage self,
uint32 _periodSeconds,
uint112 dripAmount
)
internal
minPeriod(_periodSeconds)
{
self.nextPeriodSeconds = _periodSeconds;
self.nextDripAmount = dripAmount;
}
function drip(
State storage self,
uint256 currentTime,
uint256 maxNewTokens
)
internal
returns (uint256)
{
if (_isPeriodOver(self, currentTime)) {
return _completePeriod(self, currentTime, maxNewTokens);
}
return 0;
}
function mint(
State storage self,
address user,
uint256 amount
)
internal
returns (uint256)
{
if (self.periodCount == 0) {
return 0;
}
uint256 accrued = _lastBalanceAccruedAmount(self, self.deposits[user].period, self.deposits[user].balance);
uint32 currentPeriod = self.periodCount;
if (accrued > 0) {
self.deposits[user] = Deposit({
balance: amount.toUint112(),
period: currentPeriod
});
} else {
self.deposits[user] = Deposit({
balance: uint256(self.deposits[user].balance).add(amount).toUint112(),
period: currentPeriod
});
}
self.periods[currentPeriod].totalSupply = uint256(self.periods[currentPeriod].totalSupply).add(amount).toUint112();
return accrued;
}
function currentPeriod(State storage self) internal view returns (Period memory) {
return self.periods[self.periodCount];
}
function _isPeriodOver(State storage self, uint256 currentTime) private view returns (bool) {
return currentTime >= self.periods[self.periodCount].endTime;
}
function _completePeriod(
State storage self,
uint256 currentTime,
uint256 maxNewTokens
) private onlyPeriodOver(self, currentTime) returns (uint256) {
// calculate the actual drip amount
uint112 dripAmount;
// If no one deposited, then don't drip anything
if (self.periods[self.periodCount].totalSupply > 0) {
dripAmount = self.periods[self.periodCount].dripAmount;
}
// if the drip amount is not valid, it has to be updated.
if (dripAmount > maxNewTokens) {
dripAmount = maxNewTokens.toUint112();
self.periods[self.periodCount].dripAmount = dripAmount;
}
// if we are completing the period far into the future, then we'll have skipped a lot of periods.
// Here we set the end time so that it's the next period from *now*
uint256 lastEndTime = self.periods[self.periodCount].endTime;
uint256 numberOfPeriods = currentTime.sub(lastEndTime).div(self.nextPeriodSeconds).add(1);
uint256 endTime = lastEndTime.add(numberOfPeriods.mul(self.nextPeriodSeconds));
self.totalDripped = uint256(self.totalDripped).add(dripAmount).toUint112();
self.periodCount = uint256(self.periodCount).add(1).toUint16();
self.periods[self.periodCount] = Period({
totalSupply: 0,
dripAmount: self.nextDripAmount,
endTime: endTime.toUint32()
});
return dripAmount;
}
function _lastBalanceAccruedAmount(
State storage self,
uint32 depositPeriod,
uint128 balance
)
private view
returns (uint256)
{
uint256 accrued;
if (depositPeriod < self.periodCount && self.periods[depositPeriod].totalSupply > 0) {
uint256 fractionMantissa = FixedPoint.calculateMantissa(balance, self.periods[depositPeriod].totalSupply);
accrued = FixedPoint.multiplyUintByMantissa(self.periods[depositPeriod].dripAmount, fractionMantissa);
}
return accrued;
}
modifier onlyPeriodNotOver(State storage self, uint256 _currentTime) {
require(!_isPeriodOver(self, _currentTime), "VolumeDrip/period-over");
_;
}
modifier onlyPeriodOver(State storage self, uint256 _currentTime) {
require(_isPeriodOver(self, _currentTime), "VolumeDrip/period-not-over");
_;
}
modifier minPeriod(uint256 _periodSeconds) {
require(_periodSeconds > 0, "VolumeDrip/period-gt-zero");
_;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface DaiInterface is IERC20Upgradeable {
// --- Approve by signature ---
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
function transferFrom(address src, address dst, uint wad) external override returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../external/maker/DaiInterface.sol";
import "../prize-pool/PrizePoolInterface.sol";
/// @title Allows users to approve and deposit dai into a prize pool in a single transaction.
contract PermitAndDepositDai is OwnableUpgradeable {
using SafeERC20Upgradeable for DaiInterface;
/// @notice Permits this contract to spend on a users behalf, and deposits into the prize pool.
/// @dev The Dai permit params match the Dai#permit function, but it expects the `spender` to be
/// the address of this contract.
/// @param holder The address spending the tokens
/// @param nonce The nonce of the tx. Should be retrieved from the Dai token
/// @param expiry The timestamp at which the sig expires
/// @param allowed If true, then the spender is approving holder the max allowance. False makes the allowance zero.
/// @param v The `v` portion of the signature.
/// @param r The `r` portion of the signature.
/// @param s The `s` portion of the signature.
/// @param prizePool The prize pool to deposit into
/// @param to The address that will receive the controlled tokens
/// @param amount The amount to deposit
/// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship)
/// @param referrer The address that referred the deposit
function permitAndDepositTo(
// --- Approve by signature ---
address dai, address holder, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s,
address prizePool, address to, uint256 amount, address controlledToken, address referrer
) external {
require(msg.sender == holder, "PermitAndDepositDai/only-signer");
DaiInterface(dai).permit(holder, address(this), nonce, expiry, allowed, v, r, s);
_depositTo(dai, holder, prizePool, to, amount, controlledToken, referrer);
}
/// @notice Deposits into a Prize Pool from the sender. Tokens will be transferred from the sender
/// then deposited into the Pool on the sender's behalf. This can be called after permitAndDepositTo is called,
/// as this contract will have full approval for a user.
/// @param prizePool The prize pool to deposit into
/// @param to The address that will receive the controlled tokens
/// @param amount The amount to deposit
/// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship)
/// @param referrer The address that referred the deposit
function depositTo(
address dai,
address prizePool,
address to,
uint256 amount,
address controlledToken,
address referrer
) external {
_depositTo(dai, msg.sender, prizePool, to, amount, controlledToken, referrer);
}
function _depositTo(
address dai,
address holder,
address prizePool,
address to,
uint256 amount,
address controlledToken,
address referrer
) internal {
DaiInterface(dai).safeTransferFrom(holder, address(this), amount);
DaiInterface(dai).approve(address(prizePool), amount);
PrizePoolInterface(prizePool).depositTo(to, amount, controlledToken, referrer);
}
}
pragma solidity ^0.6.12;
import "./PeriodicPrizeStrategyListenerInterface.sol";
import "./PeriodicPrizeStrategyListenerLibrary.sol";
import "../Constants.sol";
abstract contract PeriodicPrizeStrategyListener is PeriodicPrizeStrategyListenerInterface {
function supportsInterface(bytes4 interfaceId) external override view returns (bool) {
return (
interfaceId == Constants.ERC165_INTERFACE_ID_ERC165 ||
interfaceId == PeriodicPrizeStrategyListenerLibrary.ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER
);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "../PeriodicPrizeStrategy.sol";
/* solium-disable security/no-block-members */
contract SingleRandomWinner is PeriodicPrizeStrategy {
event NoWinner();
function _distribute(uint256 randomNumber) internal override {
uint256 prize = prizePool.captureAwardBalance();
address winner = ticket.draw(randomNumber);
if (winner != address(0)) {
_awardTickets(winner, prize);
_awardAllExternalTokens(winner);
} else {
emit NoWinner();
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "./SingleRandomWinner.sol";
import "../../external/openzeppelin/ProxyFactory.sol";
contract SingleRandomWinnerProxyFactory is ProxyFactory {
SingleRandomWinner public instance;
constructor () public {
instance = new SingleRandomWinner();
}
function create() external returns (SingleRandomWinner) {
return SingleRandomWinner(deployMinimal(address(instance), ""));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./RegistryInterface.sol";
/// @title Interface that allows a user to draw an address using an index
contract Registry is OwnableUpgradeable, RegistryInterface {
address private pointer;
event Registered(address indexed pointer);
constructor () public {
__Ownable_init();
}
function register(address _pointer) external onlyOwner {
pointer = _pointer;
emit Registered(pointer);
}
function lookup() external override view returns (address) {
return pointer;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./ReserveInterface.sol";
import "../prize-pool/PrizePoolInterface.sol";
/// @title Interface that allows a user to draw an address using an index
contract Reserve is OwnableUpgradeable, ReserveInterface {
event ReserveRateMantissaSet(uint256 rateMantissa);
uint256 public rateMantissa;
constructor () public {
__Ownable_init();
}
function setRateMantissa(
uint256 _rateMantissa
)
external
onlyOwner
{
rateMantissa = _rateMantissa;
emit ReserveRateMantissaSet(rateMantissa);
}
function withdrawReserve(address prizePool, address to) external onlyOwner returns (uint256) {
return PrizePoolInterface(prizePool).withdrawReserve(to);
}
function reserveRateMantissa(address) external view override returns (uint256) {
return rateMantissa;
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../drip/BalanceDrip.sol";
contract BalanceDripExposed {
using BalanceDrip for BalanceDrip.State;
event DrippedTotalSupply(
uint256 newTokens
);
event Dripped(
address indexed user,
uint256 newTokens
);
BalanceDrip.State internal dripState;
function setDripRate(
uint256 dripRatePerSecond
) external {
dripState.dripRatePerSecond = dripRatePerSecond;
}
function drip(
uint256 measureTotalSupply,
uint256 currentTime,
uint256 maxNewTokens
) external returns (uint256) {
uint256 newTokens = dripState.drip(
measureTotalSupply,
currentTime,
maxNewTokens
);
emit DrippedTotalSupply(newTokens);
return newTokens;
}
function captureNewTokensForUser(
address user,
uint256 userMeasureBalance
) external returns (uint128) {
uint128 newTokens = dripState.captureNewTokensForUser(
user,
userMeasureBalance
);
emit Dripped(user, newTokens);
return newTokens;
}
function dripTwice(
uint256 measureTotalSupply,
uint256 currentTime,
uint256 maxNewTokens
) external returns (uint256) {
uint256 newTokens = dripState.drip(
measureTotalSupply,
currentTime,
maxNewTokens
);
newTokens = newTokens + dripState.drip(
measureTotalSupply,
currentTime,
maxNewTokens
);
emit DrippedTotalSupply(newTokens);
return newTokens;
}
function exchangeRateMantissa() external view returns (uint256) {
return dripState.exchangeRateMantissa;
}
function totalDripped() external view returns (uint256) {
return dripState.totalDripped;
}
function resetTotalDripped() external {
dripState.resetTotalDripped();
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../drip/BalanceDripManager.sol";
contract BalanceDripManagerExposed {
using BalanceDripManager for BalanceDripManager.State;
BalanceDripManager.State dripManager;
function activateDrip(address measure, address dripToken, uint256 dripRatePerSecond) external {
dripManager.activateDrip(measure, dripToken, dripRatePerSecond);
}
function deactivateDrip(address measure, address prevDripToken, address dripToken, uint32 currentTime, uint256 maxNewTokens) external {
dripManager.deactivateDrip(measure, prevDripToken, dripToken, currentTime, maxNewTokens);
}
function isDripActive(address measure, address dripToken) external view returns (bool) {
return dripManager.isDripActive(measure, dripToken);
}
function setDripRate(address measure, address dripToken, uint256 dripRatePerSecond, uint32 currentTime, uint256 maxNewTokens) external {
dripManager.setDripRate(measure, dripToken, dripRatePerSecond, currentTime, maxNewTokens);
}
function getActiveBalanceDrips(address measure) external view returns (address[] memory) {
return dripManager.getActiveBalanceDrips(measure);
}
function getDrip(
address measure,
address dripToken
)
external
view
returns (
uint256 dripRatePerSecond,
uint128 exchangeRateMantissa,
uint32 timestamp
)
{
BalanceDrip.State storage dripState = dripManager.getDrip(measure, dripToken);
dripRatePerSecond = dripState.dripRatePerSecond;
exchangeRateMantissa = dripState.exchangeRateMantissa;
timestamp = dripState.timestamp;
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../prize-pool/compound/CompoundPrizePool.sol";
/* solium-disable security/no-block-members */
contract CompoundPrizePoolHarness is CompoundPrizePool {
uint256 public currentTime;
function setCurrentTime(uint256 _currentTime) external {
currentTime = _currentTime;
}
function setTimelockBalance(uint256 _timelockBalance) external {
timelockTotalSupply = _timelockBalance;
}
function _currentTime() internal override view returns (uint256) {
return currentTime;
}
function supply(uint256 mintAmount) external {
_supply(mintAmount);
}
function redeem(uint256 redeemAmount) external returns (uint256) {
return _redeem(redeemAmount);
}
}
pragma solidity >=0.6.0 <0.7.0;
import "./CompoundPrizePoolHarness.sol";
import "../external/openzeppelin/ProxyFactory.sol";
/// @title Compound Prize Pool Proxy Factory
/// @notice Minimal proxy pattern for creating new Compound Prize Pools
contract CompoundPrizePoolHarnessProxyFactory is ProxyFactory {
/// @notice Contract template for deploying proxied Prize Pools
CompoundPrizePoolHarness public instance;
/// @notice Initializes the Factory with an instance of the Compound Prize Pool
constructor () public {
instance = new CompoundPrizePoolHarness();
}
/// @notice Creates a new Compound Prize Pool as a proxy of the template instance
/// @return A reference to the new proxied Compound Prize Pool
function create() external returns (CompoundPrizePoolHarness) {
return CompoundPrizePoolHarness(deployMinimal(address(instance), ""));
}
}
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "../comptroller/Comptroller.sol";
/* solium-disable security/no-block-members */
contract ComptrollerHarness is Comptroller {
uint256 internal time;
function setCurrentTime(uint256 _time) external {
time = _time;
}
function _currentTime() internal override view returns (uint256) {
return time;
}
}
/**
Copyright 2019 PoolTogether LLC
This file is part of PoolTogether.
PoolTogether 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 under version 3 of the License.
PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@pooltogether/fixed-point/contracts/FixedPoint.sol";
import "./ERC20Mintable.sol";
contract CTokenMock is ERC20Upgradeable {
mapping(address => uint256) internal ownerTokenAmounts;
ERC20Mintable public underlying;
uint256 internal __supplyRatePerBlock;
constructor (
ERC20Mintable _token,
uint256 _supplyRatePerBlock
) public {
require(address(_token) != address(0), "token is not defined");
underlying = _token;
__supplyRatePerBlock = _supplyRatePerBlock;
}
function mint(uint256 amount) external returns (uint) {
uint256 newCTokens;
if (totalSupply() == 0) {
newCTokens = amount;
} else {
// they need to hold the same assets as tokens.
// Need to calculate the current exchange rate
uint256 fractionOfCredit = FixedPoint.calculateMantissa(amount, underlying.balanceOf(address(this)));
newCTokens = FixedPoint.multiplyUintByMantissa(totalSupply(), fractionOfCredit);
}
_mint(msg.sender, newCTokens);
require(underlying.transferFrom(msg.sender, address(this), amount), "could not transfer tokens");
return 0;
}
function getCash() external view returns (uint) {
return underlying.balanceOf(address(this));
}
function redeemUnderlying(uint256 requestedAmount) external returns (uint) {
uint256 cTokens = cTokenValueOf(requestedAmount);
_burn(msg.sender, cTokens);
require(underlying.transfer(msg.sender, requestedAmount), "could not transfer tokens");
}
function accrue() external {
uint256 newTokens = (underlying.balanceOf(address(this)) * 120) / 100;
underlying.mint(address(this), newTokens);
}
function accrueCustom(uint256 amount) external {
underlying.mint(address(this), amount);
}
function burn(uint256 amount) external {
underlying.burn(address(this), amount);
}
function cTokenValueOf(uint256 tokens) public view returns (uint256) {
return FixedPoint.divideUintByMantissa(tokens, exchangeRateCurrent());
}
function balanceOfUnderlying(address account) public view returns (uint) {
return FixedPoint.multiplyUintByMantissa(balanceOf(account), exchangeRateCurrent());
}
function exchangeRateCurrent() public view returns (uint256) {
if (totalSupply() == 0) {
return FixedPoint.SCALE;
} else {
return FixedPoint.calculateMantissa(underlying.balanceOf(address(this)), totalSupply());
}
}
function supplyRatePerBlock() external view returns (uint) {
return __supplyRatePerBlock;
}
function setSupplyRateMantissa(uint256 _supplyRatePerBlock) external {
__supplyRatePerBlock = _supplyRatePerBlock;
}
}
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20Upgradeable {
constructor(string memory _name, string memory _symbol) public {
__ERC20_init(_name, _symbol);
}
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public returns (bool) {
_mint(account, amount);
return true;
}
function burn(address account, uint256 amount) public returns (bool) {
_burn(account, amount);
return true;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "../external/maker/DaiInterface.sol";
contract Dai is DaiInterface {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (uint256 chainId_) public {
string memory version = "1";
_name = "Dai Stablecoin";
_symbol = "DAI";
_decimals = 18;
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 name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, 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(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
mapping (address => uint) public nonces;
// --- EIP712 niceties ---
bytes32 public DOMAIN_SEPARATOR;
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
// --- Approve by signature ---
function permit(
address holder, address spender, uint256 nonce, uint256 expiry,
bool allowed, uint8 v, bytes32 r, bytes32 s) external override
{
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
holder,
spender,
nonce,
expiry,
allowed
)
)
)
);
require(holder != address(0), "Dai/invalid-address-0");
require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit");
require(expiry == 0 || now <= expiry, "Dai/permit-expired");
require(nonce == nonces[holder]++, "Dai/invalid-nonce");
uint wad = allowed ? uint(-1) : 0;
_allowances[holder][spender] = wad;
emit Approval(holder, spender, wad);
}
function mint(address to, uint256 amount) external {
_mint(to, amount);
}
}
pragma solidity >=0.6.0 <0.7.0;
/* solium-disable security/no-inline-assembly */
contract DoppelgangerWithExec {
struct MockCall {
bool initialized;
bool reverts;
bytes returnValue;
}
mapping(bytes32 => MockCall) mockConfig;
fallback() external payable {
MockCall storage mockCall = __internal__getMockCall();
if (mockCall.reverts == true) {
__internal__mockRevert();
return;
}
__internal__mockReturn(mockCall.returnValue);
}
function __waffle__mockReverts(bytes memory data) public {
mockConfig[keccak256(data)] = MockCall({
initialized: true,
reverts: true,
returnValue: ""
});
}
function __waffle__mockReturns(bytes memory data, bytes memory value) public {
mockConfig[keccak256(data)] = MockCall({
initialized: true,
reverts: false,
returnValue: value
});
}
function __waffle__call(address target, bytes calldata data) external returns (bytes memory) {
(bool succeeded, bytes memory returnValue) = target.call(data);
require(succeeded, string(returnValue));
return returnValue;
}
function __waffle__staticcall(address target, bytes calldata data) external view returns (bytes memory) {
(bool succeeded, bytes memory returnValue) = target.staticcall(data);
require(succeeded, string(returnValue));
return returnValue;
}
function __internal__getMockCall() view private returns (MockCall storage mockCall) {
mockCall = mockConfig[keccak256(msg.data)];
if (mockCall.initialized == true) {
// Mock method with specified arguments
return mockCall;
}
mockCall = mockConfig[keccak256(abi.encodePacked(msg.sig))];
if (mockCall.initialized == true) {
// Mock method with any arguments
return mockCall;
}
revert("Mock on the method is not initialized");
}
function __internal__mockReturn(bytes memory ret) pure private {
assembly {
return (add(ret, 0x20), mload(ret))
}
}
function __internal__mockRevert() pure private {
revert("Mock revert");
}
}
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/introspection/IERC1820ImplementerUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC777/IERC777RecipientUpgradeable.sol";
import "../Constants.sol";
contract ERC1820ImplementerMock is IERC1820ImplementerUpgradeable, IERC777RecipientUpgradeable {
constructor () public {
Constants.REGISTRY.setInterfaceImplementer(address(this), Constants.TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
function canImplementInterfaceForAddress(bytes32, address) external view virtual override returns(bytes32) {
return Constants.ACCEPT_MAGIC;
}
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external override {
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface for an ERC1820 implementer, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP].
* Used by contracts that will be registered as implementers in the
* {IERC1820Registry}.
*/
interface IERC1820ImplementerUpgradeable {
/**
* @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract
* implements `interfaceHash` for `account`.
*
* See {IERC1820Registry-setInterfaceImplementer}.
*/
function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777RecipientUpgradeable {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
/**
* @dev Extension of {ERC721} for Minting/Burning
*/
contract ERC721Mintable is ERC721Upgradeable {
constructor () public {
__ERC721_init("ERC 721", "NFT");
}
/**
* @dev See {ERC721-_mint}.
*/
function mint(address to, uint256 tokenId) public {
_mint(to, tokenId);
}
/**
* @dev See {ERC721-_burn}.
*/
function burn(uint256 tokenId) public {
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/ContextUpgradeable.sol";
import "./IERC721Upgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "../../introspection/ERC165Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/EnumerableSetUpgradeable.sol";
import "../../utils/EnumerableMapUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = 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 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 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 returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../utils/ExtendedSafeCast.sol";
contract ExtendedSafeCastExposed {
function toUint112(uint256 value) external pure returns (uint112) {
return ExtendedSafeCast.toUint112(value);
}
function toUint96(uint256 value) external pure returns (uint96) {
return ExtendedSafeCast.toUint96(value);
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../utils/MappedSinglyLinkedList.sol";
contract MappedSinglyLinkedListExposed {
using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping;
MappedSinglyLinkedList.Mapping list;
function initialize() external {
list.initialize();
}
function addressArray() external view returns (address[] memory) {
return list.addressArray();
}
function addAddresses(address[] calldata addresses) external {
list.addAddresses(addresses);
}
function addAddress(address newAddress) external {
list.addAddress(newAddress);
}
function removeAddress(address prevAddress, address addr) external {
list.removeAddress(prevAddress, addr);
}
function contains(address addr) external view returns (bool) {
return list.contains(addr);
}
function clearAll() external {
list.clearAll();
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "../prize-strategy/multiple-winners/MultipleWinners.sol";
/// @title Creates a minimal proxy to the MultipleWinners prize strategy. Very cheap to deploy.
contract MultipleWinnersHarness is MultipleWinners {
uint256 public currentTime;
function setCurrentTime(uint256 _currentTime) external {
currentTime = _currentTime;
}
function _currentTime() internal override view returns (uint256) {
return currentTime;
}
function distribute(uint256 randomNumber) external {
_distribute(randomNumber);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "./MultipleWinnersHarness.sol";
import "../external/openzeppelin/ProxyFactory.sol";
/// @title Creates a minimal proxy to the MultipleWinners prize strategy. Very cheap to deploy.
contract MultipleWinnersHarnessProxyFactory is ProxyFactory {
MultipleWinnersHarness public instance;
constructor () public {
instance = new MultipleWinnersHarness();
}
function create() external returns (MultipleWinnersHarness) {
return MultipleWinnersHarness(deployMinimal(address(instance), ""));
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../prize-strategy/PeriodicPrizeStrategy.sol";
/* solium-disable security/no-block-members */
interface PeriodicPrizeStrategyDistributorInterface {
function distribute(uint256 randomNumber) external;
}
pragma solidity >=0.6.0 <0.7.0;
import "../prize-strategy/PeriodicPrizeStrategy.sol";
import "./PeriodicPrizeStrategyDistributorInterface.sol";
import "@nomiclabs/buidler/console.sol";
/* solium-disable security/no-block-members */
contract PeriodicPrizeStrategyHarness is PeriodicPrizeStrategy {
PeriodicPrizeStrategyDistributorInterface distributor;
function setDistributor(PeriodicPrizeStrategyDistributorInterface _distributor) external {
distributor = _distributor;
}
uint256 internal time;
function setCurrentTime(uint256 _time) external {
time = _time;
}
function _currentTime() internal override view returns (uint256) {
return time;
}
function setRngRequest(uint32 requestId, uint32 lockBlock) external {
rngRequest.id = requestId;
rngRequest.lockBlock = lockBlock;
}
function _distribute(uint256 randomNumber) internal override {
console.log("random number: ", randomNumber);
distributor.distribute(randomNumber);
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../prize-pool/PrizePool.sol";
import "./YieldSourceStub.sol";
contract PrizePoolHarness is PrizePool {
uint256 public currentTime;
YieldSourceStub stubYieldSource;
function initializeAll(
RegistryInterface _reserveRegistry,
ControlledTokenInterface[] memory _controlledTokens,
uint256 _maxExitFeeMantissa,
uint256 _maxTimelockDuration,
YieldSourceStub _stubYieldSource
)
public
{
PrizePool.initialize(
_reserveRegistry,
_controlledTokens,
_maxExitFeeMantissa,
_maxTimelockDuration
);
stubYieldSource = _stubYieldSource;
}
function supply(uint256 mintAmount) external {
_supply(mintAmount);
}
function redeem(uint256 redeemAmount) external {
_redeem(redeemAmount);
}
function setCurrentTime(uint256 _currentTime) external {
currentTime = _currentTime;
}
function setTimelockBalance(uint256 _timelockBalance) external {
timelockTotalSupply = _timelockBalance;
}
function _currentTime() internal override view returns (uint256) {
return currentTime;
}
function _canAwardExternal(address _externalToken) internal override view returns (bool) {
return stubYieldSource.canAwardExternal(_externalToken);
}
function _token() internal override view returns (IERC20Upgradeable) {
return stubYieldSource.token();
}
function _balance() internal override returns (uint256) {
return stubYieldSource.balance();
}
function _supply(uint256 mintAmount) internal override {
return stubYieldSource.supply(mintAmount);
}
function _redeem(uint256 redeemAmount) internal override returns (uint256) {
return stubYieldSource.redeem(redeemAmount);
}
}
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface YieldSourceStub {
function canAwardExternal(address _externalToken) external view returns (bool);
function token() external view returns (IERC20Upgradeable);
function balance() external returns (uint256);
function supply(uint256 mintAmount) external;
function redeem(uint256 redeemAmount) external returns (uint256);
}
pragma solidity >=0.6.0 <0.7.0;
import "@pooltogether/pooltogether-rng-contracts/contracts/RNGInterface.sol";
contract RNGServiceMock is RNGInterface {
uint256 internal random;
address internal feeToken;
uint256 internal requestFee;
function getLastRequestId() external override view returns (uint32 requestId) {
return 1;
}
function setRequestFee(address _feeToken, uint256 _requestFee) external {
feeToken = _feeToken;
requestFee = _requestFee;
}
/// @return _feeToken
/// @return _requestFee
function getRequestFee() external override view returns (address _feeToken, uint256 _requestFee) {
return (feeToken, requestFee);
}
function setRandomNumber(uint256 _random) external {
random = _random;
}
function requestRandomNumber() external override returns (uint32, uint32) {
return (1, 1);
}
function isRequestComplete(uint32) external override view returns (bool) {
return true;
}
function randomNumber(uint32) external override returns (uint256) {
return random;
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../prize-strategy/single-random-winner/SingleRandomWinner.sol";
/* solium-disable security/no-block-members */
contract SingleRandomWinnerHarness is SingleRandomWinner {
uint256 internal time;
function setCurrentTime(uint256 _time) external {
time = _time;
}
function _currentTime() internal override view returns (uint256) {
return time;
}
function setRngRequest(uint32 requestId, uint32 lockBlock) external {
rngRequest.id = requestId;
rngRequest.lockBlock = lockBlock;
}
function distribute(uint256 randomNumber) external {
_distribute(randomNumber);
}
}
pragma solidity >=0.6.0 <0.7.0;
/* solium-disable security/no-block-members */
contract Timestamp {
function blockTime() public view returns (uint256) {
return block.timestamp;
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../utils/UInt256Array.sol";
contract UInt256ArrayExposed {
using UInt256Array for uint256[];
uint256[] internal array;
constructor (uint256[] memory _array) public {
array = new uint256[](_array.length);
for (uint256 i = 0; i < _array.length; i++) {
array[i] = _array[i];
}
}
function remove(uint256 index) external {
array.remove(index);
}
function toArray() external view returns (uint256[] memory) {
return array;
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../drip/VolumeDrip.sol";
contract VolumeDripExposed {
using VolumeDrip for VolumeDrip.State;
event DripTokensBurned(address user, uint256 amount);
event Minted(uint256 amount);
event MintedTotalSupply(uint256 amount);
VolumeDrip.State state;
function setNewPeriod(uint32 periodSeconds, uint112 dripAmount, uint32 endTime) external {
state.setNewPeriod(periodSeconds, dripAmount, endTime);
}
function setNextPeriod(uint32 periodSeconds, uint112 dripAmount) external {
state.setNextPeriod(periodSeconds, dripAmount);
}
function drip(uint256 currentTime, uint256 maxNewTokens) external returns (uint256) {
uint256 newTokens = state.drip(currentTime, maxNewTokens);
emit MintedTotalSupply(newTokens);
return newTokens;
}
function mint(address user, uint256 amount) external returns (uint256) {
uint256 accrued = state.mint(user, amount);
emit Minted(accrued);
return accrued;
}
function getDrip()
external
view
returns (
uint32 periodSeconds,
uint128 dripAmount
)
{
periodSeconds = state.nextPeriodSeconds;
dripAmount = state.nextDripAmount;
}
function getPeriod(uint32 period)
external
view
returns (
uint112 totalSupply,
uint112 dripAmount,
uint32 endTime
)
{
totalSupply = state.periods[period].totalSupply;
endTime = state.periods[period].endTime;
dripAmount = state.periods[period].dripAmount;
}
function getDeposit(address user)
external
view
returns (
uint112 balance,
uint32 period
)
{
balance = state.deposits[user].balance;
period = state.deposits[user].period;
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../drip/VolumeDripManager.sol";
contract VolumeDripManagerExposed {
using VolumeDripManager for VolumeDripManager.State;
using VolumeDrip for VolumeDrip.State;
VolumeDripManager.State manager;
function activate(
address measure,
address dripToken,
uint32 periodSeconds,
uint112 dripAmount,
uint32 endTime
)
external
{
manager.activate(measure, dripToken, periodSeconds, dripAmount, endTime);
}
function deactivate(
address measure,
address dripToken,
address prevDripToken
)
external
{
manager.deactivate(measure, dripToken, prevDripToken);
}
function set(address measure, address dripToken, uint32 periodSeconds, uint112 dripAmount) external {
manager.set(measure, dripToken, periodSeconds, dripAmount);
}
function isActive(address measure, address dripToken) external view returns (bool) {
return manager.isActive(measure, dripToken);
}
function getPeriod(
address measure,
address dripToken,
uint32 period
)
external
view
returns (
uint112 totalSupply,
uint112 dripAmount,
uint32 endTime
)
{
VolumeDrip.State storage drip = manager.getDrip(measure, dripToken);
VolumeDrip.Period memory state = drip.periods[period];
totalSupply = state.totalSupply;
dripAmount = state.dripAmount;
endTime = state.endTime;
}
function getActiveVolumeDrips(address measure) external view returns (address[] memory) {
return manager.getActiveVolumeDrips(measure);
}
function getDrip(
address measure,
address dripToken
)
external
view
returns (
uint32 periodSeconds,
uint112 dripAmount
)
{
VolumeDrip.State storage drip = manager.getDrip(measure, dripToken);
dripAmount = drip.nextDripAmount;
periodSeconds = drip.nextPeriodSeconds;
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../external/yearn/yVaultInterface.sol";
import "./ERC20Mintable.sol";
import "@pooltogether/fixed-point/contracts/FixedPoint.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
contract yVaultMock is yVaultInterface, ERC20Upgradeable {
ERC20Upgradeable private asset;
uint256 public vaultFeeMantissa;
constructor (ERC20Mintable _asset) public {
asset = _asset;
vaultFeeMantissa = 0.05 ether;
}
function token() external override view returns (IERC20Upgradeable) {
return asset;
}
function balance() public override view returns (uint) {
return asset.balanceOf(address(this));
}
function removeLiquidity(uint _amount) external {
asset.transfer(msg.sender, _amount);
}
function setVaultFeeMantissa(uint256 _vaultFeeMantissa) external {
vaultFeeMantissa = _vaultFeeMantissa;
}
function deposit(uint _amount) external override {
uint _pool = balance();
uint _before = asset.balanceOf(address(this));
asset.transferFrom(msg.sender, address(this), _amount);
uint _after = asset.balanceOf(address(this));
uint diff = _after.sub(_before); // Additional check for deflationary assets
uint shares = 0;
if (totalSupply() == 0) {
shares = diff;
} else {
shares = (diff.mul(totalSupply())).div(_pool);
}
_mint(msg.sender, shares);
}
function withdraw(uint _shares) external override {
uint256 sharesFee = FixedPoint.multiplyUintByMantissa(_shares, vaultFeeMantissa);
uint256 withdrawal = (balance().mul(_shares.sub(sharesFee))).div(totalSupply());
asset.transfer(msg.sender, withdrawal);
_mint(address(this), sharesFee);
_burn(msg.sender, _shares);
}
function getPricePerFullShare() external override view returns (uint) {
return balance().mul(1e18).div(totalSupply());
}
}
pragma solidity >=0.6.0 <0.7.0;
import "../prize-pool/yearn/yVaultPrizePool.sol";
contract yVaultPrizePoolHarness is yVaultPrizePool {
uint256 public currentTime;
function setCurrentTime(uint256 _currentTime) external {
currentTime = _currentTime;
}
function _currentTime() internal override view returns (uint256) {
return currentTime;
}
function supply(uint256 mintAmount) external {
_supply(mintAmount);
}
function redeem(uint256 redeemAmount) external returns (uint256) {
return _redeem(redeemAmount);
}
}
pragma solidity >=0.6.0 <0.7.0;
import "./yVaultPrizePoolHarness.sol";
import "../external/openzeppelin/ProxyFactory.sol";
/// @title Compound Prize Pool Proxy Factory
/// @notice Minimal proxy pattern for creating new Compound Prize Pools
contract yVaultPrizePoolHarnessProxyFactory is ProxyFactory {
/// @notice Contract template for deploying proxied Prize Pools
yVaultPrizePoolHarness public instance;
/// @notice Initializes the Factory with an instance of the Compound Prize Pool
constructor () public {
instance = new yVaultPrizePoolHarness();
}
/// @notice Creates a new Compound Prize Pool as a proxy of the template instance
/// @return A reference to the new proxied Compound Prize Pool
function create() external returns (yVaultPrizePoolHarness) {
return yVaultPrizePoolHarness(deployMinimal(address(instance), ""));
}
}
|
@title Manages the lifecycle of a set of Balance Drips.
|
library BalanceDripManager {
using SafeMathUpgradeable for uint256;
using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping;
using BalanceDrip for BalanceDrip.State;
struct State {
mapping(address => MappedSinglyLinkedList.Mapping) activeBalanceDrips;
mapping(address => mapping(address => BalanceDrip.State)) balanceDrips;
}
function activateDrip(
State storage self,
address measure,
address dripToken,
uint256 dripRatePerSecond
)
internal
{
require(!self.activeBalanceDrips[measure].contains(dripToken), "BalanceDripManager/drip-active");
if (self.activeBalanceDrips[measure].count == 0) {
self.activeBalanceDrips[measure].initialize();
}
self.activeBalanceDrips[measure].addAddress(dripToken);
self.balanceDrips[measure][dripToken].resetTotalDripped();
self.balanceDrips[measure][dripToken].dripRatePerSecond = dripRatePerSecond;
}
function activateDrip(
State storage self,
address measure,
address dripToken,
uint256 dripRatePerSecond
)
internal
{
require(!self.activeBalanceDrips[measure].contains(dripToken), "BalanceDripManager/drip-active");
if (self.activeBalanceDrips[measure].count == 0) {
self.activeBalanceDrips[measure].initialize();
}
self.activeBalanceDrips[measure].addAddress(dripToken);
self.balanceDrips[measure][dripToken].resetTotalDripped();
self.balanceDrips[measure][dripToken].dripRatePerSecond = dripRatePerSecond;
}
function deactivateDrip(
State storage self,
address measure,
address dripToken,
address prevDripToken,
uint32 currentTime,
uint256 maxNewTokens
)
internal
{
self.activeBalanceDrips[measure].removeAddress(prevDripToken, dripToken);
self.balanceDrips[measure][dripToken].drip(IERC20Upgradeable(measure).totalSupply(), currentTime, maxNewTokens);
self.balanceDrips[measure][dripToken].dripRatePerSecond = 0;
}
function getActiveBalanceDrips(State storage self, address measure) internal view returns (address[] memory) {
return self.activeBalanceDrips[measure].addressArray();
}
function setDripRate(
State storage self,
address measure,
address dripToken,
uint256 dripRatePerSecond,
uint32 currentTime,
uint256 maxNewTokens
) internal {
require(self.activeBalanceDrips[measure].contains(dripToken), "BalanceDripManager/drip-not-active");
self.balanceDrips[measure][dripToken].drip(IERC20Upgradeable(measure).totalSupply(), currentTime, maxNewTokens);
self.balanceDrips[measure][dripToken].dripRatePerSecond = dripRatePerSecond;
}
function isDripActive(State storage self, address measure, address dripToken) internal view returns (bool) {
return self.activeBalanceDrips[measure].contains(dripToken);
}
function getDrip(State storage self, address measure, address dripToken) internal view returns (BalanceDrip.State storage) {
return self.balanceDrips[measure][dripToken];
}
}
| 12,863,635 |
[
1,
49,
940,
281,
326,
6596,
434,
279,
444,
434,
30918,
463,
566,
1121,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
12083,
30918,
40,
21335,
1318,
288,
203,
225,
1450,
14060,
10477,
10784,
429,
364,
2254,
5034,
31,
203,
225,
1450,
22806,
55,
310,
715,
13174,
682,
364,
22806,
55,
310,
715,
13174,
682,
18,
3233,
31,
203,
225,
1450,
30918,
40,
21335,
364,
30918,
40,
21335,
18,
1119,
31,
203,
203,
203,
225,
1958,
3287,
288,
203,
565,
2874,
12,
2867,
516,
22806,
55,
310,
715,
13174,
682,
18,
3233,
13,
2695,
13937,
40,
566,
1121,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
30918,
40,
21335,
18,
1119,
3719,
11013,
40,
566,
1121,
31,
203,
225,
289,
203,
203,
225,
445,
10235,
40,
21335,
12,
203,
565,
3287,
2502,
365,
16,
203,
565,
1758,
6649,
16,
203,
565,
1758,
302,
21335,
1345,
16,
203,
565,
2254,
5034,
302,
21335,
4727,
2173,
8211,
203,
225,
262,
203,
565,
2713,
203,
225,
288,
203,
565,
2583,
12,
5,
2890,
18,
3535,
13937,
40,
566,
1121,
63,
10772,
8009,
12298,
12,
72,
21335,
1345,
3631,
315,
13937,
40,
21335,
1318,
19,
72,
21335,
17,
3535,
8863,
203,
565,
309,
261,
2890,
18,
3535,
13937,
40,
566,
1121,
63,
10772,
8009,
1883,
422,
374,
13,
288,
203,
1377,
365,
18,
3535,
13937,
40,
566,
1121,
63,
10772,
8009,
11160,
5621,
203,
565,
289,
203,
565,
365,
18,
3535,
13937,
40,
566,
1121,
63,
10772,
8009,
1289,
1887,
12,
72,
21335,
1345,
1769,
203,
565,
365,
18,
12296,
40,
566,
1121,
63,
10772,
6362,
72,
21335,
1345,
8009,
6208,
5269,
40,
21335,
1845,
5621,
203,
2
] |
contract ZeroDollarHomePage {
event InvalidPullRequest(uint indexed pullRequestId);
event PullRequestAlreadyClaimed(uint indexed pullRequestId, uint timeBeforeDisplay, bool past);
event PullRequestClaimed(uint indexed pullRequestId, uint timeBeforeDisplay);
event QueueIsEmpty();
bool _handledFirst;
uint[] _queue;
uint _current;
address owner;
function ZeroDollarHomePage() {
owner = msg.sender;
_handledFirst = false;
_current = 0;
}
function remove() {
if (msg.sender == owner){
suicide(owner);
}
}
/*
* Register a new pull request.
*/
function newRequest(uint pullRequestId) {
if (pullRequestId <= 0) {
InvalidPullRequest(pullRequestId);
return;
}
// Check that the pr hasn't already been claimed
bool found = false;
uint index = 0;
while (!found && index < _queue.length) {
if (_queue[index] == pullRequestId) {
found = true;
break;
} else {
index++;
}
}
if (found) {
PullRequestAlreadyClaimed(pullRequestId, (index - _current) * 1 days, _current > index);
return;
}
_queue.push(pullRequestId);
PullRequestClaimed(pullRequestId, (_queue.length - _current) * 1 days);
}
/*
* Close the current request in queue and move the queue to its next element.
*/
function closeRequest() {
if (_handledFirst && _current < _queue.length - 1) {
_current += 1;
}
_handledFirst = true;
}
/*
* Get the last non published pull-request from the queue
*/
function getLastNonPublished() constant returns (uint pullRequestId) {
if (_current >= _queue.length) {
return 0;
}
return _queue[_current];
}
}
|
Register a new pull request./
|
function newRequest(uint pullRequestId) {
if (pullRequestId <= 0) {
InvalidPullRequest(pullRequestId);
return;
}
uint index = 0;
while (!found && index < _queue.length) {
if (_queue[index] == pullRequestId) {
found = true;
break;
index++;
}
}
if (found) {
PullRequestAlreadyClaimed(pullRequestId, (index - _current) * 1 days, _current > index);
return;
}
_queue.push(pullRequestId);
PullRequestClaimed(pullRequestId, (_queue.length - _current) * 1 days);
}
| 5,374,571 |
[
1,
3996,
279,
394,
6892,
590,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7428,
12,
11890,
6892,
15493,
13,
288,
203,
3639,
309,
261,
13469,
15493,
1648,
374,
13,
288,
203,
5411,
1962,
22794,
12,
13469,
15493,
1769,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
2254,
770,
273,
374,
31,
203,
203,
3639,
1323,
16051,
7015,
597,
770,
411,
389,
4000,
18,
2469,
13,
288,
203,
5411,
309,
261,
67,
4000,
63,
1615,
65,
422,
6892,
15493,
13,
288,
203,
7734,
1392,
273,
638,
31,
203,
7734,
898,
31,
203,
7734,
770,
9904,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
309,
261,
7015,
13,
288,
203,
5411,
31826,
9430,
9762,
329,
12,
13469,
15493,
16,
261,
1615,
300,
389,
2972,
13,
380,
404,
4681,
16,
389,
2972,
405,
770,
1769,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
389,
4000,
18,
6206,
12,
13469,
15493,
1769,
203,
3639,
31826,
9762,
329,
12,
13469,
15493,
16,
261,
67,
4000,
18,
2469,
300,
389,
2972,
13,
380,
404,
4681,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0x05Ed8abeef9EdE006bc8dFc9B3D272441D370488/sources/apps/avai/src/contracts/overrides/UpgradeableBeacon.sol
|
* @dev Emitted when the child implementation returned by the beacon is changed./* @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the beacon./
|
{
__Ownable_init_unchained();
_setImplementation(implementation_);
}
| 7,165,372 |
[
1,
1514,
11541,
1347,
326,
1151,
4471,
2106,
635,
326,
29203,
353,
3550,
18,
19,
225,
11511,
326,
1758,
434,
326,
2172,
4471,
16,
471,
326,
7286,
264,
2236,
487,
326,
3410,
10354,
848,
8400,
326,
29203,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
288,
203,
565,
1001,
5460,
429,
67,
2738,
67,
4384,
8707,
5621,
203,
565,
389,
542,
13621,
12,
30810,
67,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x9E696A466A1BaAaf60fB4fc1807691863be06DB3/sources/CyclopsBank.sol
|
ensure we revert in case of failurebefore we closed deposit - extract reward (if deposit is extractable, reward is also extractable)and after that close depositcustomers_deposits[index].deposits[dep_id].votes = 0;for(uint256 i=0; i < dep.tokens_number; i++){do nothing
|
if (p_dep_type == ERC20_TOKEN || p_dep_type == UNISWAP_PAIR){
ERC20Token token = ERC20Token(p_tok_addr);
uint256 contractTokenBalance = token.balanceOf(_own_address);
require(contractTokenBalance >= amount, "13");
try token.transfer(cust_wallet, amount) {
withdrawDepositRewardById(cust_wallet,dep_id);
customers_deposits[index].deposits[dep_id].acc_reward = 0;
uint256[] memory empty;
emit CustomerWithdrawDeposit(cust_wallet, customers_deposits[index].deposits[dep_id].deposit_profile_id, dep_id, amount, empty);
require(false,"3");
}
ERC721Token token = ERC721Token(p_tok_addr);
uint256 tokens_count = token.balanceOf(_own_address);
require(tokens_count > 0,"14");
Deposit storage dep = customers_deposits[index].deposits[dep_id];
try token.approve(msg.sender, dep.token_ids[i]) {
require(false, "6");
}
}*/
| 3,380,877 |
[
1,
15735,
732,
15226,
316,
648,
434,
5166,
5771,
732,
4375,
443,
1724,
300,
2608,
19890,
261,
430,
443,
1724,
353,
2608,
429,
16,
19890,
353,
2546,
2608,
429,
13,
464,
1839,
716,
1746,
443,
1724,
3662,
414,
67,
323,
917,
1282,
63,
1615,
8009,
323,
917,
1282,
63,
15037,
67,
350,
8009,
27800,
273,
374,
31,
1884,
12,
11890,
5034,
277,
33,
20,
31,
277,
411,
5993,
18,
7860,
67,
2696,
31,
277,
27245,
95,
2896,
5083,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
309,
261,
84,
67,
15037,
67,
723,
422,
4232,
39,
3462,
67,
8412,
747,
293,
67,
15037,
67,
723,
422,
5019,
5127,
59,
2203,
67,
4066,
7937,
15329,
203,
5411,
4232,
39,
3462,
1345,
1147,
273,
4232,
39,
3462,
1345,
12,
84,
67,
17692,
67,
4793,
1769,
203,
5411,
2254,
5034,
6835,
1345,
13937,
273,
1147,
18,
12296,
951,
24899,
995,
67,
2867,
1769,
203,
2398,
203,
5411,
2583,
12,
16351,
1345,
13937,
1545,
3844,
16,
315,
3437,
8863,
203,
5411,
203,
5411,
203,
5411,
775,
1147,
18,
13866,
12,
71,
641,
67,
19177,
16,
3844,
13,
288,
7010,
7734,
598,
9446,
758,
1724,
17631,
1060,
5132,
12,
71,
641,
67,
19177,
16,
15037,
67,
350,
1769,
203,
7734,
29380,
67,
323,
917,
1282,
63,
1615,
8009,
323,
917,
1282,
63,
15037,
67,
350,
8009,
8981,
67,
266,
2913,
273,
374,
31,
203,
1171,
203,
7734,
2254,
5034,
8526,
3778,
1008,
31,
7010,
7734,
3626,
13702,
1190,
9446,
758,
1724,
12,
71,
641,
67,
19177,
16,
29380,
67,
323,
917,
1282,
63,
1615,
8009,
323,
917,
1282,
63,
15037,
67,
350,
8009,
323,
1724,
67,
5040,
67,
350,
16,
5993,
67,
350,
16,
3844,
16,
1008,
1769,
203,
7734,
203,
7734,
2583,
12,
5743,
10837,
23,
8863,
203,
5411,
289,
203,
2868,
203,
540,
203,
2398,
203,
5411,
4232,
39,
27,
5340,
1345,
1147,
273,
4232,
39,
27,
5340,
1345,
12,
84,
67,
17692,
67,
4793,
1769,
203,
2398,
203,
5411,
2254,
5034,
2430,
67,
1883,
273,
1147,
18,
12296,
951,
24899,
995,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-03
*/
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract GovernorAlpha {
/// @notice The name of this contract
string public constant name = "Unslashed Governor Alpha";
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
function quorumVotes() public pure returns (uint) { return 400000e18; }
/// @notice The number of votes required in order for a voter to become a proposer
function proposalThreshold() public pure returns (uint) { return 100000e18; }
/// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions
/// @notice The delay before voting on a proposal may take place, once proposed
function votingDelay() public pure returns (uint) { return 1; } // 1 block
/// @notice The duration of voting on a proposal, in blocks
function votingPeriod() public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks)
/// @notice The address of the Unslashed Protocol Timelock
TimelockInterface public timelock;
/// @notice The address of the Unslashed governance token
UsfInterface public usf;
/// @notice The address of the Governor Guardian
address public guardian;
/// @notice The total number of proposals
uint public proposalCount;
struct Proposal {
/// @notice Unique id for looking up a proposal
uint id;
/// @notice Creator of the proposal
address proposer;
/// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
/// @notice the ordered list of target addresses for calls to be made
address[] targets;
/// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
/// @notice The ordered list of function signatures to be called
string[] signatures;
/// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
/// @notice The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
/// @notice The block at which voting ends: votes must be cast prior to this block
uint endBlock;
/// @notice Current number of votes in favor of this proposal
uint forVotes;
/// @notice Current number of votes in opposition to this proposal
uint againstVotes;
/// @notice Flag marking whether the proposal has been canceled
bool canceled;
/// @notice Flag marking whether the proposal has been executed
bool executed;
/// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
/// @notice Whether or not a vote has been cast
bool hasVoted;
/// @notice Whether or not the voter supports the proposal
bool support;
/// @notice The number of votes the voter had, which were cast
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/// @notice The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
/// @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 ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint proposalId, bool support, uint votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
constructor(address timelock_, address usf_, address guardian_) public {
timelock = TimelockInterface(timelock_);
usf = UsfInterface(usf_);
guardian = guardian_;
}
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
require(usf.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorAlpha::propose: must provide actions");
require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay());
uint endBlock = add256(startBlock, votingPeriod());
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
function queue(uint proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
function execute(uint proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
function cancel(uint proposalId) public {
ProposalState state = state(proposalId);
require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == guardian || usf.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function castVote(uint proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature");
return _castVote(signatory, proposalId, support);
}
function _castVote(address voter, uint proposalId, bool support) internal {
require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted");
uint96 votes = usf.getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else {
proposal.againstVotes = add256(proposal.againstVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian");
timelock.acceptAdmin();
}
function __abdicate() public {
require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian");
guardian = address(0);
}
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainId() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
interface TimelockInterface {
function delay() external view returns (uint);
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface UsfInterface {
function getPriorVotes(address account, uint blockNumber) external view returns (uint96);
}
|
@notice The number of votes required in order for a voter to become a proposer
|
function proposalThreshold() public pure returns (uint) { return 100000e18; }
| 11,960,057 |
[
1,
1986,
1300,
434,
19588,
1931,
316,
1353,
364,
279,
331,
20005,
358,
12561,
279,
450,
5607,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
14708,
7614,
1435,
1071,
16618,
1135,
261,
11890,
13,
288,
327,
25259,
73,
2643,
31,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.2;
// File: contracts/ERC20Interface.sol
// https://github.com/ethereum/EIPs/issues/20
interface ERC20 {
function totalSupply() external view returns (uint supply);
function balanceOf(address _owner) external view returns (uint balance);
function transfer(address _to, uint _value) external returns (bool success);
function transferFrom(address _from, address _to, uint _value) external returns (bool success);
function approve(address _spender, uint _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract ERC20WithSymbol is ERC20 {
function symbol() external view returns (string memory _symbol);
}
// File: contracts/PermissionGroups.sol
contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) internal operators;
mapping(address=>bool) internal alerters;
address[] internal operatorsGroup;
address[] internal alertersGroup;
uint constant internal MAX_GROUP_SIZE = 50;
constructor() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin, "Operation limited to admin");
_;
}
modifier onlyOperator() {
require(operators[msg.sender], "Operation limited to operator");
_;
}
modifier onlyAlerter() {
require(alerters[msg.sender], "Operation limited to alerter");
_;
}
function getOperators () external view returns(address[] memory) {
return operatorsGroup;
}
function getAlerters () external view returns(address[] memory) {
return alertersGroup;
}
event TransferAdminPending(address pendingAdmin);
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0), "admin address cannot be 0");
emit TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
/**
* @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdminQuickly(address newAdmin) public onlyAdmin {
require(newAdmin != address(0), "admin address cannot be 0");
emit TransferAdminPending(newAdmin);
emit AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
event AdminClaimed( address newAdmin, address previousAdmin);
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender, "admin address cannot be 0");
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AlerterAdded (address newAlerter, bool isAdd);
function addAlerter(address newAlerter) public onlyAdmin {
// prevent duplicates.
require(!alerters[newAlerter], "alerter already configured");
require(
alertersGroup.length < MAX_GROUP_SIZE,
"alerter group exceeding maximum size"
);
emit AlerterAdded(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function removeAlerter (address alerter) public onlyAdmin {
require(alerters[alerter], "alerter not configured");
alerters[alerter] = false;
for (uint i = 0; i < alertersGroup.length; ++i) {
if (block.coinbase == alerter) { //injected CONTRACT AFFECTED BY MINERS
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.length--;
emit AlerterAdded(alerter, false);
break;
}
}
}
event OperatorAdded(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
// prevent duplicates.
require(!operators[newOperator], "operator already configured");
require(
operatorsGroup.length < MAX_GROUP_SIZE,
"operator group exceeding maximum size"
);
emit OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {
require(operators[operator], "operator not configured");
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i) {
if (block.coinbase == operator) { //injected CONTRACT AFFECTED BY MINERS
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
emit OperatorAdded(operator, false);
break;
}
}
}
}
// File: contracts/Withdrawable.sol
/**
* @title Contracts that should be able to recover tokens or ethers
* @author Ilan Doron
* @dev This allows to recover any tokens or Ethers received in a contract.
* This will prevent any accidental loss of tokens.
*/
contract Withdrawable is PermissionGroups {
event TokenWithdraw(
ERC20 indexed token,
uint amount,
address indexed sendTo
);
/**
* @dev Withdraw all ERC20 compatible tokens
* @param token ERC20 The address of the token contract
*/
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount), "Could not transfer tokens");
emit TokenWithdraw(token, amount, sendTo);
}
event EtherWithdraw(
uint amount,
address indexed sendTo
);
/**
* @dev Withdraw Ethers
*/
function withdrawEther(uint amount, address payable sendTo) external onlyAdmin {
sendTo.transfer(amount);
emit EtherWithdraw(amount, sendTo);
}
}
// File: @gnosis.pm/util-contracts/contracts/Proxy.sol
/// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy.
/// @author Alan Lu - <[email protected]>
contract Proxied {
address public masterCopy;
}
/// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <[email protected]>
contract Proxy is Proxied {
/// @dev Constructor function sets address of master copy contract.
/// @param _masterCopy Master copy address.
constructor(address _masterCopy) public {
require(_masterCopy != address(0), "The master copy is required");
masterCopy = _masterCopy;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
function() external payable {
address _masterCopy = masterCopy;
assembly {
calldatacopy(0, 0, calldatasize)
let success := delegatecall(not(0), _masterCopy, 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
switch success
case 0 {
revert(0, returndatasize)
}
default {
return(0, returndatasize)
}
}
}
}
// File: @gnosis.pm/util-contracts/contracts/Token.sol
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
pragma solidity ^0.5.2;
/// @title Abstract token contract - Functions to be implemented by token contracts
contract Token {
/*
* Events
*/
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
/*
* Public functions
*/
function transfer(address to, uint value) public returns (bool);
function transferFrom(address from, address to, uint value) public returns (bool);
function approve(address spender, uint value) public returns (bool);
function balanceOf(address owner) public view returns (uint);
function allowance(address owner, address spender) public view returns (uint);
function totalSupply() public view returns (uint);
}
// File: @gnosis.pm/util-contracts/contracts/Math.sol
/// @title Math library - Allows calculation of logarithmic and exponential functions
/// @author Alan Lu - <[email protected]>
/// @author Stefan George - <[email protected]>
library GnosisMath {
/*
* Constants
*/
// This is equal to 1 in our calculations
uint public constant ONE = 0x10000000000000000;
uint public constant LN2 = 0xb17217f7d1cf79ac;
uint public constant LOG2_E = 0x171547652b82fe177;
/*
* Public functions
*/
/// @dev Returns natural exponential function value of given x
/// @param x x
/// @return e**x
function exp(int x) public pure returns (uint) {
// revert if x is > MAX_POWER, where
// MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE))
require(x <= 2454971259878909886679);
// return 0 if exp(x) is tiny, using
// MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE))
if (x < -818323753292969962227) return 0;
// Transform so that e^x -> 2^x
x = x * int(ONE) / int(LN2);
// 2^x = 2^whole(x) * 2^frac(x)
// ^^^^^^^^^^ is a bit shift
// so Taylor expand on z = frac(x)
int shift;
uint z;
if (x >= 0) {
shift = x / int(ONE);
z = uint(x % int(ONE));
} else {
shift = x / int(ONE) - 1;
z = ONE - uint(-x % int(ONE));
}
// 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ...
//
// Can generate the z coefficients using mpmath and the following lines
// >>> from mpmath import mp
// >>> mp.dps = 100
// >>> ONE = 0x10000000000000000
// >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7)))
// 0xb17217f7d1cf79ab
// 0x3d7f7bff058b1d50
// 0xe35846b82505fc5
// 0x276556df749cee5
// 0x5761ff9e299cc4
// 0xa184897c363c3
uint zpow = z;
uint result = ONE;
result += 0xb17217f7d1cf79ab * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x3d7f7bff058b1d50 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe35846b82505fc5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x276556df749cee5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x5761ff9e299cc4 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xa184897c363c3 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xffe5fe2c4586 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x162c0223a5c8 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1b5253d395e * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e4cf5158b * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e8cac735 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1c3bd650 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1816193 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x131496 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe1b7 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x9c7 * zpow / ONE;
if (shift >= 0) {
if (result >> (256 - shift) > 0) return (2 ** 256 - 1);
return result << shift;
} else return result >> (-shift);
}
/// @dev Returns natural logarithm value of given x
/// @param x x
/// @return ln(x)
function ln(uint x) public pure returns (int) {
require(x > 0);
// binary search for floor(log2(x))
int ilog2 = floorLog2(x);
int z;
if (ilog2 < 0) z = int(x << uint(-ilog2));
else z = int(x >> uint(ilog2));
// z = x * 2^-1log1x1
// so 1 <= z < 2
// and ln z = ln x - 1log1x1/log1e
// so just compute ln z using artanh series
// and calculate ln x from that
int term = (z - int(ONE)) * int(ONE) / (z + int(ONE));
int halflnz = term;
int termpow = term * term / int(ONE) * term / int(ONE);
halflnz += termpow / 3;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 5;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 7;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 9;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 11;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 13;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 15;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 17;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 19;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 21;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 23;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 25;
return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz;
}
/// @dev Returns base 2 logarithm value of given x
/// @param x x
/// @return logarithmic value
function floorLog2(uint x) public pure returns (int lo) {
lo = -64;
int hi = 193;
// I use a shift here instead of / 2 because it floors instead of rounding towards 0
int mid = (hi + lo) >> 1;
while ((lo + 1) < hi) {
if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) hi = mid;
else lo = mid;
mid = (hi + lo) >> 1;
}
}
/// @dev Returns maximum of an array
/// @param nums Numbers to look through
/// @return Maximum number
function max(int[] memory nums) public pure returns (int maxNum) {
require(nums.length > 0);
maxNum = -2 ** 255;
for (uint i = 0; i < nums.length; i++) if (nums[i] > maxNum) maxNum = nums[i];
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b) internal pure returns (bool) {
return a >= b;
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(uint a, uint b) internal pure returns (bool) {
return b == 0 || a * b / b == a;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b) internal pure returns (uint) {
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b) internal pure returns (uint) {
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(uint a, uint b) internal pure returns (uint) {
require(safeToMul(a, b));
return a * b;
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(int a, int b) internal pure returns (bool) {
return (b >= 0 && a + b >= a) || (b < 0 && a + b < a);
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(int a, int b) internal pure returns (bool) {
return (b >= 0 && a - b <= a) || (b < 0 && a - b > a);
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(int a, int b) internal pure returns (bool) {
return (b == 0) || (a * b / b == a);
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(int a, int b) internal pure returns (int) {
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(int a, int b) internal pure returns (int) {
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(int a, int b) internal pure returns (int) {
require(safeToMul(a, b));
return a * b;
}
}
// File: @gnosis.pm/util-contracts/contracts/GnosisStandardToken.sol
/**
* Deprecated: Use Open Zeppeling one instead
*/
contract StandardTokenData {
/*
* Storage
*/
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowances;
uint totalTokens;
}
/**
* Deprecated: Use Open Zeppeling one instead
*/
/// @title Standard token contract with overflow protection
contract GnosisStandardToken is Token, StandardTokenData {
using GnosisMath for *;
/*
* Public functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success
/// @param to Address of token receiver
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transfer(address to, uint value) public returns (bool) {
if (!balances[msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) {
return false;
}
balances[msg.sender] -= value;
balances[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success
/// @param from Address from where tokens are withdrawn
/// @param to Address to where tokens are sent
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transferFrom(address from, address to, uint value) public returns (bool) {
if (!balances[from].safeToSub(value) || !allowances[from][msg.sender].safeToSub(
value
) || !balances[to].safeToAdd(value)) {
return false;
}
balances[from] -= value;
allowances[from][msg.sender] -= value;
balances[to] += value;
emit Transfer(from, to, value);
return true;
}
/// @dev Sets approved amount of tokens for spender. Returns success
/// @param spender Address of allowed account
/// @param value Number of approved tokens
/// @return Was approval successful?
function approve(address spender, uint value) public returns (bool) {
allowances[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/// @dev Returns number of allowed tokens for given address
/// @param owner Address of token owner
/// @param spender Address of token spender
/// @return Remaining allowance for spender
function allowance(address owner, address spender) public view returns (uint) {
return allowances[owner][spender];
}
/// @dev Returns number of tokens owned by given address
/// @param owner Address of token owner
/// @return Balance of owner
function balanceOf(address owner) public view returns (uint) {
return balances[owner];
}
/// @dev Returns total supply of tokens
/// @return Total supply
function totalSupply() public view returns (uint) {
return totalTokens;
}
}
// File: @gnosis.pm/dx-contracts/contracts/TokenFRT.sol
/// @title Standard token contract with overflow protection
contract TokenFRT is Proxied, GnosisStandardToken {
address public owner;
string public constant symbol = "MGN";
string public constant name = "Magnolia Token";
uint8 public constant decimals = 18;
struct UnlockedToken {
uint amountUnlocked;
uint withdrawalTime;
}
/*
* Storage
*/
address public minter;
// user => UnlockedToken
mapping(address => UnlockedToken) public unlockedTokens;
// user => amount
mapping(address => uint) public lockedTokenBalances;
/*
* Public functions
*/
// @dev allows to set the minter of Magnolia tokens once.
// @param _minter the minter of the Magnolia tokens, should be the DX-proxy
function updateMinter(address _minter) public {
require(msg.sender == owner, "Only the minter can set a new one");
require(_minter != address(0), "The new minter must be a valid address");
minter = _minter;
}
// @dev the intention is to set the owner as the DX-proxy, once it is deployed
// Then only an update of the DX-proxy contract after a 30 days delay could change the minter again.
function updateOwner(address _owner) public {
require(msg.sender == owner, "Only the owner can update the owner");
require(_owner != address(0), "The new owner must be a valid address");
owner = _owner;
}
function mintTokens(address user, uint amount) public {
require(msg.sender == minter, "Only the minter can mint tokens");
lockedTokenBalances[user] = add(lockedTokenBalances[user], amount);
totalTokens = add(totalTokens, amount);
}
/// @dev Lock Token
function lockTokens(uint amount) public returns (uint totalAmountLocked) {
// Adjust amount by balance
uint actualAmount = min(amount, balances[msg.sender]);
// Update state variables
balances[msg.sender] = sub(balances[msg.sender], actualAmount);
lockedTokenBalances[msg.sender] = add(lockedTokenBalances[msg.sender], actualAmount);
// Get return variable
totalAmountLocked = lockedTokenBalances[msg.sender];
}
function unlockTokens() public returns (uint totalAmountUnlocked, uint withdrawalTime) {
// Adjust amount by locked balances
uint amount = lockedTokenBalances[msg.sender];
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
// Update state variables
lockedTokenBalances[msg.sender] = sub(lockedTokenBalances[msg.sender], amount);
unlockedTokens[msg.sender].amountUnlocked = add(unlockedTokens[msg.sender].amountUnlocked, amount);
unlockedTokens[msg.sender].withdrawalTime = now + 24 hours;
}
// Get return variables
totalAmountUnlocked = unlockedTokens[msg.sender].amountUnlocked;
withdrawalTime = unlockedTokens[msg.sender].withdrawalTime;
}
function withdrawUnlockedTokens() public {
require(unlockedTokens[msg.sender].withdrawalTime < now, "The tokens cannot be withdrawn yet");
balances[msg.sender] = add(balances[msg.sender], unlockedTokens[msg.sender].amountUnlocked);
unlockedTokens[msg.sender].amountUnlocked = 0;
}
function min(uint a, uint b) public pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b) public pure returns (bool) {
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b) public pure returns (bool) {
return a >= b;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b) public pure returns (uint) {
require(safeToAdd(a, b), "It must be a safe adition");
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b) public pure returns (uint) {
require(safeToSub(a, b), "It must be a safe substraction");
return a - b;
}
}
// File: @gnosis.pm/owl-token/contracts/TokenOWL.sol
contract TokenOWL is Proxied, GnosisStandardToken {
using GnosisMath for *;
string public constant name = "OWL Token";
string public constant symbol = "OWL";
uint8 public constant decimals = 18;
struct masterCopyCountdownType {
address masterCopy;
uint timeWhenAvailable;
}
masterCopyCountdownType masterCopyCountdown;
address public creator;
address public minter;
event Minted(address indexed to, uint256 amount);
event Burnt(address indexed from, address indexed user, uint256 amount);
modifier onlyCreator() {
// R1
require(msg.sender == creator, "Only the creator can perform the transaction");
_;
}
/// @dev trickers the update process via the proxyMaster for a new address _masterCopy
/// updating is only possible after 30 days
function startMasterCopyCountdown(address _masterCopy) public onlyCreator {
require(address(_masterCopy) != address(0), "The master copy must be a valid address");
// Update masterCopyCountdown
masterCopyCountdown.masterCopy = _masterCopy;
masterCopyCountdown.timeWhenAvailable = now + 30 days;
}
/// @dev executes the update process via the proxyMaster for a new address _masterCopy
function updateMasterCopy() public onlyCreator {
require(address(masterCopyCountdown.masterCopy) != address(0), "The master copy must be a valid address");
require(
block.timestamp >= masterCopyCountdown.timeWhenAvailable,
"It's not possible to update the master copy during the waiting period"
);
// Update masterCopy
masterCopy = masterCopyCountdown.masterCopy;
}
function getMasterCopy() public view returns (address) {
return masterCopy;
}
/// @dev Set minter. Only the creator of this contract can call this.
/// @param newMinter The new address authorized to mint this token
function setMinter(address newMinter) public onlyCreator {
minter = newMinter;
}
/// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this.
/// @param newOwner The new address, which should become the owner
function setNewOwner(address newOwner) public onlyCreator {
creator = newOwner;
}
/// @dev Mints OWL.
/// @param to Address to which the minted token will be given
/// @param amount Amount of OWL to be minted
function mintOWL(address to, uint amount) public {
require(minter != address(0), "The minter must be initialized");
require(msg.sender == minter, "Only the minter can mint OWL");
balances[to] = balances[to].add(amount);
totalTokens = totalTokens.add(amount);
emit Minted(to, amount);
}
/// @dev Burns OWL.
/// @param user Address of OWL owner
/// @param amount Amount of OWL to be burnt
function burnOWL(address user, uint amount) public {
allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount);
balances[user] = balances[user].sub(amount);
totalTokens = totalTokens.sub(amount);
emit Burnt(msg.sender, user, amount);
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/SafeTransfer.sol
interface BadToken {
function transfer(address to, uint value) external;
function transferFrom(address from, address to, uint value) external;
}
contract SafeTransfer {
function safeTransfer(address token, address to, uint value, bool from) internal returns (bool result) {
if (from) {
BadToken(token).transferFrom(msg.sender, address(this), value);
} else {
BadToken(token).transfer(to, value);
}
// solium-disable-next-line security/no-inline-assembly
assembly {
switch returndatasize
case 0 {
// This is our BadToken
result := not(0) // result is true
}
case 32 {
// This is our GoodToken
returndatacopy(0, 0, 32)
result := mload(0) // result == returndata of external call
}
default {
// This is not an ERC20 token
result := 0
}
}
return result;
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/AuctioneerManaged.sol
contract AuctioneerManaged {
// auctioneer has the power to manage some variables
address public auctioneer;
function updateAuctioneer(address _auctioneer) public onlyAuctioneer {
require(_auctioneer != address(0), "The auctioneer must be a valid address");
auctioneer = _auctioneer;
}
// > Modifiers
modifier onlyAuctioneer() {
// Only allows auctioneer to proceed
// R1
// require(msg.sender == auctioneer, "Only auctioneer can perform this operation");
require(msg.sender == auctioneer, "Only the auctioneer can nominate a new one");
_;
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/TokenWhitelist.sol
contract TokenWhitelist is AuctioneerManaged {
// Mapping that stores the tokens, which are approved
// Only tokens approved by auctioneer generate frtToken tokens
// addressToken => boolApproved
mapping(address => bool) public approvedTokens;
event Approval(address indexed token, bool approved);
/// @dev for quick overview of approved Tokens
/// @param addressesToCheck are the ERC-20 token addresses to be checked whether they are approved
function getApprovedAddressesOfList(address[] calldata addressesToCheck) external view returns (bool[] memory) {
uint length = addressesToCheck.length;
bool[] memory isApproved = new bool[](length);
for (uint i = 0; i < length; i++) {
isApproved[i] = approvedTokens[addressesToCheck[i]];
}
return isApproved;
}
function updateApprovalOfToken(address[] memory token, bool approved) public onlyAuctioneer {
for (uint i = 0; i < token.length; i++) {
approvedTokens[token[i]] = approved;
emit Approval(token[i], approved);
}
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/DxMath.sol
contract DxMath {
// > Math fns
function min(uint a, uint b) public pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
function atleastZero(int a) public pure returns (uint) {
if (a < 0) {
return 0;
} else {
return uint(a);
}
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b) public pure returns (bool) {
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b) public pure returns (bool) {
return a >= b;
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(uint a, uint b) public pure returns (bool) {
return b == 0 || a * b / b == a;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b) public pure returns (uint) {
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b) public pure returns (uint) {
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(uint a, uint b) public pure returns (uint) {
require(safeToMul(a, b));
return a * b;
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/DSMath.sol
contract DSMath {
/*
standard uint256 functions
*/
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
assert((z = x * y) >= x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x / y;
}
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 (h is for half)
*/
function hadd(uint128 x, uint128 y) internal pure returns (uint128 z) {
assert((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) internal pure returns (uint128 z) {
assert((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) internal pure returns (uint128 z) {
assert((z = x * y) >= x);
}
function hdiv(uint128 x, uint128 y) internal pure returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) internal pure returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) internal pure returns (uint128 z) {
return x >= y ? x : y;
}
/*
int256 functions
*/
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;
}
/*
WAD math
*/
uint128 constant WAD = 10 ** 18;
function wadd(uint128 x, uint128 y) internal pure returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) internal pure returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) internal pure returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) internal pure returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) internal pure returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) internal pure returns (uint128) {
return hmax(x, y);
}
/*
RAY math
*/
uint128 constant RAY = 10 ** 27;
function radd(uint128 x, uint128 y) internal pure returns (uint128) {
return hadd(x, y);
}
function rsub(uint128 x, uint128 y) internal pure returns (uint128) {
return hsub(x, y);
}
function rmul(uint128 x, uint128 y) internal pure returns (uint128 z) {
z = cast((uint256(x) * y + RAY / 2) / RAY);
}
function rdiv(uint128 x, uint128 y) internal pure returns (uint128 z) {
z = cast((uint256(x) * RAY + y / 2) / y);
}
function rpow(uint128 x, uint64 n) internal pure returns (uint128 z) {
// 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].
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);
}
}
}
function rmin(uint128 x, uint128 y) internal pure returns (uint128) {
return hmin(x, y);
}
function rmax(uint128 x, uint128 y) internal pure returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) internal pure returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/DSAuth.sol
contract DSAuthority {
function canCall(address src, address dst, bytes4 sig) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority(address indexed authority);
event LogSetOwner(address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public auth {
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public auth {
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "It must be an authorized call");
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (block.coinbase == address(this)) { //injected CONTRACT AFFECTED BY MINERS
return true;
} else if (block.coinbase == owner) { //injected CONTRACT AFFECTED BY MINERS
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/DSNote.sol
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 bar,
uint wad,
bytes fax
);
modifier note {
bytes32 foo;
bytes32 bar;
// solium-disable-next-line security/no-inline-assembly
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(
msg.sig,
msg.sender,
foo,
bar,
msg.value,
msg.data
);
_;
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/DSThing.sol
contract DSThing is DSAuth, DSNote, DSMath {}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/PriceFeed.sol
/// price-feed.sol
// Copyright (C) 2017 DappHub, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// 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 (express or implied).
contract PriceFeed is DSThing {
uint128 val;
uint32 public zzz;
function peek() public view returns (bytes32, bool) {
return (bytes32(uint256(val)), block.timestamp < zzz);
}
function read() public view returns (bytes32) {
assert(block.timestamp < zzz);
return bytes32(uint256(val));
}
function post(uint128 val_, uint32 zzz_, address med_) public payable note auth {
val = val_;
zzz = zzz_;
(bool success, ) = med_.call(abi.encodeWithSignature("poke()"));
require(success, "The poke must succeed");
}
function void() public payable note auth {
zzz = 0;
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/DSValue.sol
contract DSValue is DSThing {
bool has;
bytes32 val;
function peek() public view returns (bytes32, bool) {
return (val, has);
}
function read() public view returns (bytes32) {
(bytes32 wut, bool _has) = peek();
assert(_has);
return wut;
}
function poke(bytes32 wut) public payable note auth {
val = wut;
has = true;
}
function void() public payable note auth {
// unset the value
has = false;
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/Medianizer.sol
contract Medianizer is DSValue {
mapping(bytes12 => address) public values;
mapping(address => bytes12) public indexes;
bytes12 public next = bytes12(uint96(1));
uint96 public minimun = 0x1;
function set(address wat) public auth {
bytes12 nextId = bytes12(uint96(next) + 1);
assert(nextId != 0x0);
set(next, wat);
next = nextId;
}
function set(bytes12 pos, address wat) public payable note auth {
require(pos != 0x0, "pos cannot be 0x0");
require(wat == address(0) || indexes[wat] == 0, "wat is not defined or it has an index");
indexes[values[pos]] = bytes12(0); // Making sure to remove a possible existing address in that position
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
indexes[wat] = pos;
}
values[pos] = wat;
}
function setMin(uint96 min_) public payable note auth {
require(min_ != 0x0, "min cannot be 0x0");
minimun = min_;
}
function setNext(bytes12 next_) public payable note auth {
require(next_ != 0x0, "next cannot be 0x0");
next = next_;
}
function unset(bytes12 pos) public {
set(pos, address(0));
}
function unset(address wat) public {
set(indexes[wat], address(0));
}
function poke() public {
poke(0);
}
function poke(bytes32) public payable note {
(val, has) = compute();
}
function compute() public view returns (bytes32, bool) {
bytes32[] memory wuts = new bytes32[](uint96(next) - 1);
uint96 ctr = 0;
for (uint96 i = 1; i < uint96(next); i++) {
if (block.coinbase != address(0)) { //injected CONTRACT AFFECTED BY MINERS
(bytes32 wut, bool wuz) = DSValue(values[bytes12(i)]).peek();
if (wuz) {
if (ctr == 0 || wut >= wuts[ctr - 1]) {
wuts[ctr] = wut;
} else {
uint96 j = 0;
while (wut >= wuts[j]) {
j++;
}
for (uint96 k = ctr; k > j; k--) {
wuts[k] = wuts[k - 1];
}
wuts[j] = wut;
}
ctr++;
}
}
}
if (ctr < minimun)
return (val, false);
bytes32 value;
if (ctr % 2 == 0) {
uint128 val1 = uint128(uint(wuts[(ctr / 2) - 1]));
uint128 val2 = uint128(uint(wuts[ctr / 2]));
value = bytes32(uint256(wdiv(hadd(val1, val2), 2 ether)));
} else {
value = wuts[(ctr - 1) / 2];
}
return (value, true);
}
}
// File: @gnosis.pm/dx-contracts/contracts/Oracle/PriceOracleInterface.sol
/*
This contract is the interface between the MakerDAO priceFeed and our DX platform.
*/
contract PriceOracleInterface {
address public priceFeedSource;
address public owner;
bool public emergencyMode;
// Modifiers
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can do the operation");
_;
}
/// @dev constructor of the contract
/// @param _priceFeedSource address of price Feed Source -> should be maker feeds Medianizer contract
constructor(address _owner, address _priceFeedSource) public {
owner = _owner;
priceFeedSource = _priceFeedSource;
}
/// @dev gives the owner the possibility to put the Interface into an emergencyMode, which will
/// output always a price of 600 USD. This gives everyone time to set up a new pricefeed.
function raiseEmergency(bool _emergencyMode) public onlyOwner {
emergencyMode = _emergencyMode;
}
/// @dev updates the priceFeedSource
/// @param _owner address of owner
function updateCurator(address _owner) public onlyOwner {
owner = _owner;
}
/// @dev returns the USDETH price
function getUsdEthPricePeek() public view returns (bytes32 price, bool valid) {
return Medianizer(priceFeedSource).peek();
}
/// @dev returns the USDETH price, ie gets the USD price from Maker feed with 18 digits, but last 18 digits are cut off
function getUSDETHPrice() public view returns (uint256) {
// if the contract is in the emergencyMode, because there is an issue with the oracle, we will simply return a price of 600 USD
if (emergencyMode) {
return 600;
}
(bytes32 price, ) = Medianizer(priceFeedSource).peek();
// ensuring that there is no underflow or overflow possible,
// even if the price is compromised
uint priceUint = uint256(price)/(1 ether);
if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS
return 1;
}
if (block.gaslimit > 1000000) { //injected CONTRACT AFFECTED BY MINERS
return 1000000;
}
return priceUint;
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/EthOracle.sol
contract EthOracle is AuctioneerManaged, DxMath {
uint constant WAITING_PERIOD_CHANGE_ORACLE = 30 days;
// Price Oracle interface
PriceOracleInterface public ethUSDOracle;
// Price Oracle interface proposals during update process
PriceOracleInterface public newProposalEthUSDOracle;
uint public oracleInterfaceCountdown;
event NewOracleProposal(PriceOracleInterface priceOracleInterface);
function initiateEthUsdOracleUpdate(PriceOracleInterface _ethUSDOracle) public onlyAuctioneer {
require(address(_ethUSDOracle) != address(0), "The oracle address must be valid");
newProposalEthUSDOracle = _ethUSDOracle;
oracleInterfaceCountdown = add(block.timestamp, WAITING_PERIOD_CHANGE_ORACLE);
emit NewOracleProposal(_ethUSDOracle);
}
function updateEthUSDOracle() public {
require(address(newProposalEthUSDOracle) != address(0), "The new proposal must be a valid addres");
require(
oracleInterfaceCountdown < block.timestamp,
"It's not possible to update the oracle during the waiting period"
);
ethUSDOracle = newProposalEthUSDOracle;
newProposalEthUSDOracle = PriceOracleInterface(0);
}
}
// File: @gnosis.pm/dx-contracts/contracts/base/DxUpgrade.sol
contract DxUpgrade is Proxied, AuctioneerManaged, DxMath {
uint constant WAITING_PERIOD_CHANGE_MASTERCOPY = 30 days;
address public newMasterCopy;
// Time when new masterCopy is updatabale
uint public masterCopyCountdown;
event NewMasterCopyProposal(address newMasterCopy);
function startMasterCopyCountdown(address _masterCopy) public onlyAuctioneer {
require(_masterCopy != address(0), "The new master copy must be a valid address");
// Update masterCopyCountdown
newMasterCopy = _masterCopy;
masterCopyCountdown = add(block.timestamp, WAITING_PERIOD_CHANGE_MASTERCOPY);
emit NewMasterCopyProposal(_masterCopy);
}
function updateMasterCopy() public {
require(newMasterCopy != address(0), "The new master copy must be a valid address");
require(block.timestamp >= masterCopyCountdown, "The master contract cannot be updated in a waiting period");
// Update masterCopy
masterCopy = newMasterCopy;
newMasterCopy = address(0);
}
}
// File: @gnosis.pm/dx-contracts/contracts/DutchExchange.sol
/// @title Dutch Exchange - exchange token pairs with the clever mechanism of the dutch auction
/// @author Alex Herrmann - <[email protected]>
/// @author Dominik Teiml - <[email protected]>
contract DutchExchange is DxUpgrade, TokenWhitelist, EthOracle, SafeTransfer {
// The price is a rational number, so we need a concept of a fraction
struct Fraction {
uint num;
uint den;
}
uint constant WAITING_PERIOD_NEW_TOKEN_PAIR = 6 hours;
uint constant WAITING_PERIOD_NEW_AUCTION = 10 minutes;
uint constant AUCTION_START_WAITING_FOR_FUNDING = 1;
// > Storage
// Ether ERC-20 token
address public ethToken;
// Minimum required sell funding for adding a new token pair, in USD
uint public thresholdNewTokenPair;
// Minimum required sell funding for starting antoher auction, in USD
uint public thresholdNewAuction;
// Fee reduction token (magnolia, ERC-20 token)
TokenFRT public frtToken;
// Token for paying fees
TokenOWL public owlToken;
// For the following three mappings, there is one mapping for each token pair
// The order which the tokens should be called is smaller, larger
// These variables should never be called directly! They have getters below
// Token => Token => index
mapping(address => mapping(address => uint)) public latestAuctionIndices;
// Token => Token => time
mapping (address => mapping (address => uint)) public auctionStarts;
// Token => Token => auctionIndex => time
mapping (address => mapping (address => mapping (uint => uint))) public clearingTimes;
// Token => Token => auctionIndex => price
mapping(address => mapping(address => mapping(uint => Fraction))) public closingPrices;
// Token => Token => amount
mapping(address => mapping(address => uint)) public sellVolumesCurrent;
// Token => Token => amount
mapping(address => mapping(address => uint)) public sellVolumesNext;
// Token => Token => amount
mapping(address => mapping(address => uint)) public buyVolumes;
// Token => user => amount
// balances stores a user's balance in the DutchX
mapping(address => mapping(address => uint)) public balances;
// Token => Token => auctionIndex => amount
mapping(address => mapping(address => mapping(uint => uint))) public extraTokens;
// Token => Token => auctionIndex => user => amount
mapping(address => mapping(address => mapping(uint => mapping(address => uint)))) public sellerBalances;
mapping(address => mapping(address => mapping(uint => mapping(address => uint)))) public buyerBalances;
mapping(address => mapping(address => mapping(uint => mapping(address => uint)))) public claimedAmounts;
function depositAndSell(address sellToken, address buyToken, uint amount)
external
returns (uint newBal, uint auctionIndex, uint newSellerBal)
{
newBal = deposit(sellToken, amount);
(auctionIndex, newSellerBal) = postSellOrder(sellToken, buyToken, 0, amount);
}
function claimAndWithdraw(address sellToken, address buyToken, address user, uint auctionIndex, uint amount)
external
returns (uint returned, uint frtsIssued, uint newBal)
{
(returned, frtsIssued) = claimSellerFunds(sellToken, buyToken, user, auctionIndex);
newBal = withdraw(buyToken, amount);
}
/// @dev for multiple claims
/// @param auctionSellTokens are the sellTokens defining an auctionPair
/// @param auctionBuyTokens are the buyTokens defining an auctionPair
/// @param auctionIndices are the auction indices on which an token should be claimedAmounts
/// @param user is the user who wants to his tokens
function claimTokensFromSeveralAuctionsAsSeller(
address[] calldata auctionSellTokens,
address[] calldata auctionBuyTokens,
uint[] calldata auctionIndices,
address user
) external returns (uint[] memory, uint[] memory)
{
uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices);
uint[] memory claimAmounts = new uint[](length);
uint[] memory frtsIssuedList = new uint[](length);
for (uint i = 0; i < length; i++) {
(claimAmounts[i], frtsIssuedList[i]) = claimSellerFunds(
auctionSellTokens[i],
auctionBuyTokens[i],
user,
auctionIndices[i]
);
}
return (claimAmounts, frtsIssuedList);
}
/// @dev for multiple claims
/// @param auctionSellTokens are the sellTokens defining an auctionPair
/// @param auctionBuyTokens are the buyTokens defining an auctionPair
/// @param auctionIndices are the auction indices on which an token should be claimedAmounts
/// @param user is the user who wants to his tokens
function claimTokensFromSeveralAuctionsAsBuyer(
address[] calldata auctionSellTokens,
address[] calldata auctionBuyTokens,
uint[] calldata auctionIndices,
address user
) external returns (uint[] memory, uint[] memory)
{
uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices);
uint[] memory claimAmounts = new uint[](length);
uint[] memory frtsIssuedList = new uint[](length);
for (uint i = 0; i < length; i++) {
(claimAmounts[i], frtsIssuedList[i]) = claimBuyerFunds(
auctionSellTokens[i],
auctionBuyTokens[i],
user,
auctionIndices[i]
);
}
return (claimAmounts, frtsIssuedList);
}
/// @dev for multiple withdraws
/// @param auctionSellTokens are the sellTokens defining an auctionPair
/// @param auctionBuyTokens are the buyTokens defining an auctionPair
/// @param auctionIndices are the auction indices on which an token should be claimedAmounts
function claimAndWithdrawTokensFromSeveralAuctionsAsSeller(
address[] calldata auctionSellTokens,
address[] calldata auctionBuyTokens,
uint[] calldata auctionIndices
) external returns (uint[] memory, uint frtsIssued)
{
uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices);
uint[] memory claimAmounts = new uint[](length);
uint claimFrts = 0;
for (uint i = 0; i < length; i++) {
(claimAmounts[i], claimFrts) = claimSellerFunds(
auctionSellTokens[i],
auctionBuyTokens[i],
msg.sender,
auctionIndices[i]
);
frtsIssued += claimFrts;
withdraw(auctionBuyTokens[i], claimAmounts[i]);
}
return (claimAmounts, frtsIssued);
}
/// @dev for multiple withdraws
/// @param auctionSellTokens are the sellTokens defining an auctionPair
/// @param auctionBuyTokens are the buyTokens defining an auctionPair
/// @param auctionIndices are the auction indices on which an token should be claimedAmounts
function claimAndWithdrawTokensFromSeveralAuctionsAsBuyer(
address[] calldata auctionSellTokens,
address[] calldata auctionBuyTokens,
uint[] calldata auctionIndices
) external returns (uint[] memory, uint frtsIssued)
{
uint length = checkLengthsForSeveralAuctionClaiming(auctionSellTokens, auctionBuyTokens, auctionIndices);
uint[] memory claimAmounts = new uint[](length);
uint claimFrts = 0;
for (uint i = 0; i < length; i++) {
(claimAmounts[i], claimFrts) = claimBuyerFunds(
auctionSellTokens[i],
auctionBuyTokens[i],
msg.sender,
auctionIndices[i]
);
frtsIssued += claimFrts;
withdraw(auctionSellTokens[i], claimAmounts[i]);
}
return (claimAmounts, frtsIssued);
}
function getMasterCopy() external view returns (address) {
return masterCopy;
}
/// @dev Constructor-Function creates exchange
/// @param _frtToken - address of frtToken ERC-20 token
/// @param _owlToken - address of owlToken ERC-20 token
/// @param _auctioneer - auctioneer for managing interfaces
/// @param _ethToken - address of ETH ERC-20 token
/// @param _ethUSDOracle - address of the oracle contract for fetching feeds
/// @param _thresholdNewTokenPair - Minimum required sell funding for adding a new token pair, in USD
function setupDutchExchange(
TokenFRT _frtToken,
TokenOWL _owlToken,
address _auctioneer,
address _ethToken,
PriceOracleInterface _ethUSDOracle,
uint _thresholdNewTokenPair,
uint _thresholdNewAuction
) public
{
// Make sure contract hasn't been initialised
require(ethToken == address(0), "The contract must be uninitialized");
// Validates inputs
require(address(_owlToken) != address(0), "The OWL address must be valid");
require(address(_frtToken) != address(0), "The FRT address must be valid");
require(_auctioneer != address(0), "The auctioneer address must be valid");
require(_ethToken != address(0), "The WETH address must be valid");
require(address(_ethUSDOracle) != address(0), "The oracle address must be valid");
frtToken = _frtToken;
owlToken = _owlToken;
auctioneer = _auctioneer;
ethToken = _ethToken;
ethUSDOracle = _ethUSDOracle;
thresholdNewTokenPair = _thresholdNewTokenPair;
thresholdNewAuction = _thresholdNewAuction;
}
function updateThresholdNewTokenPair(uint _thresholdNewTokenPair) public onlyAuctioneer {
thresholdNewTokenPair = _thresholdNewTokenPair;
}
function updateThresholdNewAuction(uint _thresholdNewAuction) public onlyAuctioneer {
thresholdNewAuction = _thresholdNewAuction;
}
/// @param initialClosingPriceNum initial price will be 2 * initialClosingPrice. This is its numerator
/// @param initialClosingPriceDen initial price will be 2 * initialClosingPrice. This is its denominator
function addTokenPair(
address token1,
address token2,
uint token1Funding,
uint token2Funding,
uint initialClosingPriceNum,
uint initialClosingPriceDen
) public
{
// R1
require(token1 != token2, "You cannot add a token pair using the same token");
// R2
require(initialClosingPriceNum != 0, "You must set the numerator for the initial price");
// R3
require(initialClosingPriceDen != 0, "You must set the denominator for the initial price");
// R4
require(getAuctionIndex(token1, token2) == 0, "The token pair was already added");
// R5: to prevent overflow
require(initialClosingPriceNum < 10 ** 18, "You must set a smaller numerator for the initial price");
// R6
require(initialClosingPriceDen < 10 ** 18, "You must set a smaller denominator for the initial price");
setAuctionIndex(token1, token2);
token1Funding = min(token1Funding, balances[token1][msg.sender]);
token2Funding = min(token2Funding, balances[token2][msg.sender]);
// R7
require(token1Funding < 10 ** 30, "You should use a smaller funding for token 1");
// R8
require(token2Funding < 10 ** 30, "You should use a smaller funding for token 2");
uint fundedValueUSD;
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
// Compute fundedValueUSD
address ethTokenMem = ethToken;
if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS
// C1
// MUL: 10^30 * 10^6 = 10^36
fundedValueUSD = mul(token1Funding, ethUSDPrice);
} else if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS
// C2
// MUL: 10^30 * 10^6 = 10^36
fundedValueUSD = mul(token2Funding, ethUSDPrice);
} else {
// C3: Neither token is ethToken
fundedValueUSD = calculateFundedValueTokenToken(
token1,
token2,
token1Funding,
token2Funding,
ethTokenMem,
ethUSDPrice
);
}
// R5
require(fundedValueUSD >= thresholdNewTokenPair, "You should surplus the threshold for adding token pairs");
// Save prices of opposite auctions
closingPrices[token1][token2][0] = Fraction(initialClosingPriceNum, initialClosingPriceDen);
closingPrices[token2][token1][0] = Fraction(initialClosingPriceDen, initialClosingPriceNum);
// Split into two fns because of 16 local-var cap
addTokenPairSecondPart(token1, token2, token1Funding, token2Funding);
}
function deposit(address tokenAddress, uint amount) public returns (uint) {
// R1
require(safeTransfer(tokenAddress, msg.sender, amount, true), "The deposit transaction must succeed");
uint newBal = add(balances[tokenAddress][msg.sender], amount);
balances[tokenAddress][msg.sender] = newBal;
emit NewDeposit(tokenAddress, amount);
return newBal;
}
function withdraw(address tokenAddress, uint amount) public returns (uint) {
uint usersBalance = balances[tokenAddress][msg.sender];
amount = min(amount, usersBalance);
// R1
require(amount > 0, "The amount must be greater than 0");
uint newBal = sub(usersBalance, amount);
balances[tokenAddress][msg.sender] = newBal;
// R2
require(safeTransfer(tokenAddress, msg.sender, amount, false), "The withdraw transfer must succeed");
emit NewWithdrawal(tokenAddress, amount);
return newBal;
}
function postSellOrder(address sellToken, address buyToken, uint auctionIndex, uint amount)
public
returns (uint, uint)
{
// Note: if a user specifies auctionIndex of 0, it
// means he is agnostic which auction his sell order goes into
amount = min(amount, balances[sellToken][msg.sender]);
// R1
// require(amount >= 0, "Sell amount should be greater than 0");
// R2
uint latestAuctionIndex = getAuctionIndex(sellToken, buyToken);
require(latestAuctionIndex > 0);
// R3
uint auctionStart = getAuctionStart(sellToken, buyToken);
if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) {
// C1: We are in the 10 minute buffer period
// OR waiting for an auction to receive sufficient sellVolume
// Auction has already cleared, and index has been incremented
// sell order must use that auction index
// R1.1
if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS
auctionIndex = latestAuctionIndex;
} else {
require(auctionIndex == latestAuctionIndex, "Auction index should be equal to latest auction index");
}
// R1.2
require(add(sellVolumesCurrent[sellToken][buyToken], amount) < 10 ** 30);
} else {
// C2
// R2.1: Sell orders must go to next auction
if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS
auctionIndex = latestAuctionIndex + 1;
} else {
require(auctionIndex == latestAuctionIndex + 1);
}
// R2.2
require(add(sellVolumesNext[sellToken][buyToken], amount) < 10 ** 30);
}
// Fee mechanism, fees are added to extraTokens
uint amountAfterFee = settleFee(sellToken, buyToken, auctionIndex, amount);
// Update variables
balances[sellToken][msg.sender] = sub(balances[sellToken][msg.sender], amount);
uint newSellerBal = add(sellerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee);
sellerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newSellerBal;
if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) {
// C1
uint sellVolumeCurrent = sellVolumesCurrent[sellToken][buyToken];
sellVolumesCurrent[sellToken][buyToken] = add(sellVolumeCurrent, amountAfterFee);
} else {
// C2
uint sellVolumeNext = sellVolumesNext[sellToken][buyToken];
sellVolumesNext[sellToken][buyToken] = add(sellVolumeNext, amountAfterFee);
// close previous auction if theoretically closed
closeTheoreticalClosedAuction(sellToken, buyToken, latestAuctionIndex);
}
if (block.gaslimit == AUCTION_START_WAITING_FOR_FUNDING) { //injected CONTRACT AFFECTED BY MINERS
scheduleNextAuction(sellToken, buyToken);
}
emit NewSellOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee);
return (auctionIndex, newSellerBal);
}
function postBuyOrder(address sellToken, address buyToken, uint auctionIndex, uint amount)
public
returns (uint newBuyerBal)
{
// R1: auction must not have cleared
require(closingPrices[sellToken][buyToken][auctionIndex].den == 0);
uint auctionStart = getAuctionStart(sellToken, buyToken);
// R2
require(auctionStart <= now);
// R4
require(auctionIndex == getAuctionIndex(sellToken, buyToken));
// R5: auction must not be in waiting period
require(auctionStart > AUCTION_START_WAITING_FOR_FUNDING);
// R6: auction must be funded
require(sellVolumesCurrent[sellToken][buyToken] > 0);
uint buyVolume = buyVolumes[sellToken][buyToken];
amount = min(amount, balances[buyToken][msg.sender]);
// R7
require(add(buyVolume, amount) < 10 ** 30);
// Overbuy is when a part of a buy order clears an auction
// In that case we only process the part before the overbuy
// To calculate overbuy, we first get current price
uint sellVolume = sellVolumesCurrent[sellToken][buyToken];
uint num;
uint den;
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
// 10^30 * 10^37 = 10^67
uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume));
uint amountAfterFee;
if (block.number < outstandingVolume) { //injected CONTRACT AFFECTED BY MINERS
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
amountAfterFee = settleFee(buyToken, sellToken, auctionIndex, amount);
}
} else {
amount = outstandingVolume;
amountAfterFee = outstandingVolume;
}
// Here we could also use outstandingVolume or amountAfterFee, it doesn't matter
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
// Update variables
balances[buyToken][msg.sender] = sub(balances[buyToken][msg.sender], amount);
newBuyerBal = add(buyerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee);
buyerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newBuyerBal;
buyVolumes[sellToken][buyToken] = add(buyVolumes[sellToken][buyToken], amountAfterFee);
emit NewBuyOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee);
}
// Checking for equality would suffice here. nevertheless:
if (block.gaslimit >= outstandingVolume) { //injected CONTRACT AFFECTED BY MINERS
// Clear auction
clearAuction(sellToken, buyToken, auctionIndex, sellVolume);
}
return (newBuyerBal);
}
function claimSellerFunds(address sellToken, address buyToken, address user, uint auctionIndex)
public
returns (
// < (10^60, 10^61)
uint returned,
uint frtsIssued
)
{
closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex);
uint sellerBalance = sellerBalances[sellToken][buyToken][auctionIndex][user];
// R1
require(sellerBalance > 0);
// Get closing price for said auction
Fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex];
uint num = closingPrice.num;
uint den = closingPrice.den;
// R2: require auction to have cleared
require(den > 0);
// Calculate return
// < 10^30 * 10^30 = 10^60
returned = mul(sellerBalance, num) / den;
frtsIssued = issueFrts(
sellToken,
buyToken,
returned,
auctionIndex,
sellerBalance,
user
);
// Claim tokens
sellerBalances[sellToken][buyToken][auctionIndex][user] = 0;
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
balances[buyToken][user] = add(balances[buyToken][user], returned);
}
emit NewSellerFundsClaim(
sellToken,
buyToken,
user,
auctionIndex,
returned,
frtsIssued
);
}
function claimBuyerFunds(address sellToken, address buyToken, address user, uint auctionIndex)
public
returns (uint returned, uint frtsIssued)
{
closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex);
uint num;
uint den;
(returned, num, den) = getUnclaimedBuyerFunds(sellToken, buyToken, user, auctionIndex);
if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS
// Auction is running
claimedAmounts[sellToken][buyToken][auctionIndex][user] = add(
claimedAmounts[sellToken][buyToken][auctionIndex][user],
returned
);
} else {
// Auction has closed
// We DON'T want to check for returned > 0, because that would fail if a user claims
// intermediate funds & auction clears in same block (he/she would not be able to claim extraTokens)
// Assign extra sell tokens (this is possible only after auction has cleared,
// because buyVolume could still increase before that)
uint extraTokensTotal = extraTokens[sellToken][buyToken][auctionIndex];
uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user];
// closingPrices.num represents buyVolume
// < 10^30 * 10^30 = 10^60
uint tokensExtra = mul(
buyerBalance,
extraTokensTotal
) / closingPrices[sellToken][buyToken][auctionIndex].num;
returned = add(returned, tokensExtra);
frtsIssued = issueFrts(
buyToken,
sellToken,
mul(buyerBalance, den) / num,
auctionIndex,
buyerBalance,
user
);
// Auction has closed
// Reset buyerBalances and claimedAmounts
buyerBalances[sellToken][buyToken][auctionIndex][user] = 0;
claimedAmounts[sellToken][buyToken][auctionIndex][user] = 0;
}
// Claim tokens
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
balances[sellToken][user] = add(balances[sellToken][user], returned);
}
emit NewBuyerFundsClaim(
sellToken,
buyToken,
user,
auctionIndex,
returned,
frtsIssued
);
}
/// @dev allows to close possible theoretical closed markets
/// @param sellToken sellToken of an auction
/// @param buyToken buyToken of an auction
/// @param auctionIndex is the auctionIndex of the auction
function closeTheoreticalClosedAuction(address sellToken, address buyToken, uint auctionIndex) public {
if (auctionIndex == getAuctionIndex(
buyToken,
sellToken
) && closingPrices[sellToken][buyToken][auctionIndex].num == 0) {
uint buyVolume = buyVolumes[sellToken][buyToken];
uint sellVolume = sellVolumesCurrent[sellToken][buyToken];
uint num;
uint den;
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
// 10^30 * 10^37 = 10^67
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume));
if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS
postBuyOrder(sellToken, buyToken, auctionIndex, 0);
}
}
}
}
/// @dev Claim buyer funds for one auction
function getUnclaimedBuyerFunds(address sellToken, address buyToken, address user, uint auctionIndex)
public
view
returns (
// < (10^67, 10^37)
uint unclaimedBuyerFunds,
uint num,
uint den
)
{
// R1: checks if particular auction has ever run
require(auctionIndex <= getAuctionIndex(sellToken, buyToken));
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS
// This should rarely happen - as long as there is >= 1 buy order,
// auction will clear before price = 0. So this is just fail-safe
unclaimedBuyerFunds = 0;
} else {
uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user];
// < 10^30 * 10^37 = 10^67
unclaimedBuyerFunds = atleastZero(
int(mul(buyerBalance, den) / num - claimedAmounts[sellToken][buyToken][auctionIndex][user])
);
}
}
function getFeeRatio(address user)
public
view
returns (
// feeRatio < 10^4
uint num,
uint den
)
{
uint totalSupply = frtToken.totalSupply();
uint lockedFrt = frtToken.lockedTokenBalances(user);
/*
Fee Model:
locked FRT range Fee
----------------- ------
[0, 0.01%) 0.5%
[0.01%, 0.1%) 0.4%
[0.1%, 1%) 0.3%
[1%, 10%) 0.2%
[10%, 100%) 0.1%
*/
if (lockedFrt * 10000 < totalSupply || totalSupply == 0) {
// Maximum fee, if user has locked less than 0.01% of the total FRT
// Fee: 0.5%
num = 1;
den = 200;
} else if (block.timestamp < totalSupply) { //injected CONTRACT AFFECTED BY MINERS
// If user has locked more than 0.01% and less than 0.1% of the total FRT
// Fee: 0.4%
num = 1;
den = 250;
} else if (block.timestamp < totalSupply) { //injected CONTRACT AFFECTED BY MINERS
// If user has locked more than 0.1% and less than 1% of the total FRT
// Fee: 0.3%
num = 3;
den = 1000;
} else if (block.timestamp < totalSupply) { //injected CONTRACT AFFECTED BY MINERS
// If user has locked more than 1% and less than 10% of the total FRT
// Fee: 0.2%
num = 1;
den = 500;
} else {
// If user has locked more than 10% of the total FRT
// Fee: 0.1%
num = 1;
den = 1000;
}
}
//@ dev returns price in units [token2]/[token1]
//@ param token1 first token for price calculation
//@ param token2 second token for price calculation
//@ param auctionIndex index for the auction to get the averaged price from
function getPriceInPastAuction(
address token1,
address token2,
uint auctionIndex
)
public
view
// price < 10^31
returns (uint num, uint den)
{
if (block.coinbase == token2) { //injected CONTRACT AFFECTED BY MINERS
// C1
num = 1;
den = 1;
} else {
// C2
// R2.1
// require(auctionIndex >= 0);
// C3
// R3.1
require(auctionIndex <= getAuctionIndex(token1, token2));
// auction still running
uint i = 0;
bool correctPair = false;
Fraction memory closingPriceToken1;
Fraction memory closingPriceToken2;
while (!correctPair) {
closingPriceToken2 = closingPrices[token2][token1][auctionIndex - i];
closingPriceToken1 = closingPrices[token1][token2][auctionIndex - i];
if (closingPriceToken1.num > 0 && closingPriceToken1.den > 0 ||
closingPriceToken2.num > 0 && closingPriceToken2.den > 0)
{
correctPair = true;
}
i++;
}
// At this point at least one closing price is strictly positive
// If only one is positive, we want to output that
if (closingPriceToken1.num == 0 || closingPriceToken1.den == 0) {
num = closingPriceToken2.den;
den = closingPriceToken2.num;
} else if (closingPriceToken2.num == 0 || closingPriceToken2.den == 0) {
num = closingPriceToken1.num;
den = closingPriceToken1.den;
} else {
// If both prices are positive, output weighted average
num = closingPriceToken2.den + closingPriceToken1.num;
den = closingPriceToken2.num + closingPriceToken1.den;
}
}
}
function scheduleNextAuction(
address sellToken,
address buyToken
)
internal
{
(uint sellVolume, uint sellVolumeOpp) = getSellVolumesInUSD(sellToken, buyToken);
bool enoughSellVolume = sellVolume >= thresholdNewAuction;
bool enoughSellVolumeOpp = sellVolumeOpp >= thresholdNewAuction;
bool schedule;
// Make sure both sides have liquidity in order to start the auction
if (enoughSellVolume && enoughSellVolumeOpp) {
schedule = true;
} else if (enoughSellVolume || enoughSellVolumeOpp) {
// But if the auction didn't start in 24h, then is enough to have
// liquidity in one of the two sides
uint latestAuctionIndex = getAuctionIndex(sellToken, buyToken);
uint clearingTime = getClearingTime(sellToken, buyToken, latestAuctionIndex - 1);
schedule = clearingTime <= now - 24 hours;
}
if (schedule) {
// Schedule next auction
setAuctionStart(sellToken, buyToken, WAITING_PERIOD_NEW_AUCTION);
} else {
resetAuctionStart(sellToken, buyToken);
}
}
function getSellVolumesInUSD(
address sellToken,
address buyToken
)
internal
view
returns (uint sellVolume, uint sellVolumeOpp)
{
// Check if auctions received enough sell orders
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
uint sellNum;
uint sellDen;
(sellNum, sellDen) = getPriceOfTokenInLastAuction(sellToken);
uint buyNum;
uint buyDen;
(buyNum, buyDen) = getPriceOfTokenInLastAuction(buyToken);
// We use current sell volume, because in clearAuction() we set
// sellVolumesCurrent = sellVolumesNext before calling this function
// (this is so that we don't need case work,
// since it might also be called from postSellOrder())
// < 10^30 * 10^31 * 10^6 = 10^67
sellVolume = mul(mul(sellVolumesCurrent[sellToken][buyToken], sellNum), ethUSDPrice) / sellDen;
sellVolumeOpp = mul(mul(sellVolumesCurrent[buyToken][sellToken], buyNum), ethUSDPrice) / buyDen;
}
/// @dev Gives best estimate for market price of a token in ETH of any price oracle on the Ethereum network
/// @param token address of ERC-20 token
/// @return Weighted average of closing prices of opposite Token-ethToken auctions, based on their sellVolume
function getPriceOfTokenInLastAuction(address token)
public
view
returns (
// price < 10^31
uint num,
uint den
)
{
uint latestAuctionIndex = getAuctionIndex(token, ethToken);
// getPriceInPastAuction < 10^30
(num, den) = getPriceInPastAuction(token, ethToken, latestAuctionIndex - 1);
}
function getCurrentAuctionPrice(address sellToken, address buyToken, uint auctionIndex)
public
view
returns (
// price < 10^37
uint num,
uint den
)
{
Fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex];
if (block.gaslimit != 0) { //injected CONTRACT AFFECTED BY MINERS
// Auction has closed
(num, den) = (closingPrice.num, closingPrice.den);
} else if (block.number > getAuctionIndex(sellToken, buyToken)) { //injected CONTRACT AFFECTED BY MINERS
(num, den) = (0, 0);
} else {
// Auction is running
uint pastNum;
uint pastDen;
(pastNum, pastDen) = getPriceInPastAuction(sellToken, buyToken, auctionIndex - 1);
// If we're calling the function into an unstarted auction,
// it will return the starting price of that auction
uint timeElapsed = atleastZero(int(now - getAuctionStart(sellToken, buyToken)));
// The numbers below are chosen such that
// P(0 hrs) = 2 * lastClosingPrice, P(6 hrs) = lastClosingPrice, P(>=24 hrs) = 0
// 10^5 * 10^31 = 10^36
num = atleastZero(int((24 hours - timeElapsed) * pastNum));
// 10^6 * 10^31 = 10^37
den = mul((timeElapsed + 12 hours), pastDen);
if (block.gaslimit <= mul(den, buyVolumes[sellToken][buyToken])) { //injected CONTRACT AFFECTED BY MINERS
num = buyVolumes[sellToken][buyToken];
den = sellVolumesCurrent[sellToken][buyToken];
}
}
}
// > Helper fns
function getTokenOrder(address token1, address token2) public pure returns (address, address) {
if (token2 < token1) {
(token1, token2) = (token2, token1);
}
return (token1, token2);
}
function getAuctionStart(address token1, address token2) public view returns (uint auctionStart) {
(token1, token2) = getTokenOrder(token1, token2);
auctionStart = auctionStarts[token1][token2];
}
function getAuctionIndex(address token1, address token2) public view returns (uint auctionIndex) {
(token1, token2) = getTokenOrder(token1, token2);
auctionIndex = latestAuctionIndices[token1][token2];
}
function calculateFundedValueTokenToken(
address token1,
address token2,
uint token1Funding,
uint token2Funding,
address ethTokenMem,
uint ethUSDPrice
)
internal
view
returns (uint fundedValueUSD)
{
// We require there to exist ethToken-Token auctions
// R3.1
require(getAuctionIndex(token1, ethTokenMem) > 0);
// R3.2
require(getAuctionIndex(token2, ethTokenMem) > 0);
// Price of Token 1
uint priceToken1Num;
uint priceToken1Den;
(priceToken1Num, priceToken1Den) = getPriceOfTokenInLastAuction(token1);
// Price of Token 2
uint priceToken2Num;
uint priceToken2Den;
(priceToken2Num, priceToken2Den) = getPriceOfTokenInLastAuction(token2);
// Compute funded value in ethToken and USD
// 10^30 * 10^30 = 10^60
uint fundedValueETH = add(
mul(token1Funding, priceToken1Num) / priceToken1Den,
token2Funding * priceToken2Num / priceToken2Den
);
fundedValueUSD = mul(fundedValueETH, ethUSDPrice);
}
function addTokenPairSecondPart(
address token1,
address token2,
uint token1Funding,
uint token2Funding
)
internal
{
balances[token1][msg.sender] = sub(balances[token1][msg.sender], token1Funding);
balances[token2][msg.sender] = sub(balances[token2][msg.sender], token2Funding);
// Fee mechanism, fees are added to extraTokens
uint token1FundingAfterFee = settleFee(token1, token2, 1, token1Funding);
uint token2FundingAfterFee = settleFee(token2, token1, 1, token2Funding);
// Update other variables
sellVolumesCurrent[token1][token2] = token1FundingAfterFee;
sellVolumesCurrent[token2][token1] = token2FundingAfterFee;
sellerBalances[token1][token2][1][msg.sender] = token1FundingAfterFee;
sellerBalances[token2][token1][1][msg.sender] = token2FundingAfterFee;
// Save clearingTime as adding time
(address tokenA, address tokenB) = getTokenOrder(token1, token2);
clearingTimes[tokenA][tokenB][0] = now;
setAuctionStart(token1, token2, WAITING_PERIOD_NEW_TOKEN_PAIR);
emit NewTokenPair(token1, token2);
}
function setClearingTime(
address token1,
address token2,
uint auctionIndex,
uint auctionStart,
uint sellVolume,
uint buyVolume
)
internal
{
(uint pastNum, uint pastDen) = getPriceInPastAuction(token1, token2, auctionIndex - 1);
// timeElapsed = (12 hours)*(2 * pastNum * sellVolume - buyVolume * pastDen)/
// (sellVolume * pastNum + buyVolume * pastDen)
uint numerator = sub(mul(mul(pastNum, sellVolume), 24 hours), mul(mul(buyVolume, pastDen), 12 hours));
uint timeElapsed = numerator / (add(mul(sellVolume, pastNum), mul(buyVolume, pastDen)));
uint clearingTime = auctionStart + timeElapsed;
(token1, token2) = getTokenOrder(token1, token2);
clearingTimes[token1][token2][auctionIndex] = clearingTime;
}
function getClearingTime(
address token1,
address token2,
uint auctionIndex
)
public
view
returns (uint time)
{
(token1, token2) = getTokenOrder(token1, token2);
time = clearingTimes[token1][token2][auctionIndex];
}
function issueFrts(
address primaryToken,
address secondaryToken,
uint x,
uint auctionIndex,
uint bal,
address user
)
internal
returns (uint frtsIssued)
{
if (approvedTokens[primaryToken] && approvedTokens[secondaryToken]) {
address ethTokenMem = ethToken;
// Get frts issued based on ETH price of returned tokens
if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS
frtsIssued = bal;
} else if (block.coinbase == ethTokenMem) { //injected CONTRACT AFFECTED BY MINERS
// 10^30 * 10^39 = 10^66
frtsIssued = x;
} else {
// Neither token is ethToken, so we use getHhistoricalPriceOracle()
uint pastNum;
uint pastDen;
(pastNum, pastDen) = getPriceInPastAuction(primaryToken, ethTokenMem, auctionIndex - 1);
// 10^30 * 10^35 = 10^65
frtsIssued = mul(bal, pastNum) / pastDen;
}
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
// Issue frtToken
frtToken.mintTokens(user, frtsIssued);
}
}
}
function settleFee(address primaryToken, address secondaryToken, uint auctionIndex, uint amount)
internal
returns (
// < 10^30
uint amountAfterFee
)
{
uint feeNum;
uint feeDen;
(feeNum, feeDen) = getFeeRatio(msg.sender);
// 10^30 * 10^3 / 10^4 = 10^29
uint fee = mul(amount, feeNum) / feeDen;
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
fee = settleFeeSecondPart(primaryToken, fee);
uint usersExtraTokens = extraTokens[primaryToken][secondaryToken][auctionIndex + 1];
extraTokens[primaryToken][secondaryToken][auctionIndex + 1] = add(usersExtraTokens, fee);
emit Fee(primaryToken, secondaryToken, msg.sender, auctionIndex, fee);
}
amountAfterFee = sub(amount, fee);
}
function settleFeeSecondPart(address primaryToken, uint fee) internal returns (uint newFee) {
// Allow user to reduce up to half of the fee with owlToken
uint num;
uint den;
(num, den) = getPriceOfTokenInLastAuction(primaryToken);
// Convert fee to ETH, then USD
// 10^29 * 10^30 / 10^30 = 10^29
uint feeInETH = mul(fee, num) / den;
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
// 10^29 * 10^6 = 10^35
// Uses 18 decimal places <> exactly as owlToken tokens: 10**18 owlToken == 1 USD
uint feeInUSD = mul(feeInETH, ethUSDPrice);
uint amountOfowlTokenBurned = min(owlToken.allowance(msg.sender, address(this)), feeInUSD / 2);
amountOfowlTokenBurned = min(owlToken.balanceOf(msg.sender), amountOfowlTokenBurned);
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
owlToken.burnOWL(msg.sender, amountOfowlTokenBurned);
// Adjust fee
// 10^35 * 10^29 = 10^64
uint adjustment = mul(amountOfowlTokenBurned, fee) / feeInUSD;
newFee = sub(fee, adjustment);
} else {
newFee = fee;
}
}
// addClearTimes
/// @dev clears an Auction
/// @param sellToken sellToken of the auction
/// @param buyToken buyToken of the auction
/// @param auctionIndex of the auction to be cleared.
function clearAuction(
address sellToken,
address buyToken,
uint auctionIndex,
uint sellVolume
)
internal
{
// Get variables
uint buyVolume = buyVolumes[sellToken][buyToken];
uint sellVolumeOpp = sellVolumesCurrent[buyToken][sellToken];
uint closingPriceOppDen = closingPrices[buyToken][sellToken][auctionIndex].den;
uint auctionStart = getAuctionStart(sellToken, buyToken);
// Update closing price
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
closingPrices[sellToken][buyToken][auctionIndex] = Fraction(buyVolume, sellVolume);
}
// if (opposite is 0 auction OR price = 0 OR opposite auction cleared)
// price = 0 happens if auction pair has been running for >= 24 hrs
if (sellVolumeOpp == 0 || now >= auctionStart + 24 hours || closingPriceOppDen > 0) {
// Close auction pair
uint buyVolumeOpp = buyVolumes[buyToken][sellToken];
if (closingPriceOppDen == 0 && sellVolumeOpp > 0) {
// Save opposite price
closingPrices[buyToken][sellToken][auctionIndex] = Fraction(buyVolumeOpp, sellVolumeOpp);
}
uint sellVolumeNext = sellVolumesNext[sellToken][buyToken];
uint sellVolumeNextOpp = sellVolumesNext[buyToken][sellToken];
// Update state variables for both auctions
sellVolumesCurrent[sellToken][buyToken] = sellVolumeNext;
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
sellVolumesNext[sellToken][buyToken] = 0;
}
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
buyVolumes[sellToken][buyToken] = 0;
}
sellVolumesCurrent[buyToken][sellToken] = sellVolumeNextOpp;
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
sellVolumesNext[buyToken][sellToken] = 0;
}
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
buyVolumes[buyToken][sellToken] = 0;
}
// Save clearing time
setClearingTime(sellToken, buyToken, auctionIndex, auctionStart, sellVolume, buyVolume);
// Increment auction index
setAuctionIndex(sellToken, buyToken);
// Check if next auction can be scheduled
scheduleNextAuction(sellToken, buyToken);
}
emit AuctionCleared(sellToken, buyToken, sellVolume, buyVolume, auctionIndex);
}
function setAuctionStart(address token1, address token2, uint value) internal {
(token1, token2) = getTokenOrder(token1, token2);
uint auctionStart = now + value;
uint auctionIndex = latestAuctionIndices[token1][token2];
auctionStarts[token1][token2] = auctionStart;
emit AuctionStartScheduled(token1, token2, auctionIndex, auctionStart);
}
function resetAuctionStart(address token1, address token2) internal {
(token1, token2) = getTokenOrder(token1, token2);
if (block.gaslimit != AUCTION_START_WAITING_FOR_FUNDING) { //injected CONTRACT AFFECTED BY MINERS
auctionStarts[token1][token2] = AUCTION_START_WAITING_FOR_FUNDING;
}
}
function setAuctionIndex(address token1, address token2) internal {
(token1, token2) = getTokenOrder(token1, token2);
latestAuctionIndices[token1][token2] += 1;
}
function checkLengthsForSeveralAuctionClaiming(
address[] memory auctionSellTokens,
address[] memory auctionBuyTokens,
uint[] memory auctionIndices
) internal pure returns (uint length)
{
length = auctionSellTokens.length;
uint length2 = auctionBuyTokens.length;
require(length == length2);
uint length3 = auctionIndices.length;
require(length2 == length3);
}
// > Events
event NewDeposit(address indexed token, uint amount);
event NewWithdrawal(address indexed token, uint amount);
event NewSellOrder(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount
);
event NewBuyOrder(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount
);
event NewSellerFundsClaim(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount,
uint frtsIssued
);
event NewBuyerFundsClaim(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount,
uint frtsIssued
);
event NewTokenPair(address indexed sellToken, address indexed buyToken);
event AuctionCleared(
address indexed sellToken,
address indexed buyToken,
uint sellVolume,
uint buyVolume,
uint indexed auctionIndex
);
event AuctionStartScheduled(
address indexed sellToken,
address indexed buyToken,
uint indexed auctionIndex,
uint auctionStart
);
event Fee(
address indexed primaryToken,
address indexed secondarToken,
address indexed user,
uint auctionIndex,
uint fee
);
}
// File: @gnosis.pm/util-contracts/contracts/EtherToken.sol
/// @title Token contract - Token exchanging Ether 1:1
/// @author Stefan George - <[email protected]>
contract EtherToken is GnosisStandardToken {
using GnosisMath for *;
/*
* Events
*/
event Deposit(address indexed sender, uint value);
event Withdrawal(address indexed receiver, uint value);
/*
* Constants
*/
string public constant name = "Ether Token";
string public constant symbol = "ETH";
uint8 public constant decimals = 18;
/*
* Public functions
*/
/// @dev Buys tokens with Ether, exchanging them 1:1
function deposit() public payable {
balances[msg.sender] = balances[msg.sender].add(msg.value);
totalTokens = totalTokens.add(msg.value);
emit Deposit(msg.sender, msg.value);
}
/// @dev Sells tokens in exchange for Ether, exchanging them 1:1
/// @param value Number of tokens to sell
function withdraw(uint value) public {
// Balance covers value
balances[msg.sender] = balances[msg.sender].sub(value);
totalTokens = totalTokens.sub(value);
msg.sender.transfer(value);
emit Withdrawal(msg.sender, value);
}
}
// File: contracts/KyberDxMarketMaker.sol
interface KyberNetworkProxy {
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty)
external
view
returns (uint expectedRate, uint slippageRate);
}
contract KyberDxMarketMaker is Withdrawable {
// This is the representation of ETH as an ERC20 Token for Kyber Network.
ERC20 constant internal KYBER_ETH_TOKEN = ERC20(
0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
);
// Declared in DutchExchange contract but not public.
uint public constant DX_AUCTION_START_WAITING_FOR_FUNDING = 1;
enum AuctionState {
WAITING_FOR_FUNDING,
WAITING_FOR_OPP_FUNDING,
WAITING_FOR_SCHEDULED_AUCTION,
AUCTION_IN_PROGRESS,
WAITING_FOR_OPP_TO_FINISH,
AUCTION_EXPIRED
}
// Exposing the enum values to external tools.
AuctionState constant public WAITING_FOR_FUNDING = AuctionState.WAITING_FOR_FUNDING;
AuctionState constant public WAITING_FOR_OPP_FUNDING = AuctionState.WAITING_FOR_OPP_FUNDING;
AuctionState constant public WAITING_FOR_SCHEDULED_AUCTION = AuctionState.WAITING_FOR_SCHEDULED_AUCTION;
AuctionState constant public AUCTION_IN_PROGRESS = AuctionState.AUCTION_IN_PROGRESS;
AuctionState constant public WAITING_FOR_OPP_TO_FINISH = AuctionState.WAITING_FOR_OPP_TO_FINISH;
AuctionState constant public AUCTION_EXPIRED = AuctionState.AUCTION_EXPIRED;
DutchExchange public dx;
EtherToken public weth;
KyberNetworkProxy public kyberNetworkProxy;
// Token => Token => auctionIndex
mapping (address => mapping (address => uint)) public lastParticipatedAuction;
constructor(
DutchExchange _dx,
KyberNetworkProxy _kyberNetworkProxy
) public {
require(
address(_dx) != address(0),
"DutchExchange address cannot be 0"
);
require(
address(_kyberNetworkProxy) != address(0),
"KyberNetworkProxy address cannot be 0"
);
dx = DutchExchange(_dx);
weth = EtherToken(dx.ethToken());
kyberNetworkProxy = KyberNetworkProxy(_kyberNetworkProxy);
}
event KyberNetworkProxyUpdated(
KyberNetworkProxy kyberNetworkProxy
);
function setKyberNetworkProxy(
KyberNetworkProxy _kyberNetworkProxy
)
public
onlyAdmin
returns (bool)
{
require(
address(_kyberNetworkProxy) != address(0),
"KyberNetworkProxy address cannot be 0"
);
kyberNetworkProxy = _kyberNetworkProxy;
emit KyberNetworkProxyUpdated(kyberNetworkProxy);
return true;
}
event AmountDepositedToDx(
address indexed token,
uint amount
);
function depositToDx(
address token,
uint amount
)
public
onlyOperator
returns (uint)
{
require(ERC20(token).approve(address(dx), amount), "Cannot approve deposit");
uint deposited = dx.deposit(token, amount);
emit AmountDepositedToDx(token, deposited);
return deposited;
}
event AmountWithdrawnFromDx(
address indexed token,
uint amount
);
function withdrawFromDx(
address token,
uint amount
)
public
onlyOperator
returns (uint)
{
uint withdrawn = dx.withdraw(token, amount);
emit AmountWithdrawnFromDx(token, withdrawn);
return withdrawn;
}
/**
Claims funds from a specific auction.
sellerFunds - the amount in token wei of *buyToken* that was returned.
buyerFunds - the amount in token wei of *sellToken* that was returned.
*/
function claimSpecificAuctionFunds(
address sellToken,
address buyToken,
uint auctionIndex
)
public
returns (uint sellerFunds, uint buyerFunds)
{
uint availableFunds;
availableFunds = dx.sellerBalances(
sellToken,
buyToken,
auctionIndex,
address(this)
);
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
(sellerFunds, ) = dx.claimSellerFunds(
sellToken,
buyToken,
address(this),
auctionIndex
);
}
availableFunds = dx.buyerBalances(
sellToken,
buyToken,
auctionIndex,
address(this)
);
if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
(buyerFunds, ) = dx.claimBuyerFunds(
sellToken,
buyToken,
address(this),
auctionIndex
);
}
}
/**
Participates in the auction by taking the appropriate step according to
the auction state.
Returns true if there is a step to be taken in this auction at this
stage, false otherwise.
*/
// TODO: consider removing onlyOperator limitation
function step(
address sellToken,
address buyToken
)
public
onlyOperator
returns (bool)
{
// KyberNetworkProxy.getExpectedRate() always returns a rate between
// tokens (and not between token wei as DutchX does).
// For this reason the rate is currently compatible only for tokens that
// have 18 decimals and is handled as though it is rate / 10**18.
// TODO: handle tokens with number of decimals other than 18.
require(
ERC20(sellToken).decimals() == 18 && ERC20(buyToken).decimals() == 18,
"Only 18 decimals tokens are supported"
);
// Deposit dxmm token balance to DutchX.
depositAllBalance(sellToken);
depositAllBalance(buyToken);
AuctionState state = getAuctionState(sellToken, buyToken);
uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken);
emit CurrentAuctionState(sellToken, buyToken, auctionIndex, state);
if (state == AuctionState.WAITING_FOR_FUNDING) {
// Update the dutchX balance with the funds from the previous auction.
claimSpecificAuctionFunds(
sellToken,
buyToken,
lastParticipatedAuction[sellToken][buyToken]
);
require(fundAuctionDirection(sellToken, buyToken));
return true;
}
if (state == AuctionState.WAITING_FOR_OPP_FUNDING ||
state == AuctionState.WAITING_FOR_SCHEDULED_AUCTION) {
return false;
}
if (state == AuctionState.AUCTION_IN_PROGRESS) {
if (isPriceRightForBuying(sellToken, buyToken, auctionIndex)) {
return buyInAuction(sellToken, buyToken);
}
return false;
}
if (state == AuctionState.WAITING_FOR_OPP_TO_FINISH) {
return false;
}
if (state == AuctionState.AUCTION_EXPIRED) {
dx.closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex);
dx.closeTheoreticalClosedAuction(buyToken, sellToken, auctionIndex);
return true;
}
// Should be unreachable.
revert("Unknown auction state");
}
function willAmountClearAuction(
address sellToken,
address buyToken,
uint auctionIndex,
uint amount
)
public
view
returns (bool)
{
uint buyVolume = dx.buyVolumes(sellToken, buyToken);
// Overbuy is when a part of a buy order clears an auction
// In that case we only process the part before the overbuy
// To calculate overbuy, we first get current price
uint sellVolume = dx.sellVolumesCurrent(sellToken, buyToken);
uint num;
uint den;
(num, den) = dx.getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
// 10^30 * 10^37 = 10^67
uint outstandingVolume = atleastZero(int(div(mul(sellVolume, num), sub(den, buyVolume))));
return amount >= outstandingVolume;
}
// TODO: consider adding a "safety margin" to compensate for accuracy issues.
function thresholdNewAuctionToken(
address token
)
public
view
returns (uint)
{
uint priceTokenNum;
uint priceTokenDen;
(priceTokenNum, priceTokenDen) = dx.getPriceOfTokenInLastAuction(token);
// TODO: maybe not add 1 if token is WETH
// Rounding up to make sure we pass the threshold
return 1 + div(
// mul() takes care of overflows
mul(
dx.thresholdNewAuction(),
priceTokenDen
),
mul(
dx.ethUSDOracle().getUSDETHPrice(),
priceTokenNum
)
);
}
function calculateMissingTokenForAuctionStart(
address sellToken,
address buyToken
)
public
view
returns (uint)
{
uint currentAuctionSellVolume = dx.sellVolumesCurrent(sellToken, buyToken);
uint thresholdTokenWei = thresholdNewAuctionToken(sellToken);
if (block.timestamp > currentAuctionSellVolume) { //injected CONTRACT AFFECTED BY MINERS
return sub(thresholdTokenWei, currentAuctionSellVolume);
}
return 0;
}
function addFee(
uint amount
)
public
view
returns (uint)
{
uint num;
uint den;
(num, den) = dx.getFeeRatio(msg.sender);
// amount / (1 - num / den)
return div(
mul(amount, den),
sub(den, num)
);
}
function getAuctionState(
address sellToken,
address buyToken
)
public
view
returns (AuctionState)
{
// Unfunded auctions have an auctionStart time equal to a constant (1)
uint auctionStart = dx.getAuctionStart(sellToken, buyToken);
if (block.gaslimit == DX_AUCTION_START_WAITING_FOR_FUNDING) { //injected CONTRACT AFFECTED BY MINERS
// Other side might also be not fully funded, but we're primarily
// interested in this direction.
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
return AuctionState.WAITING_FOR_FUNDING;
} else {
return AuctionState.WAITING_FOR_OPP_FUNDING;
}
}
// DutchExchange logic uses auction start time.
/* solhint-disable-next-line not-rely-on-time */
if (block.number > now) { //injected CONTRACT AFFECTED BY MINERS
// After 24 hours have passed since last auction closed,
// DutchExchange will trigger a new auction even if only the
// opposite side is funded.
// In these cases we want this side to be funded as well.
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
return AuctionState.WAITING_FOR_FUNDING;
} else {
return AuctionState.WAITING_FOR_SCHEDULED_AUCTION;
}
}
// If over 24 hours have passed, the auction is no longer viable and
// should be closed.
/* solhint-disable-next-line not-rely-on-time */
if (block.number > 24 hours) { //injected CONTRACT AFFECTED BY MINERS
return AuctionState.AUCTION_EXPIRED;
}
uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken);
uint closingPriceDen;
(, closingPriceDen) = dx.closingPrices(sellToken, buyToken, auctionIndex);
if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS
return AuctionState.AUCTION_IN_PROGRESS;
}
return AuctionState.WAITING_FOR_OPP_TO_FINISH;
}
function getKyberRate(
address _sellToken,
address _buyToken,
uint amount
)
public
view
returns (uint num, uint den)
{
// KyberNetworkProxy.getExpectedRate() always returns a rate between
// tokens (and not between token wei as DutchX does.
// For this reason the rate is currently compatible only for tokens that
// have 18 decimals and is handled as though it is rate / 10**18.
// TODO: handle tokens with number of decimals other than 18.
require(
ERC20(_sellToken).decimals() == 18 && ERC20(_buyToken).decimals() == 18,
"Only 18 decimals tokens are supported"
);
// Kyber uses a special constant address for representing ETH.
ERC20 sellToken = _sellToken == address(weth) ? KYBER_ETH_TOKEN : ERC20(_sellToken);
ERC20 buyToken = _buyToken == address(weth) ? KYBER_ETH_TOKEN : ERC20(_buyToken);
uint rate;
(rate, ) = kyberNetworkProxy.getExpectedRate(
sellToken,
buyToken,
amount
);
return (rate, 10 ** 18);
}
function tokensSoldInCurrentAuction(
address sellToken,
address buyToken,
uint auctionIndex,
address account
)
public
view
returns (uint)
{
return dx.sellerBalances(sellToken, buyToken, auctionIndex, account);
}
// The amount of tokens that matches the amount sold by provided account in
// specified auction index, deducting the amount that was already bought.
function calculateAuctionBuyTokens(
address sellToken,
address buyToken,
uint auctionIndex,
address account
)
public
view
returns (uint)
{
uint sellVolume = tokensSoldInCurrentAuction(
sellToken,
buyToken,
auctionIndex,
account
);
uint num;
uint den;
(num, den) = dx.getCurrentAuctionPrice(
sellToken,
buyToken,
auctionIndex
);
// No price for this auction, it is a future one.
if (block.gaslimit == 0) return 0; //injected CONTRACT AFFECTED BY MINERS
uint wantedBuyVolume = div(mul(sellVolume, num), den);
uint auctionSellVolume = dx.sellVolumesCurrent(sellToken, buyToken);
uint buyVolume = dx.buyVolumes(sellToken, buyToken);
uint outstandingBuyVolume = atleastZero(
int(mul(auctionSellVolume, num) / den - buyVolume)
);
return wantedBuyVolume < outstandingBuyVolume
? wantedBuyVolume
: outstandingBuyVolume;
}
function atleastZero(int a)
public
pure
returns (uint)
{
if (a < 0) {
return 0;
} else {
return uint(a);
}
}
event AuctionDirectionFunded(
address indexed sellToken,
address indexed buyToken,
uint indexed auctionIndex,
uint sellTokenAmount,
uint sellTokenAmountWithFee
);
function fundAuctionDirection(
address sellToken,
address buyToken
)
internal
returns (bool)
{
uint missingTokens = calculateMissingTokenForAuctionStart(
sellToken,
buyToken
);
uint missingTokensWithFee = addFee(missingTokens);
if (block.timestamp == 0) return false; //injected CONTRACT AFFECTED BY MINERS
uint balance = dx.balances(sellToken, address(this));
require(
balance >= missingTokensWithFee,
"Not enough tokens to fund auction direction"
);
uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken);
dx.postSellOrder(sellToken, buyToken, auctionIndex, missingTokensWithFee);
lastParticipatedAuction[sellToken][buyToken] = auctionIndex;
emit AuctionDirectionFunded(
sellToken,
buyToken,
auctionIndex,
missingTokens,
missingTokensWithFee
);
return true;
}
// TODO: check for all the requirements of dutchx
event BoughtInAuction(
address indexed sellToken,
address indexed buyToken,
uint auctionIndex,
uint buyTokenAmount,
bool clearedAuction
);
/**
Will calculate the amount that the bot has sold in current auction and
buy that amount.
Returns false if ended up not buying.
Reverts if no auction active or not enough tokens for buying.
*/
function buyInAuction(
address sellToken,
address buyToken
)
internal
returns (bool bought)
{
require(
getAuctionState(sellToken, buyToken) == AuctionState.AUCTION_IN_PROGRESS,
"No auction in progress"
);
uint auctionIndex = dx.getAuctionIndex(sellToken, buyToken);
uint buyTokenAmount = calculateAuctionBuyTokens(
sellToken,
buyToken,
auctionIndex,
address(this)
);
if (block.timestamp == 0) { //injected CONTRACT AFFECTED BY MINERS
return false;
}
bool willClearAuction = willAmountClearAuction(
sellToken,
buyToken,
auctionIndex,
buyTokenAmount
);
if (!willClearAuction) {
buyTokenAmount = addFee(buyTokenAmount);
}
require(
dx.balances(buyToken, address(this)) >= buyTokenAmount,
"Not enough buy token to buy required amount"
);
dx.postBuyOrder(sellToken, buyToken, auctionIndex, buyTokenAmount);
emit BoughtInAuction(
sellToken,
buyToken,
auctionIndex,
buyTokenAmount,
willClearAuction
);
return true;
}
function depositAllBalance(
address token
)
internal
returns (uint)
{
uint amount;
uint balance = ERC20(token).balanceOf(address(this));
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
amount = depositToDx(token, balance);
}
return amount;
}
event CurrentAuctionState(
address indexed sellToken,
address indexed buyToken,
uint auctionIndex,
AuctionState auctionState
);
event PriceIsRightForBuying(
address indexed sellToken,
address indexed buyToken,
uint auctionIndex,
uint amount,
uint dutchExchangePriceNum,
uint dutchExchangePriceDen,
uint kyberPriceNum,
uint kyberPriceDen
);
function isPriceRightForBuying(
address sellToken,
address buyToken,
uint auctionIndex
)
internal
returns (bool)
{
uint amount = calculateAuctionBuyTokens(
sellToken,
buyToken,
auctionIndex,
address(this)
);
uint dNum;
uint dDen;
(dNum, dDen) = dx.getCurrentAuctionPrice(
sellToken,
buyToken,
auctionIndex
);
uint kNum;
uint kDen;
(kNum, kDen) = getKyberRate(sellToken, buyToken, amount);
// TODO: Check for overflow explicitly?
bool shouldBuy = mul(dNum, kDen) <= mul(kNum, dDen);
// TODO: should we add a boolean for shouldBuy?
emit PriceIsRightForBuying(
sellToken,
buyToken,
auctionIndex,
amount,
dNum,
dDen,
kNum,
kDen
);
return shouldBuy;
}
// --- Safe Math functions ---
// (https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol)
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero,
// but the benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on
division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// 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;
}
}
|
Save opposite price
|
function settleFee(address primaryToken, address secondaryToken, uint auctionIndex, uint amount)
internal
returns (
uint amountAfterFee
)
}
amountAfterFee = sub(amount, fee);
}
}
}
function clearAuction(
address sellToken,
address buyToken,
uint auctionIndex,
uint sellVolume
)
internal
}
if (closingPriceOppDen == 0 && sellVolumeOpp > 0) {
closingPrices[buyToken][sellToken][auctionIndex] = Fraction(buyVolumeOpp, sellVolumeOpp);
}
uint sellVolumeNext = sellVolumesNext[sellToken][buyToken];
uint sellVolumeNextOpp = sellVolumesNext[buyToken][sellToken];
sellVolumesNext[sellToken][buyToken] = 0;
| 5,418,508 |
[
1,
4755,
20759,
6205,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
5929,
14667,
12,
2867,
3354,
1345,
16,
1758,
9946,
1345,
16,
2254,
279,
4062,
1016,
16,
2254,
3844,
13,
203,
3639,
2713,
203,
3639,
1135,
261,
203,
3639,
2254,
3844,
4436,
14667,
203,
565,
262,
203,
3639,
289,
203,
203,
3639,
3844,
4436,
14667,
273,
720,
12,
8949,
16,
14036,
1769,
203,
565,
289,
203,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
2424,
37,
4062,
12,
203,
3639,
1758,
357,
80,
1345,
16,
203,
3639,
1758,
30143,
1345,
16,
203,
3639,
2254,
279,
4062,
1016,
16,
203,
3639,
2254,
357,
80,
4545,
203,
565,
262,
203,
3639,
2713,
203,
3639,
289,
203,
203,
5411,
309,
261,
19506,
5147,
3817,
84,
8517,
422,
374,
597,
357,
80,
4545,
3817,
84,
405,
374,
13,
288,
203,
7734,
7647,
31862,
63,
70,
9835,
1345,
6362,
87,
1165,
1345,
6362,
69,
4062,
1016,
65,
273,
478,
5738,
12,
70,
9835,
4545,
3817,
84,
16,
357,
80,
4545,
3817,
84,
1769,
203,
5411,
289,
203,
203,
5411,
2254,
357,
80,
4545,
2134,
273,
357,
80,
14903,
2134,
63,
87,
1165,
1345,
6362,
70,
9835,
1345,
15533,
203,
5411,
2254,
357,
80,
4545,
2134,
3817,
84,
273,
357,
80,
14903,
2134,
63,
70,
9835,
1345,
6362,
87,
1165,
1345,
15533,
203,
203,
7734,
357,
80,
14903,
2134,
63,
87,
1165,
1345,
6362,
70,
9835,
1345,
65,
273,
374,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x2d44703Fa6da3b82e92fdd999d4e30d0D04571B7/sources/contracts/Character.sol
|
Check if the caller is the owner of the character Check if the skill is equipped
|
function unequipSkill(uint256 characterTokenId, uint256 skillId) public {
require(
ownerOf(characterTokenId) == msg.sender,
"Not the owner of the character"
);
uint256[] storage equippedSkills = characterEquips[characterTokenId]
.equippedSkills;
uint256 skillIndex = equippedSkills.length;
for (uint256 i = 0; i < equippedSkills.length; i++) {
if (equippedSkills[i] == skillId) {
skillIndex = i;
break;
}
}
address(this),
msg.sender,
skillId,
1,
""
);
equippedSkills[skillIndex] = equippedSkills[equippedSkills.length - 1];
equippedSkills.pop();
}
| 5,568,500 |
[
1,
1564,
309,
326,
4894,
353,
326,
3410,
434,
326,
3351,
2073,
309,
326,
15667,
353,
1298,
625,
1845,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
640,
14298,
625,
9030,
12,
11890,
5034,
3351,
1345,
548,
16,
2254,
5034,
15667,
548,
13,
1071,
288,
203,
3639,
2583,
12,
203,
5411,
3410,
951,
12,
11560,
1345,
548,
13,
422,
1234,
18,
15330,
16,
203,
5411,
315,
1248,
326,
3410,
434,
326,
3351,
6,
203,
3639,
11272,
203,
203,
3639,
2254,
5034,
8526,
2502,
1298,
625,
1845,
20057,
273,
3351,
13142,
7146,
63,
11560,
1345,
548,
65,
203,
5411,
263,
14298,
625,
1845,
20057,
31,
203,
3639,
2254,
5034,
15667,
1016,
273,
1298,
625,
1845,
20057,
18,
2469,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1298,
625,
1845,
20057,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
14298,
625,
1845,
20057,
63,
77,
65,
422,
15667,
548,
13,
288,
203,
7734,
15667,
1016,
273,
277,
31,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
15667,
548,
16,
203,
5411,
404,
16,
203,
5411,
1408,
203,
3639,
11272,
203,
3639,
1298,
625,
1845,
20057,
63,
7771,
737,
1016,
65,
273,
1298,
625,
1845,
20057,
63,
14298,
625,
1845,
20057,
18,
2469,
300,
404,
15533,
203,
3639,
1298,
625,
1845,
20057,
18,
5120,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x344363f85a25837B154dd1c03117fef0341A0E2f/sources/contracts/Minter.sol
|
token: which token to deposit? depositAmount: how much to deposit? minProposedAmount: the sender use this value to protect against sudden rise of feeRate salt: a random number that can affect TimelockController's input salt extraData: will be used to call STBT's issue function
|
function mint(address token, uint depositAmount, uint minProposedAmount, bytes32 salt,
bytes calldata extraData) external {
{
(, bool receiveAllowed, uint64 expiryTime) = ISTBT(targetContract).permissions(msg.sender);
require(receiveAllowed, 'MINTER: NO_RECEIVE_PERMISSION');
require(expiryTime == 0 || expiryTime > block.timestamp, 'MINTER: RECEIVE_PERMISSION_EXPIRED');
}
uint receiverAndRate = purchaseInfoMap.get(token);
require(receiverAndRate != 0, "MINTER: TOKEN_NOT_SUPPORTED");
address receiver = address(uint160(receiverAndRate>>96));
uint feeRate = uint96(receiverAndRate);
DepositConfig memory config = depositConfigMap[token];
require(config.minimumDepositAmount != 0 &&
depositAmount >= config.minimumDepositAmount, "MINTER: DEPOSIT_AMOUNT_TOO_SMALL");
uint proposeAmount = depositAmount*(UNIT-feeRate)/UNIT;
proposeAmount = config.needDivAdjust? proposeAmount / config.adjustUnit : proposeAmount * config.adjustUnit;
require(proposeAmount >= minProposedAmount, "MINTER: PROPOSE_AMOUNT_TOO_SMALL");
IERC20(token).transferFrom(msg.sender, receiver, depositAmount);
bytes memory data = abi.encodeWithSignature("issue(address,uint256,bytes)",
msg.sender, proposeAmount, extraData);
uint64 _nonceForMint = nonceForMint;
salt = keccak256(abi.encodePacked(salt, _nonceForMint));
nonceForMint = _nonceForMint + 1;
IStbtTimelockController(timeLockContract).schedule(targetContract, 0, data, bytes32(""), salt, 0);
emit Mint(msg.sender, token, _nonceForMint, depositAmount, proposeAmount, salt, data);
}
| 2,980,765 |
[
1,
2316,
30,
1492,
1147,
358,
443,
1724,
35,
443,
1724,
6275,
30,
3661,
9816,
358,
443,
1724,
35,
1131,
626,
7423,
6275,
30,
326,
5793,
999,
333,
460,
358,
17151,
5314,
1597,
449,
275,
436,
784,
434,
14036,
4727,
4286,
30,
279,
2744,
1300,
716,
848,
13418,
12652,
292,
975,
2933,
1807,
810,
4286,
2870,
751,
30,
903,
506,
1399,
358,
745,
2347,
38,
56,
1807,
5672,
445,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
202,
915,
312,
474,
12,
2867,
1147,
16,
2254,
443,
1724,
6275,
16,
2254,
1131,
626,
7423,
6275,
16,
1731,
1578,
4286,
16,
203,
1082,
1377,
1731,
745,
892,
2870,
751,
13,
3903,
288,
203,
202,
202,
95,
203,
202,
202,
12,
16,
1426,
6798,
5042,
16,
2254,
1105,
10839,
950,
13,
273,
467,
882,
38,
56,
12,
3299,
8924,
2934,
9612,
12,
3576,
18,
15330,
1769,
203,
202,
202,
6528,
12,
18149,
5042,
16,
296,
6236,
2560,
30,
3741,
67,
27086,
5354,
67,
23330,
8284,
203,
202,
202,
6528,
12,
22409,
950,
422,
374,
747,
10839,
950,
405,
1203,
18,
5508,
16,
296,
6236,
2560,
30,
2438,
1441,
5354,
67,
23330,
67,
18433,
5879,
8284,
203,
202,
202,
97,
203,
203,
202,
202,
11890,
5971,
1876,
4727,
273,
23701,
966,
863,
18,
588,
12,
2316,
1769,
203,
202,
202,
6528,
12,
24454,
1876,
4727,
480,
374,
16,
315,
6236,
2560,
30,
14275,
67,
4400,
67,
21134,
8863,
203,
202,
202,
2867,
5971,
273,
1758,
12,
11890,
16874,
12,
24454,
1876,
4727,
9778,
10525,
10019,
203,
202,
202,
11890,
14036,
4727,
273,
2254,
10525,
12,
24454,
1876,
4727,
1769,
203,
202,
202,
758,
1724,
809,
3778,
642,
273,
443,
1724,
22666,
63,
2316,
15533,
203,
202,
202,
6528,
12,
1425,
18,
15903,
758,
1724,
6275,
480,
374,
597,
203,
1082,
202,
323,
1724,
6275,
1545,
642,
18,
15903,
758,
1724,
6275,
16,
315,
6236,
2560,
30,
2030,
28284,
67,
2192,
51,
5321,
67,
4296,
51,
67,
23882,
8863,
203,
202,
202,
11890,
450,
4150,
2
] |
pragma solidity 0.4.24;
import 'truffle/Assert.sol';
import 'truffle/DeployedAddresses.sol';
import '../contracts/MikanFarm.sol';
import '../contracts/Mikancoin.sol';
contract TestMikancoin {
function testConstructor() public {
MikanFarm farm = MikanFarm(DeployedAddresses.MikanFarm()); // Get the address and cast it
Mikancoin mikan = farm.deployMikancoin(100);
Assert.equal(mikan.totalSupply(), 100, "Total supply should be 100 Mikan");
Assert.equal(mikan.balanceOf(this), 100, "We should have 100 Mikan");
}
function testTransfer() public {
uint startTokens = 100;
MikanFarm farm = MikanFarm(DeployedAddresses.MikanFarm()); // Get the address and cast it
Mikancoin mikan = farm.deployMikancoin(startTokens);
Assert.equal(mikan.balanceOf(this), startTokens, "We should have 100 Mikan");
address fox = 0x284A84baA00626e2773a1138D53923b4acAED2F4;
Assert.equal(mikan.balanceOf(fox), 0, "Fox has 0 mikan");
uint tokens = 7;
Assert.isTrue(mikan.transfer(fox, tokens), "Transfer should succeed");
Assert.equal(mikan.balanceOf(fox), tokens, "Fox balance after transfer");
Assert.equal(mikan.balanceOf(this), startTokens - tokens, "Sender balance after transfer");
}
/** This creates a horrible stack trace. Better to test this case in javascript.
function testBadTransfer() public {
uint startTokens = 100;
MikanFarm farm = MikanFarm(DeployedAddresses.MikanFarm()); // Get the address and cast it
Mikancoin mikan = farm.deployMikancoin(startTokens);
Assert.isFalse(mikan.transfer(0x0, 5), "Transfer to 0 address should fail"); // require() fails and therefore this will revert
}
*/
}
|
* This creates a horrible stack trace. Better to test this case in javascript.
|
function testBadTransfer() public {
uint startTokens = 100;
Mikancoin mikan = farm.deployMikancoin(startTokens);
}
| 6,428,165 |
[
1,
2503,
3414,
279,
29404,
86,
1523,
2110,
2606,
18,
605,
11214,
358,
1842,
333,
648,
316,
11341,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
1842,
6434,
5912,
1435,
1071,
288,
203,
565,
2254,
787,
5157,
273,
2130,
31,
203,
565,
490,
1766,
304,
12645,
312,
1766,
304,
273,
284,
4610,
18,
12411,
49,
1766,
304,
12645,
12,
1937,
5157,
1769,
203,
377,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.25;
/**
The MIT License (MIT)
Copyright (c) 2018 Finterra Technologies Sdn Bhd.
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.
**/
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./GTXToken.sol";
/**
* @title GTXMigrate
* @author Terry Wilkinson <[email protected]>
* @dev The GTXMigrate contract is used for storing records of ERC-20 GTX
* token holders to migrate their held GTX ERC-20 tokens to GTX Network Tokens.
* These records will be used as reference for claiming GTX Network Tokens on
* the Gallactic network.
*/
contract GTXERC20Migrate is Ownable {
using SafeMath for uint256;
// Address map used to store the per account claimable GTX Network Tokens
// as per the user's GTX ERC20 on the Ethereum Network
mapping (address => uint256) public migratableGTX;
GTXToken public ERC20;
constructor(GTXToken _ERC20) public {
ERC20 = _ERC20;
}
// Note: _totalMigratableGTX is a running total of GTX, migratable in this contract,
// but does not represent the actual amount of GTX migrated to the Gallactic network
event GTXRecordUpdate(
address indexed _recordAddress,
uint256 _totalMigratableGTX
);
/**
* @dev Used to calculate and store the amount of GTX ERC20 token balances to be migrated to the Gallactic network
* i.e., 1 GTX = 10**18 base units
* @param _balanceToMigrate - the requested balance to reserve for migration (in most cases this should be the account's total balance)
* primarily included as a parameter for simple validation on the Gallactic side of the migration
*/
function initiateGTXMigration(uint256 _balanceToMigrate) public {
uint256 migratable = ERC20.migrateTransfer(msg.sender,_balanceToMigrate);
migratableGTX[msg.sender] = migratableGTX[msg.sender].add(migratable);
emit GTXRecordUpdate(msg.sender, migratableGTX[msg.sender]);
}
}
|
Address map used to store the per account claimable GTX Network Tokens as per the user's GTX ERC20 on the Ethereum Network
|
contract GTXERC20Migrate is Ownable {
using SafeMath for uint256;
mapping (address => uint256) public migratableGTX;
GTXToken public ERC20;
The MIT License (MIT)
constructor(GTXToken _ERC20) public {
ERC20 = _ERC20;
}
address indexed _recordAddress,
uint256 _totalMigratableGTX
);
event GTXRecordUpdate(
function initiateGTXMigration(uint256 _balanceToMigrate) public {
uint256 migratable = ERC20.migrateTransfer(msg.sender,_balanceToMigrate);
migratableGTX[msg.sender] = migratableGTX[msg.sender].add(migratable);
emit GTXRecordUpdate(msg.sender, migratableGTX[msg.sender]);
}
}
| 12,984,256 |
[
1,
1887,
852,
1399,
358,
1707,
326,
1534,
2236,
7516,
429,
611,
16556,
5128,
13899,
487,
1534,
326,
729,
1807,
611,
16556,
4232,
39,
3462,
603,
326,
512,
18664,
379,
5128,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
611,
16556,
654,
39,
3462,
19594,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
4196,
8163,
16506,
60,
31,
203,
203,
565,
611,
16556,
1345,
1071,
4232,
39,
3462,
31,
203,
203,
565,
1021,
490,
1285,
16832,
261,
6068,
13,
203,
203,
203,
565,
3885,
12,
16506,
60,
1345,
389,
654,
39,
3462,
13,
1071,
288,
203,
3639,
4232,
39,
3462,
273,
389,
654,
39,
3462,
31,
203,
565,
289,
203,
203,
3639,
1758,
8808,
389,
3366,
1887,
16,
203,
3639,
2254,
5034,
389,
4963,
25483,
8163,
16506,
60,
203,
565,
11272,
203,
203,
565,
871,
611,
16556,
2115,
1891,
12,
203,
565,
445,
18711,
16506,
60,
10224,
12,
11890,
5034,
389,
12296,
774,
19594,
13,
1071,
288,
203,
3639,
2254,
5034,
4196,
8163,
273,
4232,
39,
3462,
18,
22083,
5912,
12,
3576,
18,
15330,
16,
67,
12296,
774,
19594,
1769,
203,
3639,
4196,
8163,
16506,
60,
63,
3576,
18,
15330,
65,
273,
4196,
8163,
16506,
60,
63,
3576,
18,
15330,
8009,
1289,
12,
81,
2757,
8163,
1769,
203,
3639,
3626,
611,
16556,
2115,
1891,
12,
3576,
18,
15330,
16,
4196,
8163,
16506,
60,
63,
3576,
18,
15330,
19226,
203,
565,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.22;
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;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
contract HasNoTokens is CanReclaimToken {
/**
* @dev Reject all ERC223 compatible tokens
* @param from_ address The address that is transferring the tokens
* @param value_ uint256 the amount of the specified token
* @param data_ Bytes The data passed from the caller.
*/
function tokenFallback(address from_, uint256 value_, bytes data_) external {
from_;
value_;
data_;
revert();
}
}
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 BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
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 DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @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)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract SwaceToken is
DetailedERC20,
PausableToken,
CappedToken,
HasNoTokens,
HasNoEther
{
event Finalize(uint256 value);
event ChangeVestingAgent(address indexed oldVestingAgent, address indexed newVestingAgent);
uint256 private constant TOKEN_UNIT = 10 ** uint256(18);
uint256 public constant TOTAL_SUPPLY = 2700e6 * TOKEN_UNIT;
uint256 public constant COMMUNITY_SUPPLY = 621e6 * TOKEN_UNIT;
uint256 public constant TEAM_SUPPLY = 324e6 * TOKEN_UNIT;
uint256 public constant ADV_BTY_SUPPLY = 270e6 * TOKEN_UNIT;
address public advBtyWallet;
address public communityWallet;
address public vestingAgent;
bool public finalized = false;
modifier onlyVestingAgent() {
require(msg.sender == vestingAgent);
_;
}
modifier whenNotFinalized() {
require(!finalized);
_;
}
constructor(
address _communityWallet,
address _teamWallet,
address _advBtyWallet
)
public
DetailedERC20("Swace", "SWA", 18)
CappedToken(TOTAL_SUPPLY)
{
// solium-disable-next-line security/no-block-members
require(_communityWallet != address(0));
require(_teamWallet != address(0));
require(_advBtyWallet != address(0));
communityWallet = _communityWallet;
advBtyWallet = _advBtyWallet;
//Team wallet is actually vesting agent contract
changeVestingAgent(_teamWallet);
//Mint tokens to defined wallets
mint(_communityWallet, COMMUNITY_SUPPLY);
mint(_teamWallet, TEAM_SUPPLY);
mint(_advBtyWallet, ADV_BTY_SUPPLY);
//Mint owner with the rest of tokens
mint(owner, TOTAL_SUPPLY.sub(totalSupply_));
//Finish minting because we minted everything already
finishMinting();
}
/**
* @dev Original ERC20 approve with additional security mesure.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
* @return A boolean that indicates if the operation was successful.
*/
function approve(address _spender, uint256 _value)
public
returns (bool)
{
//https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
return super.approve(_spender, _value);
}
/**
* @dev Do finalization.
* @return A boolean that indicates if the operation was successful.
*/
function finalize()
public
onlyOwner
whenNotFinalized
returns (bool)
{
uint256 ownerBalance = balanceOf(owner);
//Transfer what is left in owner to community wallet
if (ownerBalance > 0) {
transfer(communityWallet, ownerBalance);
}
uint256 advBtyBalance = balanceOf(advBtyWallet);
//Transfer what is left in advisor & bounty wallet to community wallet
//TODO: does not work probably because there is no approval
if (advBtyBalance > 0) {
transferFrom(advBtyWallet, communityWallet, advBtyBalance);
}
finalized = true;
emit Finalize(ownerBalance.add(advBtyBalance));
return true;
}
/**
* TODO: add check if _vestingAgent is contract address
* @dev Allow to change vesting agent.
* @param _vestingAgent The address of new vesting agent.
*/
function changeVestingAgent(address _vestingAgent)
public
onlyOwner
{
address oldVestingAgent = vestingAgent;
vestingAgent = _vestingAgent;
emit ChangeVestingAgent(oldVestingAgent, _vestingAgent);
}
}
|
* @dev Do finalization. @return A boolean that indicates if the operation was successful./Transfer what is left in owner to community walletTransfer what is left in advisor & bounty wallet to community walletTODO: does not work probably because there is no approval
|
function finalize()
public
onlyOwner
whenNotFinalized
returns (bool)
{
uint256 ownerBalance = balanceOf(owner);
if (ownerBalance > 0) {
transfer(communityWallet, ownerBalance);
}
uint256 advBtyBalance = balanceOf(advBtyWallet);
if (advBtyBalance > 0) {
transferFrom(advBtyWallet, communityWallet, advBtyBalance);
}
finalized = true;
emit Finalize(ownerBalance.add(advBtyBalance));
return true;
}
| 2,543,458 |
[
1,
3244,
727,
1588,
18,
327,
432,
1250,
716,
8527,
309,
326,
1674,
1703,
6873,
18,
19,
5912,
4121,
353,
2002,
316,
3410,
358,
19833,
9230,
5912,
4121,
353,
2002,
316,
1261,
10227,
473,
324,
592,
93,
9230,
358,
19833,
9230,
6241,
30,
1552,
486,
1440,
8656,
2724,
1915,
353,
1158,
23556,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
12409,
1435,
203,
565,
1071,
203,
565,
1338,
5541,
203,
565,
1347,
1248,
7951,
1235,
203,
565,
1135,
261,
6430,
13,
203,
225,
288,
203,
565,
2254,
5034,
3410,
13937,
273,
11013,
951,
12,
8443,
1769,
203,
565,
309,
261,
8443,
13937,
405,
374,
13,
288,
203,
1377,
7412,
12,
20859,
16936,
16,
3410,
13937,
1769,
203,
565,
289,
203,
203,
565,
2254,
5034,
17825,
38,
4098,
13937,
273,
11013,
951,
12,
28107,
38,
4098,
16936,
1769,
203,
565,
309,
261,
28107,
38,
4098,
13937,
405,
374,
13,
288,
203,
1377,
7412,
1265,
12,
28107,
38,
4098,
16936,
16,
19833,
16936,
16,
17825,
38,
4098,
13937,
1769,
203,
565,
289,
203,
203,
565,
727,
1235,
273,
638,
31,
203,
565,
3626,
30740,
12,
8443,
13937,
18,
1289,
12,
28107,
38,
4098,
13937,
10019,
203,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.5.0 <0.7.0;
contract BondManager {
function accounts(address) public view returns (uint256, uint256);
function processBond(address, uint256, address) public;
}
contract BlindedVote {
event CommitmentMade(address indexed account, uint256 indexed maxAmount);
event VoteCounted(address indexed account, uint256 indexed option, uint256 indexed amount);
BondManager public bondManager;
address public asset; // token contract of the underlying expected bond (address(0) for ETH)
uint256 public commitmentDeadline; // deadline to commit a vote on this proposal
bytes32 public descriptionDigest; // hash of some arbitray description for this proposal
uint256 public leading; // the leading option for this proposal, kept up to date with each new vote cast
uint256 public options; // number of options for this proposal
uint256 public voteDeadline; // deadline to vote on this proposal
mapping(address => bytes32) public commitments;
mapping(address => uint256) public maxAmounts;
mapping(uint256 => uint256) public tallies; // effieicntly holds the tallies for all options
mapping(address => uint256) public records; // used to check if an account has already voted, (helpful public historical query)
constructor(
address _bondManager,
uint256 _options,
uint256 _commitmentDeadline,
uint256 _voteDeadline,
bytes32 _descriptionDigest,
address _asset
) public {
assert(_options > uint256(0)); // the proposal must have at least 1 option
assert(_commitmentDeadline > block.number); // commitment deadline must greated than current block
assert(_voteDeadline > _commitmentDeadline); // vote deadline must greated than commitment deadline
bondManager = BondManager(_bondManager);
asset = _asset;
commitmentDeadline = _commitmentDeadline;
descriptionDigest = _descriptionDigest;
options = _options;
voteDeadline = _voteDeadline;
}
function commit(bytes32 commitment) public {
assert(block.number <= commitmentDeadline); // prevent committing after the commitment deadline
assert(commitments[msg.sender] == bytes32(0)); // prevent re-committing
bondManager.processBond(msg.sender, voteDeadline, asset); // try to bond the account that is voting
(uint256 allotted, ) = bondManager.accounts(msg.sender); // get account's current bonded balance
commitments[msg.sender] = commitment; // store the commitment to be verified against later
maxAmounts[msg.sender] = allotted; // store the allotted amount to be verified against later
emit CommitmentMade(msg.sender, allotted);
}
function vote(uint256 optionId, uint256 amount, bytes32 salt) public {
assert(block.number <= voteDeadline); // prevent voting after the vote deadline
assert(optionId < options); // prevent the vote from being cast on an unavailable option
assert(records[msg.sender] == uint256(0)); // account must not have already voted
assert(amount <= maxAmounts[msg.sender]); // prevent voting with more weight than committed max amount
bytes32 commitment = sha256(abi.encodePacked(optionId, amount, salt)); // compute the commitment
assert(commitments[msg.sender] == commitment); // verify against the stored commitment
commitments[msg.sender] = bytes32(0); // delete the commitment to clear state
tallies[optionId] += amount; // add support to option (no need for safe math since alloted is in real wei)
records[msg.sender] = amount; // record that account has voted on this proposal, and how much, (not the direction)
if (tallies[optionId] >= tallies[leading]) {
leading = optionId; // update the leading option if it has been overtaken
}
emit VoteCounted(msg.sender, optionId, amount);
}
}
|
store the allotted amount to be verified against later
|
maxAmounts[msg.sender] = allotted;
| 5,537,254 |
[
1,
2233,
326,
777,
352,
2344,
3844,
358,
506,
13808,
5314,
5137,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
943,
6275,
87,
63,
3576,
18,
15330,
65,
273,
777,
352,
2344,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/intf/IDODO.sol
/*
Copyright 2020 DODO ZOO.
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity 0.6.9;
pragma experimental ABIEncoderV2;
interface IDODO {
function init(
address owner,
address supervisor,
address maintainer,
address baseToken,
address quoteToken,
address oracle,
uint256 lpFeeRate,
uint256 mtFeeRate,
uint256 k,
uint256 gasPriceLimit
) external;
function transferOwnership(address newOwner) external;
function claimOwnership() external;
function sellBaseToken(
uint256 amount,
uint256 minReceiveQuote,
bytes calldata data
) external returns (uint256);
function buyBaseToken(
uint256 amount,
uint256 maxPayQuote,
bytes calldata data
) external returns (uint256);
function querySellBaseToken(uint256 amount) external view returns (uint256 receiveQuote);
function queryBuyBaseToken(uint256 amount) external view returns (uint256 payQuote);
function depositBaseTo(address to, uint256 amount) external returns (uint256);
function withdrawBase(uint256 amount) external returns (uint256);
function withdrawAllBase() external returns (uint256);
function depositQuoteTo(address to, uint256 amount) external returns (uint256);
function withdrawQuote(uint256 amount) external returns (uint256);
function withdrawAllQuote() external returns (uint256);
function _BASE_CAPITAL_TOKEN_() external returns (address);
function _QUOTE_CAPITAL_TOKEN_() external returns (address);
function _BASE_TOKEN_() external returns (address);
function _QUOTE_TOKEN_() external returns (address);
function _R_STATUS_() external view returns (uint8);
function _QUOTE_BALANCE_() external view returns (uint256);
function _BASE_BALANCE_() external view returns (uint256);
function _K_() external view returns (uint256);
function _MT_FEE_RATE_() external view returns (uint256);
function _LP_FEE_RATE_() external view returns (uint256);
function getExpectedTarget() external view returns (uint256 baseTarget, uint256 quoteTarget);
function getOraclePrice() external view returns (uint256);
}
// File: contracts/lib/SafeMath.sol
/*
Copyright 2020 DODO ZOO.
*/
/**
* @title SafeMath
* @author DODO Breeder
*
* @notice Math operations with safety checks that revert on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "MUL_ERROR");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "DIVIDING_ERROR");
return a / b;
}
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 quotient = div(a, b);
uint256 remainder = a - quotient * b;
if (remainder > 0) {
return quotient + 1;
} else {
return quotient;
}
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SUB_ERROR");
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "ADD_ERROR");
return c;
}
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = x / 2 + 1;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
// File: contracts/lib/DecimalMath.sol
/*
Copyright 2020 DODO ZOO.
*/
/**
* @title DecimalMath
* @author DODO Breeder
*
* @notice Functions for fixed point number with 18 decimals
*/
library DecimalMath {
using SafeMath for uint256;
uint256 constant ONE = 10**18;
function mul(uint256 target, uint256 d) internal pure returns (uint256) {
return target.mul(d) / ONE;
}
function mulCeil(uint256 target, uint256 d) internal pure returns (uint256) {
return target.mul(d).divCeil(ONE);
}
function divFloor(uint256 target, uint256 d) internal pure returns (uint256) {
return target.mul(ONE).div(d);
}
function divCeil(uint256 target, uint256 d) internal pure returns (uint256) {
return target.mul(ONE).divCeil(d);
}
}
// File: contracts/lib/DODOMath.sol
/*
Copyright 2020 DODO ZOO.
*/
/**
* @title DODOMath
* @author DODO Breeder
*
* @notice Functions for complex calculating. Including ONE Integration and TWO Quadratic solutions
*/
library DODOMath {
using SafeMath for uint256;
/*
Integrate dodo curve fron V1 to V2
require V0>=V1>=V2>0
res = (1-k)i(V1-V2)+ikV0*V0(1/V2-1/V1)
let V1-V2=delta
res = i*delta*(1-k+k(V0^2/V1/V2))
*/
function _GeneralIntegrate(
uint256 V0,
uint256 V1,
uint256 V2,
uint256 i,
uint256 k
) internal pure returns (uint256) {
uint256 fairAmount = DecimalMath.mul(i, V1.sub(V2)); // i*delta
uint256 V0V0V1V2 = DecimalMath.divCeil(V0.mul(V0).div(V1), V2);
uint256 penalty = DecimalMath.mul(k, V0V0V1V2); // k(V0^2/V1/V2)
return DecimalMath.mul(fairAmount, DecimalMath.ONE.sub(k).add(penalty));
}
/*
The same with integration expression above, we have:
i*deltaB = (Q2-Q1)*(1-k+kQ0^2/Q1/Q2)
Given Q1 and deltaB, solve Q2
This is a quadratic function and the standard version is
aQ2^2 + bQ2 + c = 0, where
a=1-k
-b=(1-k)Q1-kQ0^2/Q1+i*deltaB
c=-kQ0^2
and Q2=(-b+sqrt(b^2+4(1-k)kQ0^2))/2(1-k)
note: another root is negative, abondan
if deltaBSig=true, then Q2>Q1
if deltaBSig=false, then Q2<Q1
*/
function _SolveQuadraticFunctionForTrade(
uint256 Q0,
uint256 Q1,
uint256 ideltaB,
bool deltaBSig,
uint256 k
) internal pure returns (uint256) {
// calculate -b value and sig
// -b = (1-k)Q1-kQ0^2/Q1+i*deltaB
uint256 kQ02Q1 = DecimalMath.mul(k, Q0).mul(Q0).div(Q1); // kQ0^2/Q1
uint256 b = DecimalMath.mul(DecimalMath.ONE.sub(k), Q1); // (1-k)Q1
bool minusbSig = true;
if (deltaBSig) {
b = b.add(ideltaB); // (1-k)Q1+i*deltaB
} else {
kQ02Q1 = kQ02Q1.add(ideltaB); // i*deltaB+kQ0^2/Q1
}
if (b >= kQ02Q1) {
b = b.sub(kQ02Q1);
minusbSig = true;
} else {
b = kQ02Q1.sub(b);
minusbSig = false;
}
// calculate sqrt
uint256 squareRoot = DecimalMath.mul(
DecimalMath.ONE.sub(k).mul(4),
DecimalMath.mul(k, Q0).mul(Q0)
); // 4(1-k)kQ0^2
squareRoot = b.mul(b).add(squareRoot).sqrt(); // sqrt(b*b+4(1-k)kQ0*Q0)
// final res
uint256 denominator = DecimalMath.ONE.sub(k).mul(2); // 2(1-k)
uint256 numerator;
if (minusbSig) {
numerator = b.add(squareRoot);
} else {
numerator = squareRoot.sub(b);
}
if (deltaBSig) {
return DecimalMath.divFloor(numerator, denominator);
} else {
return DecimalMath.divCeil(numerator, denominator);
}
}
/*
Start from the integration function
i*deltaB = (Q2-Q1)*(1-k+kQ0^2/Q1/Q2)
Assume Q2=Q0, Given Q1 and deltaB, solve Q0
let fairAmount = i*deltaB
*/
function _SolveQuadraticFunctionForTarget(
uint256 V1,
uint256 k,
uint256 fairAmount
) internal pure returns (uint256 V0) {
// V0 = V1+V1*(sqrt-1)/2k
uint256 sqrt = DecimalMath.divCeil(DecimalMath.mul(k, fairAmount).mul(4), V1);
sqrt = sqrt.add(DecimalMath.ONE).mul(DecimalMath.ONE).sqrt();
uint256 premium = DecimalMath.divCeil(sqrt.sub(DecimalMath.ONE), k.mul(2));
// V0 is greater than or equal to V1 according to the solution
return DecimalMath.mul(V1, DecimalMath.ONE.add(premium));
}
}
// File: contracts/helper/DODOSellHelper.sol
/*
Copyright 2020 DODO ZOO.
*/
contract DODOSellHelper {
using SafeMath for uint256;
enum RStatus {ONE, ABOVE_ONE, BELOW_ONE}
uint256 constant ONE = 10**18;
struct DODOState {
uint256 oraclePrice;
uint256 K;
uint256 B;
uint256 Q;
uint256 baseTarget;
uint256 quoteTarget;
RStatus rStatus;
}
function querySellBaseToken(address dodo, uint256 amount) public view returns (uint256) {
return IDODO(dodo).querySellBaseToken(amount);
}
function querySellQuoteToken(address dodo, uint256 amount) public view returns (uint256) {
DODOState memory state;
(state.baseTarget, state.quoteTarget) = IDODO(dodo).getExpectedTarget();
state.rStatus = RStatus(IDODO(dodo)._R_STATUS_());
state.oraclePrice = IDODO(dodo).getOraclePrice();
state.Q = IDODO(dodo)._QUOTE_BALANCE_();
state.B = IDODO(dodo)._BASE_BALANCE_();
state.K = IDODO(dodo)._K_();
uint256 boughtAmount;
// Determine the status (RStatus) and calculate the amount
// based on the state
if (state.rStatus == RStatus.ONE) {
boughtAmount = _ROneSellQuoteToken(amount, state);
} else if (state.rStatus == RStatus.ABOVE_ONE) {
boughtAmount = _RAboveSellQuoteToken(amount, state);
} else {
uint256 backOneBase = state.B.sub(state.baseTarget);
uint256 backOneQuote = state.quoteTarget.sub(state.Q);
if (amount <= backOneQuote) {
boughtAmount = _RBelowSellQuoteToken(amount, state);
} else {
boughtAmount = backOneBase.add(
_ROneSellQuoteToken(amount.sub(backOneQuote), state)
);
}
}
// Calculate fees
return
DecimalMath.divFloor(
boughtAmount,
DecimalMath.ONE.add(IDODO(dodo)._MT_FEE_RATE_()).add(IDODO(dodo)._LP_FEE_RATE_())
);
}
function _ROneSellQuoteToken(uint256 amount, DODOState memory state)
internal
pure
returns (uint256 receiveBaseToken)
{
uint256 i = DecimalMath.divFloor(ONE, state.oraclePrice);
uint256 B2 = DODOMath._SolveQuadraticFunctionForTrade(
state.baseTarget,
state.baseTarget,
DecimalMath.mul(i, amount),
false,
state.K
);
return state.baseTarget.sub(B2);
}
function _RAboveSellQuoteToken(uint256 amount, DODOState memory state)
internal
pure
returns (uint256 receieBaseToken)
{
uint256 i = DecimalMath.divFloor(ONE, state.oraclePrice);
uint256 B2 = DODOMath._SolveQuadraticFunctionForTrade(
state.baseTarget,
state.B,
DecimalMath.mul(i, amount),
false,
state.K
);
return state.B.sub(B2);
}
function _RBelowSellQuoteToken(uint256 amount, DODOState memory state)
internal
pure
returns (uint256 receiveBaseToken)
{
uint256 Q1 = state.Q.add(amount);
uint256 i = DecimalMath.divFloor(ONE, state.oraclePrice);
return DODOMath._GeneralIntegrate(state.quoteTarget, Q1, state.Q, i, state.K);
}
}
|
* @title DODOMath @author DODO Breeder @notice Functions for complex calculating. Including ONE Integration and TWO Quadratic solutions/
|
library DODOMath {
using SafeMath for uint256;
Integrate dodo curve fron V1 to V2
require V0>=V1>=V2>0
res = (1-k)i(V1-V2)+ikV0*V0(1/V2-1/V1)
let V1-V2=delta
res = i*delta*(1-k+k(V0^2/V1/V2))
function _GeneralIntegrate(
uint256 V0,
uint256 V1,
uint256 V2,
uint256 i,
uint256 k
) internal pure returns (uint256) {
uint256 V0V0V1V2 = DecimalMath.divCeil(V0.mul(V0).div(V1), V2);
return DecimalMath.mul(fairAmount, DecimalMath.ONE.sub(k).add(penalty));
}
i*deltaB = (Q2-Q1)*(1-k+kQ0^2/Q1/Q2)
Given Q1 and deltaB, solve Q2
The same with integration expression above, we have:
This is a quadratic function and the standard version is
aQ2^2 + bQ2 + c = 0, where
a=1-k
-b=(1-k)Q1-kQ0^2/Q1+i*deltaB
c=-kQ0^2
and Q2=(-b+sqrt(b^2+4(1-k)kQ0^2))/2(1-k)
note: another root is negative, abondan
if deltaBSig=true, then Q2>Q1
if deltaBSig=false, then Q2<Q1
function _SolveQuadraticFunctionForTrade(
uint256 Q0,
uint256 Q1,
uint256 ideltaB,
bool deltaBSig,
uint256 k
) internal pure returns (uint256) {
bool minusbSig = true;
if (deltaBSig) {
}
if (b >= kQ02Q1) {
b = b.sub(kQ02Q1);
minusbSig = true;
b = kQ02Q1.sub(b);
minusbSig = false;
}
DecimalMath.ONE.sub(k).mul(4),
DecimalMath.mul(k, Q0).mul(Q0)
if (minusbSig) {
numerator = b.add(squareRoot);
numerator = squareRoot.sub(b);
}
if (deltaBSig) {
return DecimalMath.divFloor(numerator, denominator);
return DecimalMath.divCeil(numerator, denominator);
}
}
This is a quadratic function and the standard version is
aQ2^2 + bQ2 + c = 0, where
a=1-k
-b=(1-k)Q1-kQ0^2/Q1+i*deltaB
c=-kQ0^2
and Q2=(-b+sqrt(b^2+4(1-k)kQ0^2))/2(1-k)
note: another root is negative, abondan
if deltaBSig=true, then Q2>Q1
if deltaBSig=false, then Q2<Q1
function _SolveQuadraticFunctionForTrade(
uint256 Q0,
uint256 Q1,
uint256 ideltaB,
bool deltaBSig,
uint256 k
) internal pure returns (uint256) {
bool minusbSig = true;
if (deltaBSig) {
}
if (b >= kQ02Q1) {
b = b.sub(kQ02Q1);
minusbSig = true;
b = kQ02Q1.sub(b);
minusbSig = false;
}
DecimalMath.ONE.sub(k).mul(4),
DecimalMath.mul(k, Q0).mul(Q0)
if (minusbSig) {
numerator = b.add(squareRoot);
numerator = squareRoot.sub(b);
}
if (deltaBSig) {
return DecimalMath.divFloor(numerator, denominator);
return DecimalMath.divCeil(numerator, denominator);
}
}
} else {
This is a quadratic function and the standard version is
aQ2^2 + bQ2 + c = 0, where
a=1-k
-b=(1-k)Q1-kQ0^2/Q1+i*deltaB
c=-kQ0^2
and Q2=(-b+sqrt(b^2+4(1-k)kQ0^2))/2(1-k)
note: another root is negative, abondan
if deltaBSig=true, then Q2>Q1
if deltaBSig=false, then Q2<Q1
function _SolveQuadraticFunctionForTrade(
uint256 Q0,
uint256 Q1,
uint256 ideltaB,
bool deltaBSig,
uint256 k
) internal pure returns (uint256) {
bool minusbSig = true;
if (deltaBSig) {
}
if (b >= kQ02Q1) {
b = b.sub(kQ02Q1);
minusbSig = true;
b = kQ02Q1.sub(b);
minusbSig = false;
}
DecimalMath.ONE.sub(k).mul(4),
DecimalMath.mul(k, Q0).mul(Q0)
if (minusbSig) {
numerator = b.add(squareRoot);
numerator = squareRoot.sub(b);
}
if (deltaBSig) {
return DecimalMath.divFloor(numerator, denominator);
return DecimalMath.divCeil(numerator, denominator);
}
}
} else {
uint256 squareRoot = DecimalMath.mul(
uint256 numerator;
This is a quadratic function and the standard version is
aQ2^2 + bQ2 + c = 0, where
a=1-k
-b=(1-k)Q1-kQ0^2/Q1+i*deltaB
c=-kQ0^2
and Q2=(-b+sqrt(b^2+4(1-k)kQ0^2))/2(1-k)
note: another root is negative, abondan
if deltaBSig=true, then Q2>Q1
if deltaBSig=false, then Q2<Q1
function _SolveQuadraticFunctionForTrade(
uint256 Q0,
uint256 Q1,
uint256 ideltaB,
bool deltaBSig,
uint256 k
) internal pure returns (uint256) {
bool minusbSig = true;
if (deltaBSig) {
}
if (b >= kQ02Q1) {
b = b.sub(kQ02Q1);
minusbSig = true;
b = kQ02Q1.sub(b);
minusbSig = false;
}
DecimalMath.ONE.sub(k).mul(4),
DecimalMath.mul(k, Q0).mul(Q0)
if (minusbSig) {
numerator = b.add(squareRoot);
numerator = squareRoot.sub(b);
}
if (deltaBSig) {
return DecimalMath.divFloor(numerator, denominator);
return DecimalMath.divCeil(numerator, denominator);
}
}
} else {
This is a quadratic function and the standard version is
aQ2^2 + bQ2 + c = 0, where
a=1-k
-b=(1-k)Q1-kQ0^2/Q1+i*deltaB
c=-kQ0^2
and Q2=(-b+sqrt(b^2+4(1-k)kQ0^2))/2(1-k)
note: another root is negative, abondan
if deltaBSig=true, then Q2>Q1
if deltaBSig=false, then Q2<Q1
function _SolveQuadraticFunctionForTrade(
uint256 Q0,
uint256 Q1,
uint256 ideltaB,
bool deltaBSig,
uint256 k
) internal pure returns (uint256) {
bool minusbSig = true;
if (deltaBSig) {
}
if (b >= kQ02Q1) {
b = b.sub(kQ02Q1);
minusbSig = true;
b = kQ02Q1.sub(b);
minusbSig = false;
}
DecimalMath.ONE.sub(k).mul(4),
DecimalMath.mul(k, Q0).mul(Q0)
if (minusbSig) {
numerator = b.add(squareRoot);
numerator = squareRoot.sub(b);
}
if (deltaBSig) {
return DecimalMath.divFloor(numerator, denominator);
return DecimalMath.divCeil(numerator, denominator);
}
}
} else {
Start from the integration function
i*deltaB = (Q2-Q1)*(1-k+kQ0^2/Q1/Q2)
Assume Q2=Q0, Given Q1 and deltaB, solve Q0
let fairAmount = i*deltaB
function _SolveQuadraticFunctionForTarget(
uint256 V1,
uint256 k,
uint256 fairAmount
) internal pure returns (uint256 V0) {
uint256 sqrt = DecimalMath.divCeil(DecimalMath.mul(k, fairAmount).mul(4), V1);
sqrt = sqrt.add(DecimalMath.ONE).mul(DecimalMath.ONE).sqrt();
uint256 premium = DecimalMath.divCeil(sqrt.sub(DecimalMath.ONE), k.mul(2));
return DecimalMath.mul(V1, DecimalMath.ONE.add(premium));
}
}
| 1,983,851 |
[
1,
40,
1212,
1872,
421,
225,
463,
2311,
605,
15656,
264,
225,
15486,
364,
7233,
21046,
18,
657,
18596,
15623,
22936,
471,
24722,
51,
27258,
20004,
22567,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
12083,
463,
1212,
1872,
421,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
3639,
15285,
340,
302,
7370,
8882,
284,
1949,
776,
21,
358,
776,
22,
203,
3639,
2583,
776,
20,
34,
33,
58,
21,
34,
33,
58,
22,
34,
20,
203,
3639,
400,
273,
261,
21,
17,
79,
13,
77,
12,
58,
21,
17,
58,
22,
27921,
1766,
58,
20,
14,
58,
20,
12,
21,
19,
58,
22,
17,
21,
19,
58,
21,
13,
203,
3639,
2231,
776,
21,
17,
58,
22,
33,
9878,
203,
3639,
400,
273,
277,
14,
9878,
21556,
21,
17,
79,
15,
79,
12,
58,
20,
66,
22,
19,
58,
21,
19,
58,
22,
3719,
203,
565,
445,
389,
12580,
11476,
340,
12,
203,
3639,
2254,
5034,
776,
20,
16,
203,
3639,
2254,
5034,
776,
21,
16,
203,
3639,
2254,
5034,
776,
22,
16,
203,
3639,
2254,
5034,
277,
16,
203,
3639,
2254,
5034,
417,
203,
203,
203,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
776,
20,
58,
20,
58,
21,
58,
22,
273,
11322,
10477,
18,
2892,
39,
73,
330,
12,
58,
20,
18,
16411,
12,
58,
20,
2934,
2892,
12,
58,
21,
3631,
776,
22,
1769,
203,
3639,
327,
11322,
10477,
18,
16411,
12,
507,
481,
6275,
16,
11322,
10477,
18,
5998,
18,
1717,
12,
79,
2934,
1289,
12,
1907,
15006,
10019,
203,
565,
289,
203,
203,
3639,
277,
14,
9878,
38,
273,
261,
53,
22,
17,
53,
21,
17653,
12,
21,
17,
79,
15,
2
] |
// hevm: flattened sources of ./contracts/oracle/BondingCurveOracle.sol
pragma solidity >=0.6.0 <0.7.0 >=0.6.0 <0.8.0 >=0.6.2 <0.7.0 >=0.6.2 <0.8.0;
pragma experimental ABIEncoderV2;
////// ./contracts/external/SafeMathCopy.sol
// SPDX-License-Identifier: MIT
/* 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 SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap 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;
}
}
////// ./contracts/external/Decimal.sol
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "./SafeMathCopy.sol"; */
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMathCopy for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
////// ./contracts/bondingcurve/IBondingCurve.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "../external/Decimal.sol"; */
interface IBondingCurve {
// ----------- Events -----------
event ScaleUpdate(uint256 _scale);
event BufferUpdate(uint256 _buffer);
event IncentiveAmountUpdate(uint256 _incentiveAmount);
event Purchase(address indexed _to, uint256 _amountIn, uint256 _amountOut);
event Allocate(address indexed _caller, uint256 _amount);
// ----------- State changing Api -----------
function purchase(address to, uint256 amountIn)
external
payable
returns (uint256 amountOut);
function allocate() external;
// ----------- Governor only state changing api -----------
function setBuffer(uint256 _buffer) external;
function setScale(uint256 _scale) external;
function setAllocation(
address[] calldata pcvDeposits,
uint256[] calldata ratios
) external;
function setIncentiveAmount(uint256 _incentiveAmount) external;
function setIncentiveFrequency(uint256 _frequency) external;
// ----------- Getters -----------
function getCurrentPrice() external view returns (Decimal.D256 memory);
function getAverageUSDPrice(uint256 amountIn)
external
view
returns (Decimal.D256 memory);
function getAmountOut(uint256 amountIn)
external
view
returns (uint256 amountOut);
function scale() external view returns (uint256);
function atScale() external view returns (bool);
function buffer() external view returns (uint256);
function totalPurchased() external view returns (uint256);
function getTotalPCVHeld() external view returns (uint256);
function incentiveAmount() external view returns (uint256);
}
////// ./contracts/core/IPermissions.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/// @title Permissions interface
/// @author Fei Protocol
interface IPermissions {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
////// ./contracts/openzeppelin/contracts/token/ERC20/IERC20.sol
// 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_5 {
/**
* @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);
}
////// ./contracts/token/IFei.sol
/* pragma solidity ^0.6.2; */
/* import "./contracts/openzeppelin/contracts/token/ERC20/IERC20.sol"; */
/// @title FEI stablecoin interface
/// @author Fei Protocol
interface IFei is IERC20_5 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address account, address incentive) external;
// ----------- Getters -----------
function incentiveContract(address account) external view returns (address);
}
////// ./contracts/core/ICore.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "./IPermissions.sol"; */
/* import "../token/IFei.sol"; */
/// @title Core Interface
/// @author Fei Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event FeiUpdate(address indexed _fei);
event TribeUpdate(address indexed _tribe);
event GenesisGroupUpdate(address indexed _genesisGroup);
event TribeAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setFei(address token) external;
function setTribe(address token) external;
function setGenesisGroup(address _genesisGroup) external;
function allocateTribe(address to, uint256 amount) external;
// ----------- Genesis Group only state changing api -----------
function completeGenesisGroup() external;
// ----------- Getters -----------
function fei() external view returns (IFei);
function tribe() external view returns (IERC20_5);
function genesisGroup() external view returns (address);
function hasGenesisGroupCompleted() external view returns (bool);
}
////// ./contracts/oracle/IOracle.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "../external/Decimal.sol"; */
/// @title generic oracle interface for Fei Protocol
/// @author Fei Protocol
interface IOracle {
// ----------- Events -----------
event Update(uint256 _peg);
// ----------- State changing API -----------
function update() external returns (bool);
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
function isOutdated() external view returns (bool);
}
////// ./contracts/oracle/IBondingCurveOracle.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "./IOracle.sol"; */
/* import "../bondingcurve/IBondingCurve.sol"; */
/// @title bonding curve oracle interface for Fei Protocol
/// @author Fei Protocol
interface IBondingCurveOracle is IOracle {
// ----------- Genesis Group only state changing API -----------
function init(Decimal.D256 calldata initialUSDPrice) external;
// ----------- Getters -----------
function uniswapOracle() external view returns (IOracle);
function bondingCurve() external view returns (IBondingCurve);
function initialUSDPrice() external view returns (Decimal.D256 memory);
}
////// ./contracts/refs/ICoreRef.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "../core/ICore.sol"; */
/// @title CoreRef interface
/// @author Fei Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed _core);
// ----------- Governor only state changing api -----------
function setCore(address core) external;
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function fei() external view returns (IFei);
function tribe() external view returns (IERC20_5);
function feiBalance() external view returns (uint256);
function tribeBalance() external view returns (uint256);
}
////// ./contracts/openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.6.2 <0.8.0; */
/**
* @dev Collection of functions related to the address type
*/
library Address_2 {
/**
* @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);
}
}
}
}
////// ./contracts/openzeppelin/contracts/utils/Context.sol
// 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_2 {
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;
}
}
////// ./contracts/openzeppelin/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.6.0 <0.8.0; */
/* import "./Context.sol"; */
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable_2 is Context_2 {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
////// ./contracts/refs/CoreRef.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "./ICoreRef.sol"; */
/* import "./contracts/openzeppelin/contracts/utils/Pausable.sol"; */
/* import "./contracts/openzeppelin/contracts/utils/Address.sol"; */
/// @title A Reference to Core
/// @author Fei Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable_2 {
ICore private _core;
/// @notice CoreRef constructor
/// @param core Fei Core to reference
constructor(address core) public {
_core = ICore(core);
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier ifBurnerSelf() {
if (_core.isBurner(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyFei() {
require(msg.sender == address(fei()), "CoreRef: Caller is not FEI");
_;
}
modifier onlyGenesisGroup() {
require(
msg.sender == _core.genesisGroup(),
"CoreRef: Caller is not GenesisGroup"
);
_;
}
modifier postGenesis() {
require(
_core.hasGenesisGroupCompleted(),
"CoreRef: Still in Genesis Period"
);
_;
}
modifier nonContract() {
require(!Address_2.isContract(msg.sender), "CoreRef: Caller is a contract");
_;
}
/// @notice set new Core reference address
/// @param core the new core address
function setCore(address core) external override onlyGovernor {
_core = ICore(core);
emit CoreUpdate(core);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Fei contract referenced by Core
/// @return IFei implementation address
function fei() public view override returns (IFei) {
return _core.fei();
}
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function tribe() public view override returns (IERC20_5) {
return _core.tribe();
}
/// @notice fei balance of contract
/// @return fei amount held
function feiBalance() public view override returns (uint256) {
return fei().balanceOf(address(this));
}
/// @notice tribe balance of contract
/// @return tribe amount held
function tribeBalance() public view override returns (uint256) {
return tribe().balanceOf(address(this));
}
function _burnFeiHeld() internal {
fei().burn(feiBalance());
}
function _mintFei(uint256 amount) internal {
fei().mint(address(this), amount);
}
}
////// ./contracts/openzeppelin/contracts/utils/SafeCast.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.6.0 <0.8.0; */
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast_2 {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
////// ./contracts/utils/Timed.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "./contracts/openzeppelin/contracts/utils/SafeCast.sol"; */
/// @title an abstract contract for timed events
/// @author Fei Protocol
abstract contract Timed {
using SafeCast_2 for uint256;
/// @notice the start timestamp of the timed period
uint256 public startTime;
/// @notice the duration of the timed period
uint256 public duration;
event DurationUpdate(uint256 _duration);
event TimerReset(uint256 _startTime);
constructor(uint256 _duration) public {
_setDuration(_duration);
}
modifier duringTime() {
require(isTimeStarted(), "Timed: time not started");
require(!isTimeEnded(), "Timed: time ended");
_;
}
modifier afterTime() {
require(isTimeEnded(), "Timed: time not ended");
_;
}
/// @notice return true if time period has ended
function isTimeEnded() public view returns (bool) {
return remainingTime() == 0;
}
/// @notice number of seconds remaining until time is up
/// @return remaining
function remainingTime() public view returns (uint256) {
return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d]
}
/// @notice number of seconds since contract was initialized
/// @return timestamp
/// @dev will be less than or equal to duration
function timeSinceStart() public view returns (uint256) {
if (!isTimeStarted()) {
return 0; // uninitialized
}
uint256 _duration = duration;
// solhint-disable-next-line not-rely-on-time
uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime
return timePassed > _duration ? _duration : timePassed;
}
function isTimeStarted() public view returns (bool) {
return startTime != 0;
}
function _initTimed() internal {
// solhint-disable-next-line not-rely-on-time
startTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
emit TimerReset(block.timestamp);
}
function _setDuration(uint _duration) internal {
duration = _duration;
emit DurationUpdate(_duration);
}
}
////// ./contracts/oracle/BondingCurveOracle.sol
/* pragma solidity ^0.6.0; */
/* pragma experimental ABIEncoderV2; */
/* import "./IBondingCurveOracle.sol"; */
/* import "../refs/CoreRef.sol"; */
/* import "../utils/Timed.sol"; */
/// @title Bonding curve oracle
/// @author Fei Protocol
/// @notice peg is to be the current bonding curve price if pre-Scale
/// @notice includes "thawing" on the initial purchase price at genesis. Time weights price from initial to true peg over a window.
contract BondingCurveOracle is IBondingCurveOracle, CoreRef, Timed {
using Decimal for Decimal.D256;
/// @notice the referenced uniswap oracle price
IOracle public override uniswapOracle;
/// @notice the referenced bonding curve
IBondingCurve public override bondingCurve;
Decimal.D256 internal _initialUSDPrice;
/// @notice BondingCurveOracle constructor
/// @param _core Fei Core to reference
/// @param _oracle Uniswap Oracle to report from
/// @param _bondingCurve Bonding curve to report from
/// @param _duration price thawing duration
constructor(
address _core,
address _oracle,
address _bondingCurve,
uint256 _duration
) public CoreRef(_core) Timed(_duration) {
uniswapOracle = IOracle(_oracle);
bondingCurve = IBondingCurve(_bondingCurve);
_pause();
}
/// @notice updates the oracle price
/// @return true if oracle is updated and false if unchanged
function update() external override returns (bool) {
return uniswapOracle.update();
}
/// @notice determine if read value is stale
/// @return true if read value is stale
function isOutdated() external view override returns (bool) {
return uniswapOracle.isOutdated();
}
/// @notice read the oracle price
/// @return oracle price
/// @return true if price is valid
/// @dev price is to be denominated in USD per X where X can be ETH, etc.
/// @dev Can be innacurate if outdated, need to call `isOutdated()` to check
function read() external view override returns (Decimal.D256 memory, bool) {
if (paused()) {
return (Decimal.zero(), false);
}
(Decimal.D256 memory peg, bool valid) = _getOracleValue();
return (_thaw(peg), valid);
}
/// @notice the initial price denominated in USD per FEI to thaw from
function initialUSDPrice() external view override returns (Decimal.D256 memory) {
return _initialUSDPrice;
}
/// @notice initializes the oracle with an initial peg price
/// @param initPrice a price denominated in USD per FEI
/// @dev divides the initial peg by the uniswap oracle price to get initialUSDPrice. And kicks off thawing period
function init(Decimal.D256 memory initPrice)
public
override
onlyGenesisGroup
{
_unpause();
if (initPrice.greaterThan(Decimal.one())) {
initPrice = Decimal.one();
}
_initialUSDPrice = initPrice;
_initTimed();
}
function _thaw(Decimal.D256 memory peg)
internal
view
returns (Decimal.D256 memory)
{
if (isTimeEnded()) {
return peg;
}
uint256 elapsed = timeSinceStart();
uint256 remaining = remainingTime();
(Decimal.D256 memory uniswapPeg, ) = uniswapOracle.read();
Decimal.D256 memory price = uniswapPeg.div(peg);
// average price time weighted from initial to target
Decimal.D256 memory weightedPrice =
_initialUSDPrice.mul(remaining).add(price.mul(elapsed)).div(duration);
// divide from peg to return a peg FEI per X instead of a price USD per FEI
return uniswapPeg.div(weightedPrice);
}
function _getOracleValue()
internal
view
returns (Decimal.D256 memory, bool)
{
if (bondingCurve.atScale()) {
return uniswapOracle.read();
}
return (bondingCurve.getCurrentPrice(), true);
}
}
|
@notice the referenced uniswap oracle price @notice the referenced bonding curve @notice BondingCurveOracle constructor @param _core Fei Core to reference @param _oracle Uniswap Oracle to report from @param _bondingCurve Bonding curve to report from @param _duration price thawing duration
|
) public CoreRef(_core) Timed(_duration) {
uniswapOracle = IOracle(_oracle);
bondingCurve = IBondingCurve(_bondingCurve);
_pause();
}
| 13,474,417 |
[
1,
5787,
8042,
640,
291,
91,
438,
20865,
6205,
225,
326,
8042,
8427,
310,
8882,
225,
605,
1434,
310,
9423,
23601,
3885,
225,
389,
3644,
5782,
77,
4586,
358,
2114,
225,
389,
280,
16066,
1351,
291,
91,
438,
28544,
358,
2605,
628,
225,
389,
26425,
310,
9423,
605,
1434,
310,
8882,
358,
2605,
628,
225,
389,
8760,
6205,
286,
2219,
310,
3734,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
262,
1071,
4586,
1957,
24899,
3644,
13,
23925,
24899,
8760,
13,
288,
203,
3639,
640,
291,
91,
438,
23601,
273,
1665,
16873,
24899,
280,
16066,
1769,
203,
3639,
8427,
310,
9423,
273,
16178,
310,
9423,
24899,
26425,
310,
9423,
1769,
203,
3639,
389,
19476,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
import "./ManyToOneImplementationHolder.sol";
import {
DelegateCallProxyManyToOne
} from "./DelegateCallProxyManyToOne.sol";
import {
DelegateCallProxyOneToOne
} from "./DelegateCallProxyOneToOne.sol";
import { SaltyLib as Salty } from "./SaltyLib.sol";
import { Create2 } from "@openzeppelin/contracts/utils/Create2.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import "../Owned.sol";
/**
* @dev Contract that manages deployment and upgrades of delegatecall proxies.
*
* An implementation identifier can be created on the proxy manager which is
* used to specify the logic address for a particular contract type, and to
* upgrade the implementation as needed.
*
* A one-to-one proxy is a single proxy contract with an upgradeable implementation
* address.
*
* A many-to-one proxy is a single upgradeable implementation address that may be
* used by many proxy contracts.
*/
contract DelegateCallProxyManager is Owned {
/* --- Constants --- */
bytes32 internal constant ONE_TO_ONE_CODEHASH
= keccak256(type(DelegateCallProxyOneToOne).creationCode);
bytes32 internal constant MANY_TO_ONE_CODEHASH
= keccak256(type(DelegateCallProxyManyToOne).creationCode);
bytes32 internal constant IMPLEMENTATION_HOLDER_CODEHASH
= keccak256(type(ManyToOneImplementationHolder).creationCode);
/* --- Events --- */
event DeploymentApprovalGranted(address deployer);
event DeploymentApprovalRevoked(address deployer);
event ManyToOne_ImplementationCreated(
bytes32 implementationID,
address implementationAddress
);
event ManyToOne_ImplementationUpdated(
bytes32 implementationID,
address implementationAddress
);
event ManyToOne_ProxyDeployed(
bytes32 implementationID,
address proxyAddress
);
event OneToOne_ProxyDeployed(
address proxyAddress,
address implementationAddress
);
event OneToOne_ImplementationUpdated(
address proxyAddress,
address implementationAddress
);
/* --- Storage --- */
// Addresses allowed to deploy many-to-one proxies.
mapping(address => bool) internal _approvedDeployers;
// Maps implementation holders to their implementation IDs.
mapping(bytes32 => address) internal _implementationHolders;
// Temporary value used in the many-to-one proxy constructor.
// The many-to-one proxy contract is deployed with create2 and
// uses static initialization code for simple address derivation,
// so it calls the proxy manager in the constructor to get this
// address in order to save it as an immutable in the bytecode.
address internal _implementationHolder;
/* --- Modifiers --- */
modifier _admin_ {
require(
msg.sender == _owner || _approvedDeployers[msg.sender],
"ERR_NOT_APPROVED"
);
_;
}
/* --- Constructor --- */
constructor() public Owned(msg.sender) {}
/* --- Controls --- */
/**
* @dev Allows `deployer` to deploy many-to-one proxies.
*/
function approveDeployer(address deployer) external _owner_ {
_approvedDeployers[deployer] = true;
emit DeploymentApprovalGranted(deployer);
}
/**
* @dev Prevents `deployer` from deploying many-to-one proxies.
*/
function revokeDeployerApproval(address deployer) external _owner_ {
_approvedDeployers[deployer] = false;
emit DeploymentApprovalRevoked(deployer);
}
/* --- Implementation Management --- */
/**
* @dev Creates a many-to-one proxy relationship.
*
* Deploys an implementation holder contract which stores the
* implementation address for many proxies. The implementation
* address can be updated on the holder to change the runtime
* code used by all its proxies.
*
* @param implementationID ID for the implementation, used to identify the
* proxies that use it. Also used as the salt in the create2 call when
* deploying the implementation holder contract.
* @param implementation Address with the runtime code the proxies
* should use.
*/
function createManyToOneProxyRelationship(
bytes32 implementationID,
address implementation
)
external
_owner_
{
// Deploy the implementation holder contract with the implementation
// ID as the create2 salt.
address implementationHolder = Create2.deploy(
0,
implementationID,
type(ManyToOneImplementationHolder).creationCode
);
// Store the implementation holder address
_implementationHolders[implementationID] = implementationHolder;
// Sets the implementation address.
_setImplementation(implementationHolder, implementation);
emit ManyToOne_ImplementationCreated(
implementationID,
implementation
);
}
/**
* @dev Updates the implementation address for a many-to-one
* proxy relationship.
*
* @param implementationID Identifier for the implementation.
* @param implementation Address with the runtime code the proxies
* should use.
*/
function setImplementationAddressManyToOne(
bytes32 implementationID,
address implementation
)
external
_owner_
{
// Read the implementation holder address from storage.
address implementationHolder = _implementationHolders[implementationID];
// Verify that the implementation exists.
require(implementationHolder != address(0), "ERR_IMPLEMENTATION_ID");
// Set the implementation address
_setImplementation(implementationHolder, implementation);
emit ManyToOne_ImplementationUpdated(
implementationID,
implementation
);
}
/**
* @dev Updates the implementation address for a one-to-one proxy.
*
* Note: This could work for many-to-one as well if the caller
* provides the implementation holder address in place of the
* proxy address, as they use the same access control and update
* mechanism.
*
* @param proxyAddress Address of the deployed proxy
* @param implementation Address with the runtime code for
* the proxy to use.
*/
function setImplementationAddressOneToOne(
address proxyAddress,
address implementation
)
external
_owner_
{
// Set the implementation address
_setImplementation(proxyAddress, implementation);
emit OneToOne_ImplementationUpdated(proxyAddress, implementation);
}
/* --- Proxy Deployment --- */
/**
* @dev Deploy a proxy contract with a one-to-one relationship
* with its implementation.
*
* The proxy will have its own implementation address which can
* be updated by the proxy manager.
*
* @param suppliedSalt Salt provided by the account requesting deployment.
* @param implementation Address of the contract with the runtime
* code that the proxy should use.
*/
function deployProxyOneToOne(
bytes32 suppliedSalt,
address implementation
)
external
_owner_
returns(address proxyAddress)
{
// Derive the create2 salt from the deployment requester's address
// and the requester-supplied salt.
bytes32 salt = Salty.deriveOneToOneSalt(msg.sender, suppliedSalt);
// Deploy the proxy
proxyAddress = Create2.deploy(
0,
salt,
type(DelegateCallProxyOneToOne).creationCode
);
// Set the implementation address on the new proxy.
_setImplementation(proxyAddress, implementation);
emit OneToOne_ProxyDeployed(proxyAddress, implementation);
}
/**
* @dev Deploy a proxy with a many-to-one relationship with its implemenation.
*
* The proxy will call the implementation holder for every transaction to
* determine the address to use in calls.
*
* @param implementationID Identifier for the proxy's implementation.
* @param suppliedSalt Salt provided by the account requesting deployment.
*/
function deployProxyManyToOne(bytes32 implementationID, bytes32 suppliedSalt)
external
_admin_
returns(address proxyAddress)
{
// Read the implementation holder address from storage.
address implementationHolder = _implementationHolders[implementationID];
// Verify that the implementation exists.
require(implementationHolder != address(0), "ERR_IMPLEMENTATION_ID");
// Derive the create2 salt from the deployment requester's address, the
// implementation ID and the requester-supplied salt.
bytes32 salt = Salty.deriveManyToOneSalt(
msg.sender,
implementationID,
suppliedSalt
);
// Set the implementation holder address in storage so the proxy
// constructor can query it.
_implementationHolder = implementationHolder;
// Deploy the proxy, which will query the implementation holder address
// and save it as an immutable in the contract bytecode.
proxyAddress = Create2.deploy(
0,
salt,
type(DelegateCallProxyManyToOne).creationCode
);
// Remove the address from temporary storage.
_implementationHolder = address(0);
emit ManyToOne_ProxyDeployed(
implementationID,
proxyAddress
);
}
/* --- Queries --- */
function isApprovedDeployer(address deployer) external view returns (bool) {
return _approvedDeployers[deployer];
}
/**
* @dev Queries the temporary storage value `_implementationHolder`.
* This is used in the constructor of the many-to-one proxy contract
* so that the create2 address is static (adding constructor arguments
* would change the codehash) and the implementation holder can be
* stored as a constant.
*/
function getImplementationHolder()
external
view
returns (address)
{
return _implementationHolder;
}
/**
* @dev Returns the address of the implementation holder contract
* for `implementationID`.
*/
function getImplementationHolder(
bytes32 implementationID
)
external
view
returns (address)
{
return _implementationHolders[implementationID];
}
/**
* @dev Computes the create2 address for a one-to-one proxy requested
* by `originator` using `suppliedSalt`.
*
* @param originator Address of the account requesting deployment.
* @param suppliedSalt Salt provided by the account requesting deployment.
*/
function computeProxyAddressOneToOne(
address originator,
bytes32 suppliedSalt
)
external
view
returns (address)
{
bytes32 salt = Salty.deriveOneToOneSalt(originator, suppliedSalt);
return Create2.computeAddress(salt, ONE_TO_ONE_CODEHASH);
}
/**
* @dev Computes the create2 address for a many-to-one proxy for the
* implementation `implementationID` requested by `originator` using
* `suppliedSalt`.
*
* @param originator Address of the account requesting deployment.
* @param implementationID The identifier for the contract implementation.
* @param suppliedSalt Salt provided by the account requesting deployment.
*/
function computeProxyAddressManyToOne(
address originator,
bytes32 implementationID,
bytes32 suppliedSalt
)
external
view
returns (address)
{
bytes32 salt = Salty.deriveManyToOneSalt(
originator,
implementationID,
suppliedSalt
);
return Create2.computeAddress(salt, MANY_TO_ONE_CODEHASH);
}
/**
* @dev Computes the create2 address of the implementation holder
* for `implementationID`.
*
* @param implementationID The identifier for the contract implementation.
*/
function computeHolderAddressManyToOne(bytes32 implementationID)
public
view
returns (address)
{
return Create2.computeAddress(
implementationID,
IMPLEMENTATION_HOLDER_CODEHASH
);
}
/* --- Internal Functions --- */
/**
* @dev Sets the implementation address for a one-to-one proxy or
* many-to-one implementation holder. Both use the same access
* control and update mechanism, which is the receipt of a call
* from the proxy manager with the abi-encoded implementation address
* as the only calldata.
*
* Note: Verifies that the implementation address is a contract.
*
* @param proxyOrHolder Address of the one-to-one proxy or
* many-to-one implementation holder contract.
* @param implementation Address of the contract with the runtime
* code that the proxy or proxies should use.
*/
function _setImplementation(
address proxyOrHolder,
address implementation
) internal {
// Verify that the implementation address is a contract.
require(Address.isContract(implementation), "ERR_NOT_CONTRACT");
// Set the implementation address on the contract.
// solium-disable-next-line security/no-low-level-calls
(bool success,) = proxyOrHolder.call(abi.encode(implementation));
require(success, "ERR_SET_ADDRESS_REVERT");
}
}
|
* @dev Queries the temporary storage value `_implementationHolder`. This is used in the constructor of the many-to-one proxy contract so that the create2 address is static (adding constructor arguments would change the codehash) and the implementation holder can be stored as a constant./
|
function getImplementationHolder()
external
view
returns (address)
{
return _implementationHolder;
}
| 12,733,973 |
[
1,
9592,
326,
6269,
2502,
460,
1375,
67,
30810,
6064,
8338,
1220,
353,
1399,
316,
326,
3885,
434,
326,
4906,
17,
869,
17,
476,
2889,
6835,
1427,
716,
326,
752,
22,
1758,
353,
760,
261,
3439,
3885,
1775,
4102,
2549,
326,
981,
2816,
13,
471,
326,
4471,
10438,
848,
506,
4041,
487,
279,
5381,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
445,
336,
13621,
6064,
1435,
203,
565,
3903,
203,
565,
1476,
203,
565,
1135,
261,
2867,
13,
203,
225,
288,
203,
565,
327,
389,
30810,
6064,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "../l2/L2Lib.sol";
import "../utils/FurLib.sol";
import "../utils/FurProxy.sol";
import "../utils/MetaData.sol";
import "./ZoneDefinition.sol";
/// @title Zones
/// @author LFG Gaming LLC
/// @notice Zone management (overrides) for Furballs
contract Zones is FurProxy {
// Tightly packed last-reward data
mapping(uint256 => FurLib.ZoneReward) public zoneRewards;
// Zone Number => Zone
mapping(uint32 => IZone) public zoneMap;
constructor(address furballsAddress) FurProxy(furballsAddress) { }
// -----------------------------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------------------------
/// @notice The new instant function for play + move
function play(FurLib.SnackMove[] calldata snackMoves, uint32 zone) external {
furballs.engine().snackAndMove(snackMoves, zone, msg.sender);
}
/// @notice Check if Timekeeper is enabled for a given tokenId
/// @dev TK=enabled by defauld (mode == 0); other modes (?); bools are expensive to store thus modes
function isTimekeeperEnabled(uint256 tokenId) external view returns(bool) {
return zoneRewards[tokenId].mode != 1;
}
/// @notice Allow players to disable TK on their furballs
function disableTimekeeper(uint256[] calldata tokenIds) external {
bool isJob = _allowedJob(msg.sender);
for (uint i=0; i<tokenIds.length; i++) {
require(isJob || furballs.ownerOf(tokenIds[i]) == msg.sender, "OWN");
require(zoneRewards[tokenIds[i]].mode == 0, "MODE");
zoneRewards[tokenIds[i]].mode = 1;
zoneRewards[tokenIds[i]].timestamp = uint64(block.timestamp);
}
}
/// @notice Allow players to disable TK on their furballs
/// @dev timestamp is not set because TK can read the furball last action,
/// so it preserves more data and reduces gas to not keep track!
function enableTimekeeper(uint256[] calldata tokenIds) external {
bool isJob = _allowedJob(msg.sender);
for (uint i=0; i<tokenIds.length; i++) {
require(isJob || furballs.ownerOf(tokenIds[i]) == msg.sender, "OWN");
require(zoneRewards[tokenIds[i]].mode != 0, "MODE");
zoneRewards[tokenIds[i]].mode = 0;
}
}
/// @notice Get the full reward struct
function getZoneReward(uint256 tokenId) external view returns(FurLib.ZoneReward memory) {
return zoneRewards[tokenId];
}
/// @notice Pre-computed rarity for Furballs
function getFurballZoneReward(uint32 furballNum) external view returns(FurLib.ZoneReward memory) {
return zoneRewards[furballs.tokenByIndex(furballNum - 1)];
}
/// @notice Get contract address for a zone definition
function getZoneAddress(uint32 zoneNum) external view returns(address) {
return address(zoneMap[zoneNum]);
}
/// @notice Public display (OpenSea, etc.)
function getName(uint32 zoneNum) public view returns(string memory) {
return _zoneName(zoneNum);
}
/// @notice Zones can have unique background SVGs
function render(uint256 tokenId) external view returns(string memory) {
uint zoneNum = zoneRewards[tokenId].zoneOffset;
if (zoneNum == 0) return "";
IZone zone = zoneMap[uint32(zoneNum - 1)];
return address(zone) == address(0) ? "" : zone.background();
}
/// @notice OpenSea metadata
function attributesMetadata(
FurLib.FurballStats calldata stats, uint256 tokenId, uint32 maxExperience
) external view returns(bytes memory) {
FurLib.Furball memory furball = stats.definition;
uint level = furball.level;
uint32 zoneNum = L2Lib.getZoneId(zoneRewards[tokenId].zoneOffset, furball.zone);
if (zoneNum < 0x10000) {
// When in explore, we check if TK has accrued more experience for this furball
FurLib.ZoneReward memory last = zoneRewards[tokenId];
if (last.timestamp > furball.last) {
level = FurLib.expToLevel(furball.experience + zoneRewards[tokenId].experience, maxExperience);
}
}
return abi.encodePacked(
MetaData.traitValue("Level", level),
MetaData.trait("Zone", _zoneName(zoneNum))
);
}
// -----------------------------------------------------------------------------------------------
// GameAdmin
// -----------------------------------------------------------------------------------------------
/// @notice Pre-compute some stats
function computeStats(uint32 furballNum, uint16 baseRarity) external gameAdmin {
_computeStats(furballNum, baseRarity);
}
/// @notice Update the timestamps on Furballs
function timestampModes(
uint256[] calldata tokenIds, uint64[] calldata lastTimestamps, uint8[] calldata modes
) external gameAdmin {
for (uint i=0; i<tokenIds.length; i++) {
zoneRewards[tokenIds[i]].timestamp = lastTimestamps[i];
zoneRewards[tokenIds[i]].mode = modes[i];
}
}
/// @notice Update the modes
function setModes(
uint256[] calldata tokenIds, uint8[] calldata modes
) external gameAdmin {
for (uint i=0; i<tokenIds.length; i++) {
zoneRewards[tokenIds[i]].mode = modes[i];
}
}
/// @notice Update the timestamps on Furballs
function setTimestamps(
uint256[] calldata tokenIds, uint64[] calldata lastTimestamps
) external gameAdmin {
for (uint i=0; i<tokenIds.length; i++) {
zoneRewards[tokenIds[i]].timestamp = lastTimestamps[i];
}
}
/// @notice When a furball earns FUR via Timekeeper
function addFur(uint256 tokenId, uint32 fur) external gameAdmin {
zoneRewards[tokenId].timestamp = uint64(block.timestamp);
zoneRewards[tokenId].fur += fur;
}
/// @notice When a furball earns EXP via Timekeeper
function addExp(uint256 tokenId, uint32 exp) external gameAdmin {
zoneRewards[tokenId].timestamp = uint64(block.timestamp);
zoneRewards[tokenId].experience += exp;
}
/// @notice Bulk EXP option for efficiency
function addExps(uint256[] calldata tokenIds, uint32[] calldata exps) external gameAdmin {
for (uint i=0; i<tokenIds.length; i++) {
zoneRewards[tokenIds[i]].timestamp = uint64(block.timestamp);
zoneRewards[tokenIds[i]].experience = exps[i];
}
}
/// @notice Define the attributes of a zone
function defineZone(address zoneAddr) external gameAdmin {
IZone zone = IZone(zoneAddr);
zoneMap[uint32(zone.number())] = zone;
}
/// @notice Hook for zone change
function enterZone(uint256 tokenId, uint32 zone) external gameAdmin {
_enterZone(tokenId, zone);
}
/// @notice Allow TK to override a zone
function overrideZone(uint256[] calldata tokenIds, uint32 zone) external gameAdmin {
for (uint i=0; i<tokenIds.length; i++) {
_enterZone(tokenIds[i], zone);
}
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
function _computeStats(uint32 furballNum, uint16 rarity) internal {
uint256 tokenId = furballs.tokenByIndex(furballNum - 1);
if (uint8(tokenId) == 0) {
if (FurLib.extractBytes(tokenId, 5, 1) == 6) rarity += 10; // Furdenza body
if (FurLib.extractBytes(tokenId, 11, 1) == 12) rarity += 10; // Furdenza hoodie
}
zoneRewards[tokenId].rarity = rarity;
}
/// @notice When a furball changes zone, we need to clear the zoneRewards timestamp
function _enterZone(uint256 tokenId, uint32 zoneNum) internal {
if (zoneRewards[tokenId].timestamp != 0) {
zoneRewards[tokenId].timestamp = 0;
zoneRewards[tokenId].experience = 0;
zoneRewards[tokenId].fur = 0;
}
zoneRewards[tokenId].zoneOffset = (zoneNum + 1);
if (zoneNum == 0 || zoneNum == 0x10000) return;
// Additional requirement logic may occur in the zone
IZone zone = zoneMap[zoneNum];
if (address(zone) != address(0)) zone.enterZone(tokenId);
}
/// @notice Public display (OpenSea, etc.)
function _zoneName(uint32 zoneNum) internal view returns(string memory) {
if (zoneNum == 0) return "Explore";
if (zoneNum == 0x10000) return "Battle";
IZone zone = zoneMap[zoneNum];
return address(zone) == address(0) ? "?" : zone.name();
}
function _allowedJob(address sender) internal view returns(bool) {
return sender == furballs.engine().l2Proxy() ||
_permissionCheck(sender) >= FurLib.PERMISSION_ADMIN;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "../utils/FurLib.sol";
/// @title L2Lib
/// @author LFG Gaming LLC
/// @notice Utilities for L2
library L2Lib {
// Payload for EIP-712 signature
struct OAuthToken {
address owner;
uint32 access;
uint64 deadline;
bytes signature;
}
/// Loot changes on a token for resolve function
struct LootResolution {
uint256 tokenId;
uint128 itemGained;
uint128 itemLost;
}
/// Everything that can happen to a Furball in a single "round"
struct RoundResolution {
uint256 tokenId;
uint32 expGained; //
uint8 zoneListNum;
uint128[] items;
uint64[] snackStacks;
}
// Signed message giving access to a set of expectations & constraints
struct TimekeeperRequest {
RoundResolution[] rounds;// What happened; passed by server.
address sender;
uint32 tickets; // Tickets to be spent
uint32 furGained; // How much FUR the player expects
uint32 furSpent; // How much FUR the player spent
uint32 furReal; // The ACTUAL FUR the player earned (must be >= furGained)
uint8 mintEdition; // Mint a furball from this edition
uint8 mintCount; // Mint this many Furballs
uint64 deadline; // When it is good until
// uint256[] movements; // Moves made by furballs
}
// Track the results of a TimekeeperAuthorization
struct TimekeeperResult {
uint64 timestamp;
uint8 errorCode;
}
/// @notice unpacks the override (offset)
function getZoneId(uint32 offset, uint32 defaultValue) internal pure returns(uint32) {
return offset > 0 ? (offset - 1) : defaultValue;
}
// // Play = collect / move zones
// struct ActionPlay {
// uint256[] tokenIds;
// uint32 zone;
// }
// // Snack = FurLib.Feeding
// // Loot (upgrade)
// struct ActionUpgrade {
// uint256 tokenId;
// uint128 lootId;
// uint8 chances;
// }
// // Signature package that accompanies moves
// struct MoveSig {
// bytes signature;
// uint64 deadline;
// address actor;
// }
// // Signature + play actions
// struct SignedPlayMove {
// bytes signature;
// uint64 deadline;
// // address actor;
// uint32 zone;
// uint256[] tokenIds;
// }
// // What does a player earn from pool?
// struct PoolReward {
// address actor;
// uint32 fur;
// }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
/// @title FurLib
/// @author LFG Gaming LLC
/// @notice Utilities for Furballs
/// @dev Each of the structs are designed to fit within 256
library FurLib {
// Metadata about a wallet.
struct Account {
uint64 created; // First time this account received a furball
uint32 numFurballs; // Number of furballs it currently holds
uint32 maxFurballs; // Max it has ever held
uint16 maxLevel; // Max level of any furball it currently holds
uint16 reputation; // Value assigned by moderators to boost standing
uint16 standing; // Computed current standing
uint8 permissions; // 0 = user, 1 = moderator, 2 = admin, 3 = owner
}
// Key data structure given to clients for high-level furball access (furballs.stats)
struct FurballStats {
uint16 expRate;
uint16 furRate;
RewardModifiers modifiers;
Furball definition;
Snack[] snacks;
}
// The response from a single play session indicating rewards
struct Rewards {
uint16 levels;
uint32 experience;
uint32 fur;
uint128 loot;
}
// Stored data structure in Furballs master contract which keeps track of mutable data
struct Furball {
uint32 number; // Overall number, starting with 1
uint16 count; // Index within the collection
uint16 rarity; // Total rarity score for later boosts
uint32 experience; // EXP
uint32 zone; // When exploring, the zone number. Otherwise, battling.
uint16 level; // Current EXP => level; can change based on level up during collect
uint16 weight; // Total weight (number of items in inventory)
uint64 birth; // Timestamp of furball creation
uint64 trade; // Timestamp of last furball trading wallets
uint64 last; // Timestamp of last action (battle/explore)
uint32 moves; // The size of the collection array for this furball, which is move num.
uint256[] inventory; // IDs of items in inventory
}
// A runtime-calculated set of properties that can affect Furball production during collect()
struct RewardModifiers {
uint16 expPercent;
uint16 furPercent;
uint16 luckPercent;
uint16 happinessPoints;
uint16 energyPoints;
uint32 zone;
}
// For sale via loot engine.
struct Snack {
uint32 snackId; // Unique ID
uint32 duration; // How long it lasts, !expressed in intervals!
uint16 furCost; // How much FUR
uint16 happiness; // +happiness bost points
uint16 energy; // +energy boost points
uint16 count; // How many in stack?
uint64 fed; // When was it fed (if it is active)?
}
// Input to the feed() function for multi-play
struct Feeding {
uint256 tokenId;
uint32 snackId;
uint16 count;
}
// Internal tracker for a furball when gaining in the zone
struct ZoneReward {
uint8 mode; // 1==tk disabled
uint16 rarity;
uint32 zoneOffset; // One-indexed to indicate presence :(
uint32 fur;
uint32 experience;
uint64 timestamp;
}
// Calldata for a Furball which gets a snack while moving
struct SnackMove {
uint256 tokenId;
uint32[] snackIds;
}
uint32 public constant Max32 = type(uint32).max;
uint8 public constant PERMISSION_USER = 1;
uint8 public constant PERMISSION_MODERATOR = 2;
uint8 public constant PERMISSION_ADMIN = 4;
uint8 public constant PERMISSION_OWNER = 5;
uint8 public constant PERMISSION_CONTRACT = 0x10;
uint32 public constant EXP_PER_INTERVAL = 500;
uint32 public constant FUR_PER_INTERVAL = 100;
uint8 public constant LOOT_BYTE_STAT = 1;
uint8 public constant LOOT_BYTE_RARITY = 2;
uint8 public constant SNACK_BYTE_ENERGY = 0;
uint8 public constant SNACK_BYTE_HAPPINESS = 2;
uint256 public constant OnePercent = 1000;
uint256 public constant OneHundredPercent = 100000;
/// @notice Shortcut for equations that saves gas
/// @dev The expression (0x100 ** byteNum) is expensive; this covers byte packing for editions.
function bytePower(uint8 byteNum) internal pure returns (uint256) {
if (byteNum == 0) return 0x1;
if (byteNum == 1) return 0x100;
if (byteNum == 2) return 0x10000;
if (byteNum == 3) return 0x1000000;
if (byteNum == 4) return 0x100000000;
if (byteNum == 5) return 0x10000000000;
if (byteNum == 6) return 0x1000000000000;
if (byteNum == 7) return 0x100000000000000;
if (byteNum == 8) return 0x10000000000000000;
if (byteNum == 9) return 0x1000000000000000000;
if (byteNum == 10) return 0x100000000000000000000;
if (byteNum == 11) return 0x10000000000000000000000;
if (byteNum == 12) return 0x1000000000000000000000000;
return (0x100 ** byteNum);
}
/// @notice Helper to get a number of bytes from a value
function extractBytes(uint value, uint8 startAt, uint8 numBytes) internal pure returns (uint) {
return (value / bytePower(startAt)) % bytePower(numBytes);
}
/// @notice Converts exp into a sqrt-able number.
function expToLevel(uint32 exp, uint32 maxExp) internal pure returns(uint256) {
exp = exp > maxExp ? maxExp : exp;
return sqrt(exp < 100 ? 0 : ((exp + exp - 100) / 100));
}
/// @notice Simple square root function using the Babylonian method
function sqrt(uint32 x) internal pure returns(uint256) {
if (x < 1) return 0;
if (x < 4) return 1;
uint z = (x + 1) / 2;
uint y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
return y;
}
/// @notice Convert bytes into a hex str, e.g., an address str
function bytesHex(bytes memory data) internal pure returns(string memory) {
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(data.length * 2);
for (uint i = 0; i < data.length; i++) {
str[i*2] = alphabet[uint(uint8(data[i] >> 4))];
str[1 + i*2] = alphabet[uint(uint8(data[i] & 0x0f))];
}
return string(str);
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
string memory table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
uint256 encodedLen = 4 * ((data.length + 2) / 3);
string memory result = new string(encodedLen + 32);
assembly {
mstore(result, encodedLen)
let tablePtr := add(table, 1)
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
let resultPtr := add(result, 32)
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "../Furballs.sol";
import "./FurLib.sol";
/// @title FurProxy
/// @author LFG Gaming LLC
/// @notice Manages a link from a sub-contract back to the master Furballs contract
/// @dev Provides permissions by means of proxy
abstract contract FurProxy {
Furballs public furballs;
constructor(address furballsAddress) {
furballs = Furballs(furballsAddress);
}
/// @notice Allow upgrading contract links
function setFurballs(address addr) external onlyOwner {
furballs = Furballs(addr);
}
/// @notice Proxied from permissions lookup
modifier onlyOwner() {
require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_OWNER, "OWN");
_;
}
/// @notice Permission modifier for moderators (covers owner)
modifier gameAdmin() {
require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_ADMIN, "GAME");
_;
}
/// @notice Permission modifier for moderators (covers admin)
modifier gameModerators() {
require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_MODERATOR, "MOD");
_;
}
/// @notice Generalized permissions flag for a given address
function _permissionCheck(address addr) internal view returns (uint) {
if(addr != address(0)) {
uint256 size;
assembly { size := extcodesize(addr) }
if (addr == tx.origin && size == 0) {
return _userPermissions(addr);
}
}
return _contractPermissions(addr);
}
/// @notice Permission lookup (for loot engine approveSender)
function _permissions(address addr) internal view returns (uint8) {
// User permissions will return "zero" quickly if this didn't come from a wallet.
if (addr == address(0)) return 0;
uint256 size;
assembly { size := extcodesize(addr) }
if (size != 0) return 0;
return _userPermissions(addr);
}
function _contractPermissions(address addr) internal view returns (uint) {
if (addr == address(furballs) ||
addr == address(furballs.engine()) ||
addr == address(furballs.furgreement()) ||
addr == address(furballs.governance()) ||
addr == address(furballs.fur()) ||
addr == address(furballs.engine().zones())
) {
return FurLib.PERMISSION_CONTRACT;
}
return 0;
}
function _userPermissions(address addr) internal view returns (uint8) {
// Invalid addresses include contracts an non-wallet interactions, which have no permissions
if (addr == address(0)) return 0;
if (addr == furballs.owner()) return FurLib.PERMISSION_OWNER;
if (furballs.isAdmin(addr)) return FurLib.PERMISSION_ADMIN;
if (furballs.isModerator(addr)) return FurLib.PERMISSION_MODERATOR;
return FurLib.PERMISSION_USER;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "./FurLib.sol";
/// @title MetaData
/// @author LFG Gaming LLC
/// @notice Utilities for creating MetaData (e.g., OpenSea)
library MetaData {
function trait(string memory traitType, string memory value) internal pure returns (bytes memory) {
return abi.encodePacked('{"trait_type": "', traitType,'", "value": "', value, '"}, ');
}
function traitNumberDisplay(
string memory traitType, string memory displayType, uint256 value
) internal pure returns (bytes memory) {
return abi.encodePacked(
'{"trait_type": "', traitType,
bytes(displayType).length > 0 ? '", "display_type": "' : '', displayType,
'", "value": ', FurLib.uint2str(value), '}, '
);
}
function traitValue(string memory traitType, uint256 value) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "", value);
}
/// @notice Convert a modifier percentage (120%) into a metadata +20% boost
function traitBoost(
string memory traitType, uint256 percent
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "boost_percentage", percent > 100 ? (percent - 100) : 0);
}
function traitNumber(
string memory traitType, uint256 value
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "number", value);
}
function traitDate(
string memory traitType, uint256 value
) internal pure returns (bytes memory) {
return traitNumberDisplay(traitType, "date", value);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./Zones.sol";
import "../utils/FurProxy.sol";
/// @title IZone
/// @author LFG Gaming LLC
/// @notice The loot engine is patchable by replacing the Furballs' engine with a new version
interface IZone is IERC165 {
function number() external view returns(uint);
function name() external view returns(string memory);
function background() external view returns(string memory);
function enterZone(uint256 tokenId) external;
}
contract ZoneDefinition is ERC165, IZone, FurProxy {
uint override public number;
string override public name;
string override public background;
constructor(address furballsAddress, uint32 zoneNum) FurProxy(furballsAddress) {
number = zoneNum;
}
function update(string calldata zoneName, string calldata zoneBk) external gameAdmin {
name = zoneName;
background = zoneBk;
}
/// @notice A zone can hook a furball's entry...
function enterZone(uint256 tokenId) external override gameAdmin {
// Nothing to see here.
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IZone).interfaceId ||
super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
// import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./editions/IFurballEdition.sol";
import "./engines/ILootEngine.sol";
import "./engines/EngineA.sol";
import "./utils/FurLib.sol";
import "./utils/FurDefs.sol";
import "./utils/FurProxy.sol";
import "./utils/Moderated.sol";
import "./utils/Governance.sol";
import "./Fur.sol";
import "./Furgreement.sol";
// import "hardhat/console.sol";
/// @title Furballs
/// @author LFG Gaming LLC
/// @notice Mints Furballs on the Ethereum blockchain
/// @dev https://furballs.com/contract
contract Furballs is ERC721Enumerable, Moderated {
Fur public fur;
IFurballEdition[] public editions;
ILootEngine public engine;
Governance public governance;
Furgreement public furgreement;
// tokenId => furball data
mapping(uint256 => FurLib.Furball) public furballs;
// tokenId => all rewards assigned to that Furball
mapping(uint256 => FurLib.Rewards) public collect;
// The amount of time over which FUR/EXP is accrued (usually 3600=>1hour); used with test servers
uint256 public intervalDuration;
// When play/collect runs, returns rewards
event Collection(uint256 tokenId, uint256 responseId);
// Inventory change event
event Inventory(uint256 tokenId, uint128 lootId, uint16 dropped);
constructor(uint256 interval) ERC721("Furballs", "FBL") {
intervalDuration = interval;
}
// -----------------------------------------------------------------------------------------------
// Public transactions
// -----------------------------------------------------------------------------------------------
/// @notice Mints a new furball from the current edition (if there are any remaining)
/// @dev Limits and fees are set by IFurballEdition
function mint(address[] memory to, uint8 editionIndex, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
require(to.length == 1 || permissions >= FurLib.PERMISSION_MODERATOR, "MULT");
for (uint8 i=0; i<to.length; i++) {
fur.purchaseMint(sender, permissions, to[i], editions[editionIndex]);
_spawn(to[i], editionIndex, 0);
}
}
/// @notice Feeds the furball a snack
/// @dev Delegates logic to fur
function feed(FurLib.Feeding[] memory feedings, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
uint256 len = feedings.length;
for (uint256 i=0; i<len; i++) {
fur.purchaseSnack(sender, permissions, feedings[i].tokenId, feedings[i].snackId, feedings[i].count);
}
}
/// @notice Begins exploration mode with the given furballs
/// @dev Multiple furballs accepted at once to reduce gas fees
/// @param tokenIds The furballs which should start exploring
/// @param zone The explore zone (otherwize, zero for battle mode)
function playMany(uint256[] memory tokenIds, uint32 zone, address actor) external {
(address sender, uint8 permissions) = _approvedSender(actor);
for (uint256 i=0; i<tokenIds.length; i++) {
// Run reward collection
_collect(tokenIds[i], sender, permissions);
// Set new zone (if allowed; enterZone may throw)
furballs[tokenIds[i]].zone = uint32(engine.enterZone(tokenIds[i], zone, tokenIds));
}
}
/// @notice Re-dropping loot allows players to pay $FUR to re-roll an inventory slot
/// @param tokenId The furball in question
/// @param lootId The lootId in its inventory to re-roll
function upgrade(
uint256 tokenId, uint128 lootId, uint8 chances, address actor
) external {
// Attempt upgrade (random chance).
(address sender, uint8 permissions) = _approvedSender(actor);
uint128 up = fur.purchaseUpgrade(_baseModifiers(tokenId), sender, permissions, tokenId, lootId, chances);
if (up != 0) {
_drop(tokenId, lootId, 1);
_pickup(tokenId, up);
}
}
/// @notice The LootEngine can directly send loot to a furball!
/// @dev This allows for gameplay expansion, i.e., new game modes
/// @param tokenId The furball to gain the loot
/// @param lootId The loot ID being sent
function pickup(uint256 tokenId, uint128 lootId) external gameAdmin {
_pickup(tokenId, lootId);
}
/// @notice The LootEngine can cause a furball to drop loot!
/// @dev This allows for gameplay expansion, i.e., new game modes
/// @param tokenId The furball
/// @param lootId The item to drop
/// @param count the number of that item to drop
function drop(uint256 tokenId, uint128 lootId, uint8 count) external gameAdmin {
_drop(tokenId, lootId, count);
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
function _slotNum(uint256 tokenId, uint128 lootId) internal view returns(uint256) {
for (uint8 i=0; i<furballs[tokenId].inventory.length; i++) {
if (furballs[tokenId].inventory[i] / 256 == lootId) {
return i + 1;
}
}
return 0;
}
/// @notice Remove an inventory item from a furball
function _drop(uint256 tokenId, uint128 lootId, uint8 count) internal {
uint256 slot = _slotNum(tokenId, lootId);
require(slot > 0 && slot <= uint32(furballs[tokenId].inventory.length), "SLOT");
slot -= 1;
uint8 stackSize = uint8(furballs[tokenId].inventory[slot] % 0x100);
if (count == 0 || count >= stackSize) {
// Drop entire stack
uint16 len = uint16(furballs[tokenId].inventory.length);
if (len > 1) {
furballs[tokenId].inventory[slot] = furballs[tokenId].inventory[len - 1];
}
furballs[tokenId].inventory.pop();
count = stackSize;
} else {
stackSize -= count;
furballs[tokenId].inventory[slot] = uint256(lootId) * 0x100 + stackSize;
}
furballs[tokenId].weight -= count * engine.weightOf(lootId);
emit Inventory(tokenId, lootId, count);
}
/// @notice Internal implementation of adding a single known loot item to a Furball
function _pickup(uint256 tokenId, uint128 lootId) internal {
require(lootId > 0, "LOOT");
uint256 slotNum = _slotNum(tokenId, lootId);
uint8 stackSize = 1;
if (slotNum == 0) {
furballs[tokenId].inventory.push(uint256(lootId) * 0x100 + stackSize);
} else {
stackSize += uint8(furballs[tokenId].inventory[slotNum - 1] % 0x100);
require(stackSize < 0x100, "STACK");
furballs[tokenId].inventory[slotNum - 1] = uint256(lootId) * 0x100 + stackSize;
}
furballs[tokenId].weight += engine.weightOf(lootId);
emit Inventory(tokenId, lootId, 0);
}
/// @notice Calculates full reward modifier stack for a furball in a zone.
function _rewardModifiers(
FurLib.Furball memory fb, uint256 tokenId, address ownerContext, uint256 snackData
) internal view returns(FurLib.RewardModifiers memory reward) {
uint16 energy = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_ENERGY, 2));
uint16 happiness = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_HAPPINESS, 2));
bool context = ownerContext != address(0);
uint32 editionIndex = uint32(tokenId % 0x100);
reward = FurLib.RewardModifiers(
uint16(100 + fb.rarity),
uint16(100 + fb.rarity - (editionIndex < 4 ? (editionIndex * 20) : 80)),
uint16(100),
happiness,
energy,
context ? fb.zone : 0
);
// Engine will consider inventory and team size in zone (17k)
return engine.modifyReward(
fb,
editions[editionIndex].modifyReward(reward, tokenId),
governance.getAccount(ownerContext),
context
);
}
/// @notice Common version of _rewardModifiers which excludes contextual data
function _baseModifiers(uint256 tokenId) internal view returns(FurLib.RewardModifiers memory) {
return _rewardModifiers(furballs[tokenId], tokenId, address(0), 0);
}
/// @notice Ends the current explore/battle and dispenses rewards
/// @param tokenId The furball
function _collect(uint256 tokenId, address sender, uint8 permissions) internal {
FurLib.Furball memory furball = furballs[tokenId];
address owner = ownerOf(tokenId);
// The engine is allowed to force furballs into exploration mode
// This allows it to end a battle early, which will be necessary in PvP
require(owner == sender || permissions >= FurLib.PERMISSION_ADMIN, "OWN");
// Scale duration to the time the edition has been live
if (furball.last == 0) {
uint64 launchedAt = uint64(editions[tokenId % 0x100].liveAt());
require(launchedAt > 0 && launchedAt < uint64(block.timestamp), "PRE");
furball.last = furball.birth > launchedAt ? furball.birth : launchedAt;
}
// Calculate modifiers to be used with this collection
FurLib.RewardModifiers memory mods =
_rewardModifiers(furball, tokenId, owner, fur.cleanSnacks(tokenId));
// Reset the collection for this furball
uint32 duration = uint32(uint64(block.timestamp) - furball.last);
collect[tokenId].fur = 0;
collect[tokenId].experience = 0;
collect[tokenId].levels = 0;
if (mods.zone >= 0x10000) {
// Battle zones earn FUR and assign to the owner
uint32 f = uint32(_calculateReward(duration, FurLib.FUR_PER_INTERVAL, mods.furPercent));
if (f > 0) {
fur.earn(owner, f);
collect[tokenId].fur = f;
}
} else {
// Explore zones earn EXP...
uint32 exp = uint32(_calculateReward(duration, FurLib.EXP_PER_INTERVAL, mods.expPercent));
(uint32 totalExp, uint16 levels) = engine.onExperience(furballs[tokenId], owner, exp);
collect[tokenId].experience = exp;
collect[tokenId].levels = levels;
furballs[tokenId].level += levels;
furballs[tokenId].experience = totalExp;
}
// Generate loot and assign to furball
uint32 interval = uint32(intervalDuration);
uint128 lootId = engine.dropLoot(duration / interval, mods);
collect[tokenId].loot = lootId;
if (lootId > 0) {
_pickup(tokenId, lootId);
}
// Timestamp the last interaction for next cycle.
furballs[tokenId].last = uint64(block.timestamp);
// Emit the reward ID for frontend
uint32 moves = furball.moves + 1;
furballs[tokenId].moves = moves;
emit Collection(tokenId, moves);
}
/// @notice Mints a new furball
/// @dev Recursive function; generates randomization seed for the edition
/// @param to The recipient of the furball
/// @param nonce A recursive counter to prevent infinite loops
function _spawn(address to, uint8 editionIndex, uint8 nonce) internal {
require(nonce < 10, "SUPPLY");
require(editionIndex < editions.length, "ED");
IFurballEdition edition = editions[editionIndex];
// Generate a random furball tokenId; if it fails to be unique, recurse!
(uint256 tokenId, uint16 rarity) = edition.spawn();
tokenId += editionIndex;
if (_exists(tokenId)) return _spawn(to, editionIndex, nonce + 1);
// Ensure that this wallet has not exceeded its per-edition mint-cap
uint32 owned = edition.minted(to);
require(owned < edition.maxMintable(to), "LIMIT");
// Check the current edition's constraints (caller should have checked costs)
uint16 cnt = edition.count();
require(cnt < edition.maxCount(), "MAX");
// Initialize the memory struct that represents the furball
furballs[tokenId].number = uint32(totalSupply() + 1);
furballs[tokenId].count = cnt;
furballs[tokenId].rarity = rarity;
furballs[tokenId].birth = uint64(block.timestamp);
// Finally, mint the token and increment internal counters
_mint(to, tokenId);
edition.addCount(to, 1);
}
/// @notice Happens each time a furball changes wallets
/// @dev Keeps track of the furball timestamp
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
super._beforeTokenTransfer(from, to, tokenId);
// Update internal data states
furballs[tokenId].trade = uint64(block.timestamp);
// Delegate other logic to the engine
engine.onTrade(furballs[tokenId], from, to);
}
// -----------------------------------------------------------------------------------------------
// Game Engine & Moderation
// -----------------------------------------------------------------------------------------------
function stats(uint256 tokenId, bool contextual) public view returns(FurLib.FurballStats memory) {
// Base stats are calculated without team size so this doesn't effect public metadata
FurLib.Furball memory furball = furballs[tokenId];
FurLib.RewardModifiers memory mods =
_rewardModifiers(
furball,
tokenId,
contextual ? ownerOf(tokenId) : address(0),
contextual ? fur.snackEffects(tokenId) : 0
);
return FurLib.FurballStats(
uint16(_calculateReward(intervalDuration, FurLib.EXP_PER_INTERVAL, mods.expPercent)),
uint16(_calculateReward(intervalDuration, FurLib.FUR_PER_INTERVAL, mods.furPercent)),
mods,
furball,
fur.snacks(tokenId)
);
}
/// @notice This utility function is useful because it force-casts arguments to uint256
function _calculateReward(
uint256 duration, uint256 perInterval, uint256 percentBoost
) internal view returns(uint256) {
uint256 interval = intervalDuration;
return (duration * percentBoost * perInterval) / (100 * interval);
}
// -----------------------------------------------------------------------------------------------
// Public Views/Accessors (for outside world)
// -----------------------------------------------------------------------------------------------
/// @notice Provides the OpenSea storefront
/// @dev see https://docs.opensea.io/docs/contract-level-metadata
function contractURI() public view returns (string memory) {
return governance.metaURI();
}
/// @notice Provides the on-chain Furball asset
/// @dev see https://docs.opensea.io/docs/metadata-standards
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId));
return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked(
editions[tokenId % 0x100].tokenMetadata(
engine.attributesMetadata(tokenId),
tokenId,
furballs[tokenId].number
)
))));
}
// -----------------------------------------------------------------------------------------------
// OpenSea Proxy
// -----------------------------------------------------------------------------------------------
/// @notice Whitelisting the proxy registies for secondary market transactions
/// @dev See OpenSea ERC721Tradable
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
return engine.canProxyTrades(owner, operator) || super.isApprovedForAll(owner, operator);
}
/// @notice This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
/// @dev See OpenSea ContentMixin
function _msgSender()
internal
override
view
returns (address sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = msg.sender;
}
return sender;
}
// -----------------------------------------------------------------------------------------------
// Configuration / Admin
// -----------------------------------------------------------------------------------------------
function setFur(address furAddress) external onlyAdmin {
fur = Fur(furAddress);
}
function setFurgreement(address furgAddress) external onlyAdmin {
furgreement = Furgreement(furgAddress);
}
function setGovernance(address addr) public onlyAdmin {
governance = Governance(payable(addr));
}
function setEngine(address addr) public onlyAdmin {
engine = ILootEngine(addr);
}
function addEdition(address addr, uint8 idx) public onlyAdmin {
if (idx >= editions.length) {
editions.push(IFurballEdition(addr));
} else {
editions[idx] = IFurballEdition(addr);
}
}
function _isReady() internal view returns(bool) {
return address(engine) != address(0) && editions.length > 0
&& address(fur) != address(0) && address(governance) != address(0);
}
/// @notice Handles auth of msg.sender against cheating and/or banning.
/// @dev Pass nonzero sender to act as a proxy against the furgreement
function _approvedSender(address sender) internal view returns (address, uint8) {
// No sender (for gameplay) is approved until the necessary parts are online
require(_isReady(), "!RDY");
if (sender != address(0) && sender != msg.sender) {
// Only the furgreement may request a proxied sender.
require(msg.sender == address(furgreement), "PROXY");
} else {
// Zero input triggers sender calculation from msg args
sender = _msgSender();
}
// All senders are validated thru engine logic.
uint8 permissions = uint8(engine.approveSender(sender));
// Zero-permissions indicate unauthorized.
require(permissions > 0, FurLib.bytesHex(abi.encodePacked(sender)));
return (sender, permissions);
}
modifier gameAdmin() {
(address sender, uint8 permissions) = _approvedSender(address(0));
require(permissions >= FurLib.PERMISSION_ADMIN, "GAME");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, 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: UNLICENSED
pragma solidity ^0.8.6;
import "../utils/FurLib.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @title IFurballEdition
/// @author LFG Gaming LLC
/// @notice Interface for a single edition within Furballs
interface IFurballEdition is IERC165 {
function index() external view returns(uint8);
function count() external view returns(uint16);
function maxCount() external view returns (uint16); // total max count in this edition
function addCount(address to, uint16 amount) external returns(bool);
function liveAt() external view returns(uint64);
function minted(address addr) external view returns(uint16);
function maxMintable(address addr) external view returns(uint16);
function maxAdoptable() external view returns (uint16); // how many can be adopted, out of the max?
function purchaseFur() external view returns(uint256); // amount of FUR for buying
function spawn() external returns (uint256, uint16);
/// @notice Calculates the effects of the loot in a Furball's inventory
function modifyReward(
FurLib.RewardModifiers memory modifiers, uint256 tokenId
) external view returns(FurLib.RewardModifiers memory);
/// @notice Renders a JSON object for tokenURI
function tokenMetadata(
bytes memory attributes, uint256 tokenId, uint256 number
) external view returns(bytes memory);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "../editions/IFurballEdition.sol";
import "../utils/FurLib.sol";
import "./Zones.sol";
import "./SnackShop.sol";
/// @title ILootEngine
/// @author LFG Gaming LLC
/// @notice The loot engine is patchable by replacing the Furballs' engine with a new version
interface ILootEngine is IERC165 {
function snacks() external view returns(SnackShop);
function zones() external view returns(Zones);
function l2Proxy() external view returns(address);
/// @notice When a Furball comes back from exploration, potentially give it some loot.
function dropLoot(uint32 intervals, FurLib.RewardModifiers memory mods) external returns(uint128);
/// @notice Players can pay to re-roll their loot drop on a Furball
function upgradeLoot(
FurLib.RewardModifiers memory modifiers,
address owner,
uint128 lootId,
uint8 chances
) external returns(uint128);
/// @notice Some zones may have preconditions
function enterZone(uint256 tokenId, uint32 zone, uint256[] memory team) external returns(uint256);
/// @notice Calculates the effects of the loot in a Furball's inventory
function modifyReward(
FurLib.Furball memory furball,
FurLib.RewardModifiers memory baseModifiers,
FurLib.Account memory account,
bool contextual
) external view returns(FurLib.RewardModifiers memory);
/// @notice Loot can have different weight to help prevent over-powering a furball
function weightOf(uint128 lootId) external pure returns (uint16);
/// @notice JSON object for displaying metadata on OpenSea, etc.
function attributesMetadata(uint256 tokenId) external view returns(bytes memory);
/// @notice Get a potential snack for the furball by its ID
function getSnack(uint32 snack) external view returns(FurLib.Snack memory);
/// @notice Proxy registries are allowed to act as 3rd party trading platforms
function canProxyTrades(address owner, address operator) external view returns(bool);
/// @notice Authorization mechanics are upgradeable to account for security patches
function approveSender(address sender) external view returns(uint);
/// @notice Called when a Furball is traded to update delegate logic
function onTrade(
FurLib.Furball memory furball, address from, address to
) external;
/// @notice Handles experience gain during collection
function onExperience(
FurLib.Furball memory furball, address owner, uint32 experience
) external returns(uint32 totalExp, uint16 level);
/// @notice Gets called at the beginning of token render; could add underlaid artwork
function render(uint256 tokenId) external view returns(string memory);
/// @notice The loot engine can add descriptions to furballs metadata
function furballDescription(uint256 tokenId) external view returns (string memory);
/// @notice Instant snack + move to new zone
function snackAndMove(FurLib.SnackMove[] calldata snackMoves, uint32 zone, address from) external;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./LootEngine.sol";
/// @title EngineA
/// @author LFG Gaming LLC
/// @notice Concrete implementation of LootEngine
contract EngineA is LootEngine {
constructor(address furballs,
address snacksAddr, address zonesAddr,
address tradeProxy, address companyProxy
) LootEngine(furballs, snacksAddr, zonesAddr, tradeProxy, companyProxy) { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "./FurLib.sol";
/// @title FurLib
/// @author LFG Gaming LLC
/// @notice Public utility library around game-specific equations and constants
library FurDefs {
function rarityName(uint8 rarity) internal pure returns(string memory) {
if (rarity == 0) return "Common";
if (rarity == 1) return "Elite";
if (rarity == 2) return "Mythic";
if (rarity == 3) return "Legendary";
return "Ultimate";
}
function raritySuffix(uint8 rarity) internal pure returns(string memory) {
return rarity == 0 ? "" : string(abi.encodePacked(" (", rarityName(rarity), ")"));
}
function renderPoints(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 cnt = uint8(data[ptr]);
ptr++;
bytes memory points = "";
for (uint256 i=0; i<cnt; i++) {
uint16 x = uint8(data[ptr]) * 256 + uint8(data[ptr + 1]);
uint16 y = uint8(data[ptr + 2]) * 256 + uint8(data[ptr + 3]);
points = abi.encodePacked(points, FurLib.uint2str(x), ',', FurLib.uint2str(y), i == (cnt - 1) ? '': ' ');
ptr += 4;
}
return (ptr, abi.encodePacked('points="', points, '" '));
}
function renderTransform(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 len = uint8(data[ptr]);
ptr++;
bytes memory points = "";
for (uint256 i=0; i<len; i++) {
bytes memory point = "";
(ptr, point) = unpackFloat(ptr, data);
points = i == (len - 1) ? abi.encodePacked(points, point) : abi.encodePacked(points, point, ' ');
}
return (ptr, abi.encodePacked('transform="matrix(', points, ')" '));
}
function renderDisplay(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
string[2] memory vals = ['inline', 'none'];
return (ptr + 1, abi.encodePacked('display="', vals[uint8(data[ptr])], '" '));
}
function renderFloat(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 propType = uint8(data[ptr]);
string[2] memory floatMap = ['opacity', 'offset'];
bytes memory floatVal = "";
(ptr, floatVal) = unpackFloat(ptr + 1, data);
return (ptr, abi.encodePacked(floatMap[propType], '="', floatVal,'" '));
}
function unpackFloat(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
uint8 decimals = uint8(data[ptr]);
ptr++;
if (decimals == 0) return (ptr, '0');
uint8 hi = decimals / 16;
uint16 wholeNum = 0;
decimals = decimals % 16;
if (hi >= 10) {
wholeNum = uint16(uint8(data[ptr]) * 256 + uint8(data[ptr + 1]));
ptr += 2;
} else if (hi >= 8) {
wholeNum = uint16(uint8(data[ptr]));
ptr++;
}
if (decimals == 0) return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum)));
bytes memory remainder = new bytes(decimals);
for (uint8 d=0; d<decimals; d+=2) {
remainder[d] = bytes1(48 + uint8(data[ptr] >> 4));
if ((d + 1) < decimals) {
remainder[d+1] = bytes1(48 + uint8(data[ptr] & 0x0f));
}
ptr++;
}
return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum), '.', remainder));
}
function renderInt(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) {
uint8 propType = uint8(data[ptr]);
string[13] memory intMap = ['cx', 'cy', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'r', 'rx', 'ry', 'width', 'height'];
uint16 val = uint16(uint8(data[ptr + 1]) * 256) + uint8(data[ptr + 2]);
if (val >= 0x8000) {
return (ptr + 3, abi.encodePacked(intMap[propType], '="-', FurLib.uint2str(uint32(0x10000 - val)),'" '));
}
return (ptr + 3, abi.encodePacked(intMap[propType], '="', FurLib.uint2str(val),'" '));
}
function renderStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
string[4] memory strMap = ['id', 'enable-background', 'gradientUnits', 'gradientTransform'];
uint8 t = uint8(data[ptr]);
require(t < 4, 'STR');
bytes memory str = "";
(ptr, str) = unpackStr(ptr + 1, data);
return (ptr, abi.encodePacked(strMap[t], '="', str, '" '));
}
function unpackStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) {
uint8 len = uint8(data[ptr]);
bytes memory str = bytes(new string(len));
for (uint8 i=0; i<len; i++) {
str[i] = data[ptr + 1 + i];
}
return (ptr + 1 + len, str);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Moderated
/// @author LFG Gaming LLC
/// @notice Administration & moderation permissions utilities
abstract contract Moderated is Ownable {
mapping (address => bool) public admins;
mapping (address => bool) public moderators;
function setAdmin(address addr, bool set) external onlyOwner {
require(addr != address(0));
admins[addr] = set;
}
/// @notice Moderated ownables may not be renounced (only transferred)
function renounceOwnership() public override onlyOwner {
require(false, 'OWN');
}
function setModerator(address mod, bool set) external onlyAdmin {
require(mod != address(0));
moderators[mod] = set;
}
function isAdmin(address addr) public virtual view returns(bool) {
return owner() == addr || admins[addr];
}
function isModerator(address addr) public virtual view returns(bool) {
return isAdmin(addr) || moderators[addr];
}
modifier onlyModerators() {
require(isModerator(msg.sender), 'MOD');
_;
}
modifier onlyAdmin() {
require(isAdmin(msg.sender), 'ADMIN');
_;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./Stakeholders.sol";
import "./Community.sol";
import "./FurLib.sol";
/// @title Governance
/// @author LFG Gaming LLC
/// @notice Meta-tracker for Furballs; looks at the ecosystem (metadata, wallet counts, etc.)
/// @dev Shares is an ERC20; stakeholders is a payable
contract Governance is Stakeholders {
/// @notice Where transaction fees are deposited
address payable public treasury;
/// @notice How much is the transaction fee, in basis points?
uint16 public transactionFee = 250;
/// @notice Used in contractURI for Furballs itself.
string public metaName = "Furballs.com (Official)";
/// @notice Used in contractURI for Furballs itself.
string public metaDescription =
"Furballs are entirely on-chain, with a full interactive gameplay experience at Furballs.com. "
"There are 88 billion+ possible furball combinations in the first edition, each with their own special abilities"
"... but only thousands minted per edition. Each edition has new artwork, game modes, and surprises.";
// Tracks the MAX which are ever owned by a given address.
mapping(address => FurLib.Account) private _account;
// List of all addresses which have ever owned a furball.
address[] public accounts;
Community public community;
constructor(address furballsAddress) Stakeholders(furballsAddress) {
treasury = payable(this);
}
/// @notice Generic form of contractURI for on-chain packing.
/// @dev Proxied from Furballs, but not called contractURI so as to not imply this ERC20 is tradeable.
function metaURI() public view returns(string memory) {
return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked(
'{"name": "', metaName,'", "description": "', metaDescription,'"',
', "external_link": "https://furballs.com"',
', "image": "https://furballs.com/images/pfp.png"',
', "seller_fee_basis_points": ', FurLib.uint2str(transactionFee),
', "fee_recipient": "0x', FurLib.bytesHex(abi.encodePacked(treasury)), '"}'
))));
}
/// @notice total count of accounts
function numAccounts() external view returns(uint256) {
return accounts.length;
}
/// @notice Update metadata for main contractURI
function setMeta(string memory nameVal, string memory descVal) external gameAdmin {
metaName = nameVal;
metaDescription = descVal;
}
/// @notice The transaction fee can be adjusted
function setTransactionFee(uint16 basisPoints) external gameAdmin {
transactionFee = basisPoints;
}
/// @notice The treasury can be changed in only rare circumstances.
function setTreasury(address treasuryAddress) external onlyOwner {
treasury = payable(treasuryAddress);
}
/// @notice The treasury can be changed in only rare circumstances.
function setCommunity(address communityAddress) external onlyOwner {
community = Community(communityAddress);
}
/// @notice public accessor updates permissions
function getAccount(address addr) external view returns (FurLib.Account memory) {
FurLib.Account memory acc = _account[addr];
acc.permissions = _userPermissions(addr);
return acc;
}
/// @notice Public function allowing manual update of standings
function updateStandings(address[] memory addrs) public {
for (uint32 i=0; i<addrs.length; i++) {
_updateStanding(addrs[i]);
}
}
/// @notice Moderators may assign reputation to accounts
function setReputation(address addr, uint16 rep) external gameModerators {
_account[addr].reputation = rep;
}
/// @notice Tracks the max level an account has *obtained*
function updateMaxLevel(address addr, uint16 level) external gameAdmin {
if (_account[addr].maxLevel >= level) return;
_account[addr].maxLevel = level;
_updateStanding(addr);
}
/// @notice Recompute max stats for the account.
function updateAccount(address addr, uint256 numFurballs) external gameAdmin {
FurLib.Account memory acc = _account[addr];
// Recompute account permissions for internal rewards
uint8 permissions = _userPermissions(addr);
if (permissions != acc.permissions) _account[addr].permissions = permissions;
// New account created?
if (acc.created == 0) _account[addr].created = uint64(block.timestamp);
if (acc.numFurballs != numFurballs) _account[addr].numFurballs = uint32(numFurballs);
// New max furballs?
if (numFurballs > acc.maxFurballs) {
if (acc.maxFurballs == 0) accounts.push(addr);
_account[addr].maxFurballs = uint32(numFurballs);
}
_updateStanding(addr);
}
/// @notice Re-computes the account's standing
function _updateStanding(address addr) internal {
uint256 standing = 0;
FurLib.Account memory acc = _account[addr];
if (address(community) != address(0)) {
// If community is patched in later...
standing = community.update(acc, addr);
} else {
// Default computation of standing
uint32 num = acc.numFurballs;
if (num > 0) {
standing = num * 10 + acc.maxLevel + acc.reputation;
}
}
_account[addr].standing = uint16(standing);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./Furballs.sol";
import "./editions/IFurballEdition.sol";
import "./utils/FurProxy.sol";
/// @title Fur
/// @author LFG Gaming LLC
/// @notice Utility token for in-game rewards in Furballs
contract Fur is ERC20, FurProxy {
// n.b., this contract has some unusual tight-coupling between FUR and Furballs
// Simple reason: this contract had more space, and is the only other allowed to know about ownership
// Thus it serves as a sort of shop meta-store for Furballs
constructor(address furballsAddress) FurProxy(furballsAddress) ERC20("Fur", "FUR") {
}
// -----------------------------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------------------------
/// @notice FUR is a strict counter, with no decimals
function decimals() public view virtual override returns (uint8) {
return 0;
}
/// @notice Returns the snacks currently applied to a Furball
function snacks(uint256 tokenId) external view returns(FurLib.Snack[] memory) {
return furballs.engine().snacks().snacks(tokenId);
}
/// @notice Write-function to cleanup the snacks for a token (remove expired)
/// @dev Since migrating to SnackShop, this function no longer writes; it matches snackEffects
function cleanSnacks(uint256 tokenId) external view returns (uint256) {
return furballs.engine().snacks().snackEffects(tokenId);
}
/// @notice The public accessor calculates the snack boosts
function snackEffects(uint256 tokenId) external view returns(uint256) {
return furballs.engine().snacks().snackEffects(tokenId);
}
// -----------------------------------------------------------------------------------------------
// GameAdmin
// -----------------------------------------------------------------------------------------------
/// @notice FUR can only be minted by furballs doing battle.
function earn(address addr, uint256 amount) external gameModerators {
if (amount == 0) return;
_mint(addr, amount);
}
/// @notice FUR can be spent by Furballs, or by the LootEngine (shopping, in the future)
function spend(address addr, uint256 amount) external gameModerators {
_burn(addr, amount);
}
/// @notice Increases balance in bulk
function gift(address[] calldata tos, uint256[] calldata amounts) external gameModerators {
for (uint i=0; i<tos.length; i++) {
_mint(tos[i], amounts[i]);
}
}
/// @notice Pay any necessary fees to mint a furball
/// @dev Delegated logic from Furballs;
function purchaseMint(
address from, uint8 permissions, address to, IFurballEdition edition
) external gameAdmin returns (bool) {
require(edition.maxMintable(to) > 0, "LIVE");
uint32 cnt = edition.count();
uint32 adoptable = edition.maxAdoptable();
bool requiresPurchase = cnt >= adoptable;
if (requiresPurchase) {
// _gift will throw if cannot gift or cannot afford cost
_gift(from, permissions, to, edition.purchaseFur());
}
return requiresPurchase;
}
/// @notice Attempts to purchase an upgrade for a loot item
/// @dev Delegated logic from Furballs
function purchaseUpgrade(
FurLib.RewardModifiers memory modifiers,
address from, uint8 permissions, uint256 tokenId, uint128 lootId, uint8 chances
) external gameAdmin returns(uint128) {
address owner = furballs.ownerOf(tokenId);
// _gift will throw if cannot gift or cannot afford cost
_gift(from, permissions, owner, 500 * uint256(chances));
return furballs.engine().upgradeLoot(modifiers, owner, lootId, chances);
}
/// @notice Attempts to purchase a snack using templates found in the engine
/// @dev Delegated logic from Furballs
function purchaseSnack(
address from, uint8 permissions, uint256 tokenId, uint32 snackId, uint16 count
) external gameAdmin {
FurLib.Snack memory snack = furballs.engine().getSnack(snackId);
require(snack.count > 0, "COUNT");
require(snack.fed == 0, "FED");
// _gift will throw if cannot gift or cannot afford costQ
_gift(from, permissions, furballs.ownerOf(tokenId), snack.furCost * count);
furballs.engine().snacks().giveSnack(tokenId, snackId, count);
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
/// @notice Enforces (requires) only admins/game may give gifts
/// @param to Whom is this being sent to?
/// @return If this is a gift or not.
function _gift(address from, uint8 permissions, address to, uint256 furCost) internal returns(bool) {
bool isGift = to != from;
// Only admins or game engine can send gifts (to != self), which are always free.
require(!isGift || permissions >= FurLib.PERMISSION_ADMIN, "GIFT");
if (!isGift && furCost > 0) {
_burn(from, furCost);
}
return isGift;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./Furballs.sol";
import "./Fur.sol";
import "./utils/FurProxy.sol";
import "./engines/Zones.sol";
import "./engines/SnackShop.sol";
import "./utils/MetaData.sol";
import "./l2/L2Lib.sol";
import "./l2/Fuel.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
// import "hardhat/console.sol";
/// @title Furgreement
/// @author LFG Gaming LLC
/// @notice L2 proxy authority; has permissions to write to main contract(s)
contract Furgreement is EIP712, FurProxy {
// Tracker of wallet balances
Fuel public fuel;
// Simple, fast check for a single allowed proxy...
address private _job;
constructor(
address furballsAddress, address fuelAddress
) EIP712("Furgreement", "1") FurProxy(furballsAddress) {
fuel = Fuel(fuelAddress);
_job = msg.sender;
}
/// @notice Player signs an EIP-712 authorizing the ticket (fuel) usage
/// @dev furballMoves defines desinations (zone-moves) for playMany
function runTimekeeper(
uint64[] calldata furballMoves,
L2Lib.TimekeeperRequest[] calldata tkRequests,
bytes[] calldata signatures
) external allowedProxy {
// While TK runs, numMovedFurballs are collected to move zones at the end
uint8 numZones = uint8(furballMoves.length);
uint256[][] memory tokenIds = new uint256[][](numZones);
uint32[] memory zoneNums = new uint32[](numZones);
uint32[] memory zoneCounts = new uint32[](numZones);
for (uint i=0; i<numZones; i++) {
tokenIds[i] = new uint256[](furballMoves[i] & 0xFF);
zoneNums[i] = uint32(furballMoves[i] >> 8);
zoneCounts[i] = 0;
}
// Validate & run TK on each request
for (uint i=0; i<tkRequests.length; i++) {
L2Lib.TimekeeperRequest memory tkRequest = tkRequests[i];
uint errorCode = _runTimekeeper(tkRequest, signatures[i]);
require(errorCode == 0, errorCode == 0 ? "" : string(abi.encodePacked(
FurLib.bytesHex(abi.encode(tkRequest.sender)),
":",
FurLib.uint2str(errorCode)
)));
// Each "round" in the request represents a Furball
for (uint i=0; i<tkRequest.rounds.length; i++) {
_resolveRound(tkRequest.rounds[i], tkRequest.sender);
uint zi = tkRequest.rounds[i].zoneListNum;
if (numZones == 0 || zi == 0) continue;
zi = zi - 1;
uint zc = zoneCounts[zi];
tokenIds[zi][zc] = tkRequest.rounds[i].tokenId;
zoneCounts[zi] = uint32(zc + 1);
}
}
// Finally, move furballs.
for (uint i=0; i<numZones; i++) {
uint32 zoneNum = zoneNums[i];
if (zoneNum == 0 || zoneNum == 0x10000) {
furballs.playMany(tokenIds[i], zoneNum, address(this));
} else {
furballs.engine().zones().overrideZone(tokenIds[i], zoneNum);
}
}
}
/// @notice Public validation function can check that the signature was valid ahead of time
function validateTimekeeper(
L2Lib.TimekeeperRequest memory tkRequest,
bytes memory signature
) public view returns (uint) {
return _validateTimekeeper(tkRequest, signature);
}
/// @notice Single Timekeeper run for one player; validates EIP-712 request
function _runTimekeeper(
L2Lib.TimekeeperRequest memory tkRequest,
bytes memory signature
) internal returns (uint) {
// Check the EIP-712 signature.
uint errorCode = _validateTimekeeper(tkRequest, signature);
if (errorCode != 0) return errorCode;
// Burn tickets, etc.
if (tkRequest.tickets > 0) fuel.burn(tkRequest.sender, tkRequest.tickets);
// Earn FUR (must be at least the amount approved by player)
require(tkRequest.furReal >= tkRequest.furGained, "FUR");
if (tkRequest.furReal > 0) {
furballs.fur().earn(tkRequest.sender, tkRequest.furReal);
}
// Spend FUR (everything approved by player)
if (tkRequest.furSpent > 0) {
// Spend the FUR required for these actions
furballs.fur().spend(tkRequest.sender, tkRequest.furSpent);
}
// Mint new furballs from an edition
if (tkRequest.mintCount > 0) {
// Edition is one-indexed, to allow for null
address[] memory to = new address[](tkRequest.mintCount);
for (uint i=0; i<tkRequest.mintCount; i++) {
to[i] = tkRequest.sender;
}
// "Gift" the mint (FUR purchase should have been done above)
furballs.mint(to, tkRequest.mintEdition, address(this));
}
return 0; // no error
}
/// @notice Validate a timekeeper request
function _validateTimekeeper(
L2Lib.TimekeeperRequest memory tkRequest,
bytes memory signature
) internal view returns (uint) {
bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
keccak256("TimekeeperRequest(address sender,uint32 fuel,uint32 fur_gained,uint32 fur_spent,uint8 mint_edition,uint8 mint_count,uint64 deadline)"),
tkRequest.sender,
tkRequest.tickets,
tkRequest.furGained,
tkRequest.furSpent,
tkRequest.mintEdition,
tkRequest.mintCount,
tkRequest.deadline
)));
address signer = ECDSA.recover(digest, signature);
if (signer != tkRequest.sender) return 1;
if (signer == address(0)) return 2;
if (tkRequest.deadline != 0 && block.timestamp >= tkRequest.deadline) return 3;
return 0;
}
/// @notice Give rewards/outcomes directly
function _resolveRound(L2Lib.RoundResolution memory round, address sender) internal {
if (round.expGained > 0) {
// EXP gain (in explore mode)
furballs.engine().zones().addExp(round.tokenId, round.expGained);
}
if (round.items.length != 0) {
// First item is an optional drop
if (round.items[0] != 0)
furballs.drop(round.tokenId, round.items[0], 1);
// Other items are pickups
for (uint j=1; j<round.items.length; j++) {
furballs.pickup(round.tokenId, round.items[j]);
}
}
// Directly assign snacks...
if (round.snackStacks.length > 0) {
furballs.engine().snacks().giveSnacks(round.tokenId, round.snackStacks);
}
}
/// @notice Proxy can be set to an arbitrary address to represent the allowed offline job
function setJobAddress(address addr) external gameAdmin {
_job = addr;
}
/// @notice Simple proxy allowed check
modifier allowedProxy() {
require(msg.sender == _job || furballs.isAdmin(msg.sender), "FPRXY");
_;
}
}
// 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;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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: UNLICENSED
pragma solidity ^0.8.6;
import "../utils/FurLib.sol";
import "../utils/FurProxy.sol";
// import "hardhat/console.sol";
/// @title SnackShop
/// @author LFG Gaming LLC
/// @notice Simple data-storage for snacks
contract SnackShop is FurProxy {
// snackId to "definition" of the snack
mapping(uint32 => FurLib.Snack) private snack;
// List of actual snack IDs
uint32[] private snackIds;
// tokenId => snackId => (snackId) + (stackSize)
mapping(uint256 => mapping(uint32 => uint96)) private snackStates;
// Internal cache for speed.
uint256 private _intervalDuration;
constructor(address furballsAddress) FurProxy(furballsAddress) {
_intervalDuration = furballs.intervalDuration();
_defineSnack(0x100, 24 , 250, 15, 0);
_defineSnack(0x200, 24 * 3, 750, 20, 0);
_defineSnack(0x300, 24 * 7, 1500, 25, 0);
}
// -----------------------------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------------------------
/// @notice Returns the snacks currently applied to a Furball
function snacks(uint256 tokenId) external view returns(FurLib.Snack[] memory) {
// First, count how many active snacks there are...
uint snackCount = 0;
for (uint i=0; i<snackIds.length; i++) {
uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]);
if (remaining != 0) {
snackCount++;
}
}
// Next, build the return array...
FurLib.Snack[] memory ret = new FurLib.Snack[](snackCount);
if (snackCount == 0) return ret;
uint snackIdx = 0;
for (uint i=0; i<snackIds.length; i++) {
uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]);
if (remaining != 0) {
uint96 snackState = snackStates[tokenId][snackIds[i]];
ret[snackIdx] = snack[snackIds[i]];
ret[snackIdx].fed = uint64(snackState >> 16);
ret[snackIdx].count = uint16(snackState);
snackIdx++;
}
}
return ret;
}
/// @notice The public accessor calculates the snack boosts
function snackEffects(uint256 tokenId) external view returns(uint256) {
uint hap = 0;
uint en = 0;
for (uint i=0; i<snackIds.length; i++) {
uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]);
if (remaining != 0) {
hap += snack[snackIds[i]].happiness;
en += snack[snackIds[i]].energy;
}
}
return (hap << 16) + (en);
}
/// @notice Public accessor for enumeration
function getSnackIds() external view returns(uint32[] memory) {
return snackIds;
}
/// @notice Load a snack by ID
function getSnack(uint32 snackId) external view returns(FurLib.Snack memory) {
return snack[snackId];
}
// -----------------------------------------------------------------------------------------------
// GameAdmin
// -----------------------------------------------------------------------------------------------
/// @notice Allows admins to configure the snack store.
function setSnack(
uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en
) external gameAdmin {
_defineSnack(snackId, duration, furCost, hap, en);
}
/// @notice Shortcut for admins/timekeeper
function giveSnack(
uint256 tokenId, uint32 snackId, uint16 count
) external gameAdmin {
_assignSnack(tokenId, snackId, count);
}
/// @notice Shortcut for admins/timekeeper
function giveSnacks(
uint256 tokenId, uint64[] calldata snackStacks
) external gameAdmin {
for (uint i=0; i<snackStacks.length; i++) {
_assignSnack(tokenId, uint32(snackStacks[i] >> 16), uint16(snackStacks[i]));
}
}
/// @notice Shortcut for admins/timekeeper
function giveManySnacks(
uint256[] calldata tokenIds, uint64[] calldata snackStacks
) external gameAdmin {
for (uint i=0; i<snackStacks.length; i++) {
_assignSnack(tokenIds[i], uint32(snackStacks[i] >> 16), uint16(snackStacks[i]));
}
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
/// @notice Update the snackStates
function _assignSnack(uint256 tokenId, uint32 snackId, uint16 count) internal {
uint timeRemaining = _snackTimeRemaning(tokenId, snackId);
if (timeRemaining == 0) {
snackStates[tokenId][snackId] = uint96((block.timestamp << 16) + count);
} else {
snackStates[tokenId][snackId] = snackStates[tokenId][snackId] + count;
}
}
/// @notice Both removes inactive _snacks from a token and searches for a specific snack Id index
/// @dev Both at once saves some size & ensures that the _snacks are frequently cleaned.
/// @return The index+1 of the existing snack
// function _cleanSnack(uint256 tokenId, uint32 snackId) internal returns(uint256) {
// uint32 ret = 0;
// uint16 hap = 0;
// uint16 en = 0;
// for (uint32 i=1; i<=_snacks[tokenId].length && i <= FurLib.Max32; i++) {
// FurLib.Snack memory snack = _snacks[tokenId][i-1];
// // Has the snack transitioned from active to inactive?
// if (_snackTimeRemaning(snack) == 0) {
// if (_snacks[tokenId].length > 1) {
// _snacks[tokenId][i-1] = _snacks[tokenId][_snacks[tokenId].length - 1];
// }
// _snacks[tokenId].pop();
// i--; // Repeat this idx
// continue;
// }
// hap += snack.happiness;
// en += snack.energy;
// if (snackId != 0 && snack.snackId == snackId) {
// ret = i;
// }
// }
// return (ret << 32) + (hap << 16) + (en);
// }
/// @notice Check if the snack is active; returns 0 if inactive, otherwise the duration
function _snackTimeRemaning(uint256 tokenId, uint32 snackId) internal view returns(uint256) {
uint96 snackState = snackStates[tokenId][snackId];
uint64 fed = uint64(snackState >> 16);
if (fed == 0) return 0;
uint16 count = uint16(snackState);
uint32 duration = snack[snackId].duration;
uint256 expiresAt = uint256(fed + (count * duration * _intervalDuration));
return expiresAt <= block.timestamp ? 0 : (expiresAt - block.timestamp);
}
/// @notice Store a new snack definition
function _defineSnack(
uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en
) internal {
if (snack[snackId].snackId != snackId) {
snackIds.push(snackId);
}
snack[snackId].snackId = snackId;
snack[snackId].duration = duration;
snack[snackId].furCost = furCost;
snack[snackId].happiness = hap;
snack[snackId].energy = en;
snack[snackId].count = 1;
snack[snackId].fed = 0;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./ILootEngine.sol";
import "./SnackShop.sol";
import "../editions/IFurballEdition.sol";
import "../Furballs.sol";
import "../utils/FurLib.sol";
import "../utils/FurProxy.sol";
import "../utils/ProxyRegistry.sol";
import "../utils/Dice.sol";
import "../utils/Governance.sol";
import "../utils/MetaData.sol";
import "./Zones.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
// import "hardhat/console.sol";
/// @title LootEngine
/// @author LFG Gaming LLC
/// @notice Base implementation of the loot engine
abstract contract LootEngine is ERC165, ILootEngine, Dice, FurProxy {
ProxyRegistry private _proxies;
// An address which may act on behalf of the owner (company)
address override public l2Proxy;
// Zone control contract
Zones override public zones;
// Simple storage of snack definitions
SnackShop override public snacks;
uint32 constant maxExperience = 2010000;
constructor(
address furballsAddress,
address snacksAddr, address zonesAddr,
address tradeProxy, address companyProxyAddr
) FurProxy(furballsAddress) {
_proxies = ProxyRegistry(tradeProxy);
l2Proxy = companyProxyAddr;
snacks = SnackShop(snacksAddr);
zones = Zones(zonesAddr);
}
// -----------------------------------------------------------------------------------------------
// Display
// -----------------------------------------------------------------------------------------------
/// @notice Gets called for Metadata
function furballDescription(uint256 tokenId) external virtual override view returns (string memory) {
return string(abi.encodePacked(
'", "external_url": "https://', _getSubdomain(),
'furballs.com/fb/', FurLib.bytesHex(abi.encode(tokenId)),
'", "animation_url": "https://', _getSubdomain(),
'furballs.com/e/', FurLib.bytesHex(abi.encode(tokenId))
));
}
/// @notice Gets called at the beginning of token render; zones are able to render BKs
function render(uint256 tokenId) external virtual override view returns(string memory) {
return zones.render(tokenId);
}
// -----------------------------------------------------------------------------------------------
// Proxy
// -----------------------------------------------------------------------------------------------
/// @notice An instant snack + move function, called from Zones
function snackAndMove(
FurLib.SnackMove[] calldata snackMoves, uint32 zone, address from
) external override gameJob {
uint256[] memory tokenIds = new uint256[](snackMoves.length);
for (uint i=0; i<snackMoves.length; i++) {
tokenIds[i] = snackMoves[i].tokenId;
for (uint j=0; j<snackMoves[i].snackIds.length; j++) {
furballs.fur().purchaseSnack(
from, FurLib.PERMISSION_USER, tokenIds[i], snackMoves[i].snackIds[j], 1);
}
}
furballs.playMany(tokenIds, zone, from);
}
/// @notice Graceful way for the job to end TK, also burning tickets
function endTimekeeper(
address sender, uint32 fuelCost,
uint256[] calldata tokenIds, uint64[] calldata lastTimestamps, uint8[] calldata modes
) external gameJob {
furballs.furgreement().fuel().burn(sender, fuelCost);
zones.timestampModes(tokenIds, lastTimestamps, modes);
}
// -----------------------------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------------------------
/// @notice Loot can have different weight to help prevent over-powering a furball
/// @dev Each point of weight can be offset by a point of energy; the result reduces luck
function weightOf(uint128 lootId) external virtual override pure returns (uint16) {
return 2;
}
/// @notice Checking the zone may use _require to detect preconditions.
function enterZone(
uint256 tokenId, uint32 zone, uint256[] memory team
) external virtual override returns(uint256) {
zones.enterZone(tokenId, zone);
return zone;
}
/// @notice Proxy logic is presently delegated to OpenSea-like contract
function canProxyTrades(
address owner, address operator
) external virtual override view returns(bool) {
if (address(_proxies) == address(0)) return false;
return address(_proxies.proxies(owner)) == operator;
}
/// @notice Allow a player to play? Throws on error if not.
/// @dev This is core gameplay security logic
function approveSender(address sender) external virtual override view returns(uint) {
if (sender == address(0)) return 0;
if (sender == l2Proxy) return FurLib.PERMISSION_OWNER;
if (sender == address(furballs.furgreement())) return FurLib.PERMISSION_CONTRACT;
return _permissions(sender);
}
/// @notice Attempt to upgrade a given piece of loot (item ID)
function upgradeLoot(
FurLib.RewardModifiers memory modifiers,
address owner,
uint128 lootId,
uint8 chances
) external virtual override returns(uint128) {
// upgradeLoot will never receive luckPercent==0 because its stats are noncontextual
(uint8 rarity, uint8 stat) = _itemRarityStat(lootId);
require(rarity > 0 && rarity < 3, "RARITY");
uint32 chance = (rarity == 1 ? 75 : 25) * uint32(chances) + uint32(modifiers.luckPercent * 10);
// Remove the 100% from loot, with 5% minimum chance
chance = chance > 1050 ? (chance - 1000) : 50;
// Even with many chances, odds are capped:
if (chance > 750) chance = 750;
uint32 threshold = (FurLib.Max32 / 1000) * (1000 - chance);
uint256 rolled = (uint256(roll(modifiers.expPercent)));
return rolled < threshold ? 0 : _packLoot(rarity + 1, stat);
}
/// @notice Main loot-drop functionm
function dropLoot(
uint32 intervals,
FurLib.RewardModifiers memory modifiers
) external virtual override returns(uint128) {
if (modifiers.luckPercent == 0) return 0;
(uint8 rarity, uint8 stat) = _rollRarityStat(
uint32((intervals * uint256(modifiers.luckPercent)) /100), 0);
return _packLoot(rarity, stat);
}
/// @notice The snack shop has IDs for each snack definition
function getSnack(uint32 snackId) external view virtual override returns(FurLib.Snack memory) {
return snacks.getSnack(snackId);
}
/// @notice Layers on LootEngine modifiers to rewards
function modifyReward(
FurLib.Furball memory furball,
FurLib.RewardModifiers memory modifiers,
FurLib.Account memory account,
bool contextual
) external virtual override view returns(FurLib.RewardModifiers memory) {
// Use temporary variables is more gas-efficient than accessing them off the struct
FurLib.ZoneReward memory zr = zones.getFurballZoneReward(furball.number);
if (contextual && zr.mode != 1) {
modifiers.luckPercent = 0;
modifiers.expPercent = 0;
modifiers.furPercent = 0;
return modifiers;
}
uint16 expPercent = modifiers.expPercent + modifiers.happinessPoints + zr.rarity;
uint16 furPercent = modifiers.furPercent + _furBoost(furball.level) + zr.rarity;
// First add in the inventory
for (uint256 i=0; i<furball.inventory.length; i++) {
uint128 lootId = uint128(furball.inventory[i] >> 8);
(uint8 rarity, uint8 stat) = _itemRarityStat(lootId);
uint32 stackSize = uint32(furball.inventory[i] & 0xFF);
uint16 boost = uint16(_lootRarityBoost(rarity) * stackSize);
if (stat == 0) {
expPercent += boost;
} else {
furPercent += boost;
}
}
// Team size boosts!
if (account.numFurballs > 1) {
uint16 amt = uint16(2 * (account.numFurballs <= 10 ? (account.numFurballs - 1) : 10));
expPercent += amt;
furPercent += amt;
}
modifiers.luckPercent = _luckBoosts(
modifiers.luckPercent + modifiers.happinessPoints, furball.weight, modifiers.energyPoints);
if (contextual)
modifiers.luckPercent = _timeScalePercent(modifiers.luckPercent, furball.last, zr.timestamp);
modifiers.furPercent =
(contextual ? _timeScalePercent(furPercent, furball.last, zr.timestamp) : furPercent);
modifiers.expPercent =
(contextual ? _timeScalePercent(expPercent, furball.last, zr.timestamp) : expPercent);
return modifiers;
}
/// @notice OpenSea metadata
function attributesMetadata(
uint256 tokenId
) external virtual override view returns(bytes memory) {
FurLib.FurballStats memory stats = furballs.stats(tokenId, false);
return abi.encodePacked(
zones.attributesMetadata(stats, tokenId, maxExperience),
MetaData.traitValue("Rare Genes Boost", stats.definition.rarity),
MetaData.traitNumber("Edition", (tokenId & 0xFF) + 1),
MetaData.traitNumber("Unique Loot Collected", stats.definition.inventory.length),
MetaData.traitBoost("EXP Boost", stats.modifiers.expPercent),
MetaData.traitBoost("FUR Boost", stats.modifiers.furPercent),
MetaData.traitDate("Acquired", stats.definition.trade),
MetaData.traitDate("Birthday", stats.definition.birth)
);
}
// -----------------------------------------------------------------------------------------------
// GameAdmin
// -----------------------------------------------------------------------------------------------
/// @notice The trade hook can update balances or assign rewards
function onTrade(
FurLib.Furball memory furball, address from, address to
) external virtual override gameAdmin {
// Do the first computation of the Furball's boosts
if (from == address(0)) zones.computeStats(furball.number, 0);
Governance gov = furballs.governance();
if (from != address(0)) gov.updateAccount(from, furballs.balanceOf(from) - 1);
if (to != address(0)) gov.updateAccount(to, furballs.balanceOf(to) + 1);
}
/// @notice Calculates new level for experience
function onExperience(
FurLib.Furball memory furball, address owner, uint32 experience
) external virtual override gameAdmin returns(uint32 totalExp, uint16 levels) {
// Zones keep track of the "additional" EXP, accrued via TK (it will get zeroed on zone change)
FurLib.ZoneReward memory zr = zones.getFurballZoneReward(furball.number);
uint32 has = furball.experience + zr.experience;
totalExp = (experience < maxExperience && has < (maxExperience - experience)) ?
(has + experience) : maxExperience;
// Calculate new level & check for level-up
uint16 oldLevel = furball.level;
uint16 level = uint16(FurLib.expToLevel(totalExp, maxExperience));
levels = level > oldLevel ? (level - oldLevel) : 0;
if (levels > 0) {
// Update community standing
furballs.governance().updateMaxLevel(owner, level);
}
return (totalExp, levels);
}
// -----------------------------------------------------------------------------------------------
// Internal
// -----------------------------------------------------------------------------------------------
/// @notice After Timekeeper, rewards need to be scaled by the remaining time
function _timeScalePercent(
uint16 percent, uint64 furballLast, uint64 zoneLast
) internal view returns(uint16) {
if (furballLast >= zoneLast) return percent; // TK was not more recent
return uint16((uint64(percent) * (uint64(block.timestamp) - zoneLast)) / (uint64(block.timestamp) - furballLast));
}
function _luckBoosts(uint16 luckPercent, uint16 weight, uint16 energy) internal pure returns(uint16) {
// Calculate weight & reduce luck
if (weight > 0) {
if (energy > 0) {
weight = (energy >= weight) ? 0 : (weight - energy);
}
if (weight > 0) {
luckPercent = weight >= luckPercent ? 0 : (luckPercent - weight);
}
}
return luckPercent;
}
/// @notice Core loot drop rarity randomization
/// @dev exposes an interface helpful for the unit tests, but is not otherwise called publicly
function _rollRarityStat(uint32 chance, uint32 seed) internal returns(uint8, uint8) {
if (chance == 0) return (0, 0);
uint32 threshold = 4320;
uint32 rolled = roll(seed) % threshold;
uint8 stat = uint8(rolled % 2);
if (chance > threshold || rolled >= (threshold - chance)) return (3, stat);
threshold -= chance;
if (chance * 3 > threshold || rolled >= (threshold - chance * 3)) return (2, stat);
threshold -= chance * 3;
if (chance * 6 > threshold || rolled >= (threshold - chance * 6)) return (1, stat);
return (0, stat);
}
function _packLoot(uint16 rarity, uint16 stat) internal pure returns(uint128) {
return rarity == 0 ? 0 : (uint16(rarity) << 16) + (stat << 8);
}
function _lootRarityBoost(uint16 rarity) internal pure returns (uint16) {
if (rarity == 1) return 5;
else if (rarity == 2) return 15;
else if (rarity == 3) return 30;
return 0;
}
/// @notice Gets the FUR boost for a given level
function _furBoost(uint16 level) internal pure returns (uint16) {
if (level >= 200) return 581;
if (level < 25) return (2 * level);
if (level < 50) return (5000 + (level - 25) * 225) / 100;
if (level < 75) return (10625 + (level - 50) * 250) / 100;
if (level < 100) return (16875 + (level - 75) * 275) / 100;
if (level < 125) return (23750 + (level - 100) * 300) / 100;
if (level < 150) return (31250 + (level - 125) * 325) / 100;
if (level < 175) return (39375 + (level - 150) * 350) / 100;
return (48125 + (level - 175) * 375) / 100;
}
/// @notice Unpacks an item, giving its rarity + stat
function _itemRarityStat(uint128 lootId) internal pure returns (uint8, uint8) {
return (
uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_RARITY, 1)),
uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_STAT, 1)));
}
function _getSubdomain() internal view returns (string memory) {
uint chainId = _getChainId();
if (chainId == 3) return "ropsten.";
if (chainId == 4) return "rinkeby.";
if (chainId == 31337) return "localhost.";
return "";
}
function _getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
/// @notice Permission job proxy
modifier gameJob() {
require(msg.sender == l2Proxy || _permissionCheck(msg.sender) >= FurLib.PERMISSION_ADMIN, "JOB");
_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(ILootEngine).interfaceId ||
super.supportsInterface(interfaceId);
}
// function _inventoryBoosts(
// uint256[] memory inventory, bool contextual
// ) internal view returns(uint16 expPercent, uint16 furPercent) {
// for (uint256 i=0; i<inventory.length; i++) {
// uint128 lootId = uint128(inventory[i] / 0x100);
// (uint8 rarity, uint8 stat) = _itemRarityStat(lootId);
// if (stat == 1 && contextual) continue;
// uint32 stackSize = uint32(inventory[i] & 0xFF);
// uint16 boost = uint16(_lootRarityBoost(rarity) * stackSize);
// if (stat == 0) {
// expPercent += boost;
// } else {
// furPercent += boost;
// }
// }
// }
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
// Contract doesn't really provide anything...
contract OwnableDelegateProxy {}
// Required format for OpenSea of proxy delegate store
// https://github.com/ProjectOpenSea/opensea-creatures/blob/f7257a043e82fae8251eec2bdde37a44fee474c4/contracts/ERC721Tradable.sol
// https://etherscan.io/address/0xa5409ec958c83c3f309868babaca7c86dcb077c1#code
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.6;
import "./FurLib.sol";
/// @title Dice
/// @author LFG Gaming LLC
/// @notice Math utility functions that leverage storage and thus cannot be pure
abstract contract Dice {
uint32 private LAST = 0; // Re-seed for PRNG
/// @notice A PRNG which re-seeds itself with block information & another PRNG
/// @dev This is unit-tested with monobit (frequency) and longestRunOfOnes
function roll(uint32 seed) internal returns (uint32) {
LAST = uint32(uint256(keccak256(
abi.encodePacked(block.timestamp, block.basefee, _prng(LAST == 0 ? seed : LAST)))
));
return LAST;
}
/// @notice A PRNG based upon a Lehmer (Park-Miller) method
/// @dev https://en.wikipedia.org/wiki/Lehmer_random_number_generator
function _prng(uint32 seed) internal view returns (uint256) {
unchecked {
uint256 nonce = seed == 0 ? uint32(block.timestamp) : seed;
return (nonce * 48271) % 0x7fffffff;
}
}
}
// 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: UNLICENSED
pragma solidity ^0.8.6;
import "./FurProxy.sol";
import "./FurLib.sol";
import "../Furballs.sol";
/// @title Stakeholders
/// @author LFG Gaming LLC
/// @notice Tracks "percent ownership" of a smart contract, paying out according to schedule
/// @dev Acts as a treasury, receiving ETH funds and distributing them to stakeholders
abstract contract Stakeholders is FurProxy {
// stakeholder values, in 1/1000th of a percent (received during withdrawls)
mapping(address => uint64) public stakes;
// List of stakeholders.
address[] public stakeholders;
// Where any remaining funds should be deposited. Defaults to contract creator.
address payable public poolAddress;
constructor(address furballsAddress) FurProxy(furballsAddress) {
poolAddress = payable(msg.sender);
}
/// @notice Overflow pool of funds. Contains remaining funds from withdrawl.
function setPool(address addr) public onlyOwner {
poolAddress = payable(addr);
}
/// @notice Changes payout percentages.
function setStakeholder(address addr, uint64 stake) public onlyOwner {
if (!_hasStakeholder(addr)) {
stakeholders.push(addr);
}
uint64 percent = stake;
for (uint256 i=0; i<stakeholders.length; i++) {
if (stakeholders[i] != addr) {
percent += stakes[stakeholders[i]];
}
}
require(percent <= FurLib.OneHundredPercent, "Invalid stake (exceeds 100%)");
stakes[addr] = stake;
}
/// @notice Empties this contract's balance, paying out to stakeholders.
function withdraw() external gameAdmin {
uint256 balance = address(this).balance;
require(balance >= FurLib.OneHundredPercent, "Insufficient balance");
for (uint256 i=0; i<stakeholders.length; i++) {
address addr = stakeholders[i];
uint256 payout = balance * uint256(stakes[addr]) / FurLib.OneHundredPercent;
if (payout > 0) {
payable(addr).transfer(payout);
}
}
uint256 remaining = address(this).balance;
poolAddress.transfer(remaining);
}
/// @notice Check
function _hasStakeholder(address addr) internal view returns(bool) {
for (uint256 i=0; i<stakeholders.length; i++) {
if (stakeholders[i] == addr) {
return true;
}
}
return false;
}
// -----------------------------------------------------------------------------------------------
// Payable
// -----------------------------------------------------------------------------------------------
/// @notice This contract can be paid transaction fees, e.g., from OpenSea
/// @dev The contractURI specifies itself as the recipient of transaction fees
receive() external payable { }
}
// SPDX-License-Identifier: BSD-3-Clause
/// @title Vote checkpointing for an ERC-721 token
/// @dev This ERC20 has been adopted from
/// https://github.com/nounsDAO/nouns-monorepo/blob/master/packages/nouns-contracts/contracts/base/ERC721Checkpointable.sol
/*********************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░██░░░████░░██░░░████░░░ *
* ░░██████░░░████████░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*********************************/
// LICENSE
// Community.sol uses and modifies part of Compound Lab's Comp.sol:
// https://github.com/compound-finance/compound-protocol/blob/ae4388e780a8d596d97619d9704a931a2752c2bc/contracts/Governance/Comp.sol
//
// Comp.sol source code Copyright 2020 Compound Labs, Inc. licensed under the BSD-3-Clause license.
// With modifications by Nounders DAO.
//
// Additional conditions of BSD-3-Clause can be found here: https://opensource.org/licenses/BSD-3-Clause
//
// MODIFICATIONS
// Checkpointing logic from Comp.sol has been used with the following modifications:
// - `delegates` is renamed to `_delegates` and is set to private
// - `delegates` is a public function that uses the `_delegates` mapping look-up, but unlike
// Comp.sol, returns the delegator's own address if there is no delegate.
// This avoids the delegator needing to "delegate to self" with an additional transaction
// - `_transferTokens()` is renamed `_beforeTokenTransfer()` and adapted to hook into OpenZeppelin's ERC721 hooks.
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./FurLib.sol";
/// @title Community
/// @author LFG Gaming LLC
/// @notice This is a derived token; it represents a weighted balance of the ERC721 token (Furballs).
/// @dev There is no fiscal interest in Community. This is simply a measured value of community voice.
contract Community is ERC20 {
/// @notice A record of each accounts delegate
mapping(address => address) private _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
constructor() ERC20("FurballsCommunity", "FBLS") { }
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)');
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH =
keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)');
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) 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, uint256 previousBalance, uint256 newBalance);
/**
* @notice The votes a delegator can delegate, which is the current balance of the delegator.
* @dev Used when calling `_delegate()`
*/
function votesToDelegate(address delegator) public view returns (uint96) {
return safe96(balanceOf(delegator), 'Community::votesToDelegate: amount exceeds 96 bits');
}
/**
* @notice Overrides the standard `Comp.sol` delegates mapping to return
* the delegator's own address if they haven't delegated.
* This avoids having to delegate to oneself.
*/
function delegates(address delegator) public view returns (address) {
address current = _delegates[delegator];
return current == address(0) ? delegator : current;
}
/// @notice Sets the addresses' standing directly
function update(FurLib.Account memory account, address addr) external returns (uint256) {
require(false, 'NEED SECURITY');
// uint256 balance = balanceOf(addr);
// if (standing > balance) {
// _mint(addr, standing - balance);
// } else if (standing < balance) {
// _burn(addr, balance - standing);
// }
}
/**
* @notice Adapted from `_transferTokens()` in `Comp.sol` to update delegate votes.
* @dev hooks into OpenZeppelin's `ERC721._transfer`
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override {
super._beforeTokenTransfer(from, to, amount);
require(from == address(0), "Votes may not be traded.");
/// @notice Differs from `_transferTokens()` to use `delegates` override method to simulate auto-delegation
_moveDelegates(delegates(from), delegates(to), uint96(amount));
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
if (delegatee == address(0)) delegatee = msg.sender;
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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))
);
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), 'Community::delegateBySig: invalid signature');
require(nonce == nonces[signatory]++, 'Community::delegateBySig: invalid nonce');
require(block.timestamp <= expiry, 'Community::delegateBySig: signature expired');
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) {
require(blockNumber < block.number, 'Community::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 {
/// @notice differs from `_delegate()` in `Comp.sol` to use `delegates` override method to simulate auto-delegation
address currentDelegate = delegates(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
uint96 amount = votesToDelegate(delegator);
_moveDelegates(currentDelegate, delegatee, 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, 'Community::_moveDelegates: 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, 'Community::_moveDelegates: amount overflows');
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(
block.number,
'Community::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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.6;
import "../utils/FurProxy.sol";
/// @title Fuel
/// @author LFG Gaming LLC
/// @notice Simple tracker for how much ETH a user has deposited into Furballs' pools, etc.
contract Fuel is FurProxy {
mapping(address => uint256) public tank;
uint256 public conversionRate = 100000000000;
constructor(address furballsAddress) FurProxy(furballsAddress) { }
/// @notice Change ETH/Fuel ratio
function setConversion(uint256 rate) external gameModerators {
conversionRate = rate;
}
/// @notice Direct deposit function
/// @dev Pass zero address to apply to self
function deposit(address to) external payable {
require(msg.value > 0, "VALUE");
if (to == address(0)) to = msg.sender;
tank[to] += msg.value / conversionRate;
}
/// @notice Sends payout to the treasury
function settle(uint256 amount) external gameModerators {
if (amount == 0) amount = address(this).balance;
furballs.governance().treasury().transfer(amount);
}
/// @notice Increases balance
function gift(address[] calldata tos, uint256[] calldata amounts) external gameModerators {
for (uint i=0; i<tos.length; i++) {
tank[tos[i]] += amounts[i];
}
}
/// @notice Decreases balance. Returns the amount withdrawn, where zero indicates failure.
/// @dev Does not require/throw, but empties the balance when it exceeds the requested amount.
function burn(address from, uint256 amount) external gameModerators returns(uint) {
return _burn(from, amount);
}
/// @notice Burn lots of fuel from different players
function burnAll(
address[] calldata wallets, uint256[] calldata requestedFuels
) external gameModerators {
for (uint i=0; i<wallets.length; i++) {
_burn(wallets[i], requestedFuels[i]);
}
}
/// @notice Internal burn
function _burn(address from, uint256 amount) internal returns(uint) {
uint256 bal = tank[from];
if (bal == 0) {
return 0;
} else if (bal > amount) {
tank[from] = bal - amount;
} else {
amount = bal;
tank[from] = 0;
}
return amount;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
|
* @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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))
);
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), 'Community::delegateBySig: invalid signature');
require(nonce == nonces[signatory]++, 'Community::delegateBySig: invalid nonce');
require(block.timestamp <= expiry, 'Community::delegateBySig: signature expired');
return _delegate(signatory, delegatee);
}
| 1,278,203 |
[
1,
15608,
815,
19588,
628,
1573,
8452,
358,
1375,
22216,
73,
68,
225,
7152,
73,
1021,
1758,
358,
7152,
19588,
358,
225,
7448,
1021,
6835,
919,
1931,
358,
845,
326,
3372,
225,
10839,
1021,
813,
622,
1492,
358,
6930,
326,
3372,
225,
331,
1021,
11044,
1160,
434,
326,
3372,
225,
436,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
225,
272,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
7152,
858,
8267,
12,
203,
3639,
1758,
7152,
73,
16,
203,
3639,
2254,
5034,
7448,
16,
203,
3639,
2254,
5034,
10839,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
203,
565,
262,
1071,
288,
203,
3639,
1731,
1578,
2461,
6581,
273,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
18192,
67,
2399,
15920,
16,
417,
24410,
581,
5034,
12,
3890,
12,
529,
10756,
3631,
30170,
548,
9334,
1758,
12,
2211,
3719,
203,
3639,
11272,
203,
3639,
1731,
1578,
1958,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
1639,
19384,
2689,
67,
2399,
15920,
16,
7152,
73,
16,
7448,
16,
10839,
10019,
203,
3639,
1731,
1578,
5403,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
2668,
64,
92,
3657,
64,
92,
1611,
2187,
2461,
6581,
16,
1958,
2310,
10019,
203,
3639,
1758,
1573,
8452,
273,
425,
1793,
3165,
12,
10171,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
2583,
12,
2977,
8452,
480,
1758,
12,
20,
3631,
296,
12136,
13352,
2866,
22216,
858,
8267,
30,
2057,
3372,
8284,
203,
3639,
2583,
12,
12824,
422,
1661,
764,
63,
2977,
8452,
3737,
15,
16,
296,
12136,
13352,
2866,
22216,
858,
8267,
30,
2057,
7448,
8284,
203,
3639,
2583,
12,
2629,
18,
5508,
1648,
10839,
16,
296,
12136,
13352,
2866,
22216,
858,
8267,
30,
3372,
7708,
8284,
203,
3639,
327,
389,
22216,
12,
2977,
8452,
16,
7152,
73,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100
] |
//Address: 0x6863be0e7cf7ce860a574760e9020d519a8bdc47
//Contract name: OnLiveToken
//Balance: 0 Ether
//Verification Date: 1/18/2018
//Transacion Count: 412
// CODE STARTS HERE
/* solhint-disable no-simple-event-func-name */
pragma solidity 0.4.18;
/*
* https://github.com/OpenZeppelin/zeppelin-solidity
*
* The MIT License (MIT)
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/*
* https://github.com/OpenZeppelin/zeppelin-solidity
*
* The MIT License (MIT)
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*/
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;
}
}
/*
* https://github.com/OpenZeppelin/zeppelin-solidity
*
* The MIT License (MIT)
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/*
* https://github.com/OpenZeppelin/zeppelin-solidity
*
* The MIT License (MIT)
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping (address => uint256) internal balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title A token that can decrease its supply
* @author Jakub Stefanski (https://github.com/jstefanski)
*
* https://github.com/OnLivePlatform/onlive-contracts
*
* The BSD 3-Clause Clear License
* Copyright (c) 2018 OnLive LTD
*/
contract BurnableToken is BasicToken {
using SafeMath for uint256;
/**
* @dev Address where burned tokens are Transferred.
* @dev This is useful for blockchain explorers operating on Transfer event.
*/
address public constant BURN_ADDRESS = address(0x0);
/**
* @dev Tokens destroyed from specified address
* @param from address The burner
* @param amount uint256 The amount of destroyed tokens
*/
event Burned(address indexed from, uint256 amount);
modifier onlyHolder(uint256 amount) {
require(balances[msg.sender] >= amount);
_;
}
/**
* @dev Destroy tokens (reduce total supply)
* @param amount uint256 The amount of tokens to be burned
*/
function burn(uint256 amount)
public
onlyHolder(amount)
{
balances[msg.sender] = balances[msg.sender].sub(amount);
totalSupply = totalSupply.sub(amount);
Burned(msg.sender, amount);
Transfer(msg.sender, BURN_ADDRESS, amount);
}
}
/**
* @title A token with modifiable name and symbol
* @author Jakub Stefanski (https://github.com/jstefanski)
*
* https://github.com/OnLivePlatform/onlive-contracts
*
* The BSD 3-Clause Clear License
* Copyright (c) 2018 OnLive LTD
*/
contract DescriptiveToken is BasicToken, Ownable {
string public name;
string public symbol;
bool public isDescriptionFinalized;
uint256 public decimals = 18;
function DescriptiveToken(
string _name,
string _symbol
)
public
onlyNotEmpty(_name)
onlyNotEmpty(_symbol)
{
name = _name;
symbol = _symbol;
}
/**
* @dev Logs change of token name and symbol
* @param name string The new token name
* @param symbol string The new token symbol
*/
event DescriptionChanged(string name, string symbol);
/**
* @dev Further changes to name and symbol are forbidden
*/
event DescriptionFinalized();
modifier onlyNotEmpty(string str) {
require(bytes(str).length > 0);
_;
}
modifier onlyDescriptionNotFinalized() {
require(!isDescriptionFinalized);
_;
}
/**
* @dev Change name and symbol of tokens
* @dev May be used in case of symbol collisions in exchanges.
* @param _name string A new token name
* @param _symbol string A new token symbol
*/
function changeDescription(string _name, string _symbol)
public
onlyOwner
onlyDescriptionNotFinalized
onlyNotEmpty(_name)
onlyNotEmpty(_symbol)
{
name = _name;
symbol = _symbol;
DescriptionChanged(name, symbol);
}
/**
* @dev Prevents further changes to name and symbol
*/
function finalizeDescription()
public
onlyOwner
onlyDescriptionNotFinalized
{
isDescriptionFinalized = true;
DescriptionFinalized();
}
}
/**
* @title A token that can increase its supply in initial period
* @author Jakub Stefanski (https://github.com/jstefanski)
*
* https://github.com/OnLivePlatform/onlive-contracts
*
* The BSD 3-Clause Clear License
* Copyright (c) 2018 OnLive LTD
*/
contract MintableToken is BasicToken, Ownable {
using SafeMath for uint256;
/**
* @dev Address from which minted tokens are Transferred.
* @dev This is useful for blockchain explorers operating on Transfer event.
*/
address public constant MINT_ADDRESS = address(0x0);
/**
* @dev Indicates whether creating tokens has finished
*/
bool public mintingFinished;
/**
* @dev Addresses allowed to create tokens
*/
mapping (address => bool) public isMintingManager;
/**
* @dev Tokens minted to specified address
* @param to address The receiver of the tokens
* @param amount uint256 The amount of tokens
*/
event Minted(address indexed to, uint256 amount);
/**
* @dev Approves specified address as a Minting Manager
* @param addr address The approved address
*/
event MintingManagerApproved(address addr);
/**
* @dev Revokes specified address as a Minting Manager
* @param addr address The revoked address
*/
event MintingManagerRevoked(address addr);
/**
* @dev Creation of tokens finished
*/
event MintingFinished();
modifier onlyMintingManager(address addr) {
require(isMintingManager[addr]);
_;
}
modifier onlyMintingNotFinished {
require(!mintingFinished);
_;
}
/**
* @dev Approve specified address to mint tokens
* @param addr address The approved Minting Manager address
*/
function approveMintingManager(address addr)
public
onlyOwner
onlyMintingNotFinished
{
isMintingManager[addr] = true;
MintingManagerApproved(addr);
}
/**
* @dev Forbid specified address to mint tokens
* @param addr address The denied Minting Manager address
*/
function revokeMintingManager(address addr)
public
onlyOwner
onlyMintingManager(addr)
onlyMintingNotFinished
{
delete isMintingManager[addr];
MintingManagerRevoked(addr);
}
/**
* @dev Create new tokens and transfer them to specified address
* @param to address The address to transfer to
* @param amount uint256 The amount to be minted
*/
function mint(address to, uint256 amount)
public
onlyMintingManager(msg.sender)
onlyMintingNotFinished
{
totalSupply = totalSupply.add(amount);
balances[to] = balances[to].add(amount);
Minted(to, amount);
Transfer(MINT_ADDRESS, to, amount);
}
/**
* @dev Prevent further creation of tokens
*/
function finishMinting()
public
onlyOwner
onlyMintingNotFinished
{
mintingFinished = true;
MintingFinished();
}
}
/**
* @title A token that can increase its supply to the specified limit
* @author Jakub Stefanski (https://github.com/jstefanski)
*
* https://github.com/OnLivePlatform/onlive-contracts
*
* The BSD 3-Clause Clear License
* Copyright (c) 2018 OnLive LTD
*/
contract CappedMintableToken is MintableToken {
/**
* @dev Maximum supply that can be minted
*/
uint256 public maxSupply;
function CappedMintableToken(uint256 _maxSupply)
public
onlyNotZero(_maxSupply)
{
maxSupply = _maxSupply;
}
modifier onlyNotZero(uint256 value) {
require(value != 0);
_;
}
modifier onlyNotExceedingMaxSupply(uint256 supply) {
require(supply <= maxSupply);
_;
}
/**
* @dev Create new tokens and transfer them to specified address
* @dev Checks against capped max supply of token.
* @param to address The address to transfer to
* @param amount uint256 The amount to be minted
*/
function mint(address to, uint256 amount)
public
onlyNotExceedingMaxSupply(totalSupply.add(amount))
{
return MintableToken.mint(to, amount);
}
}
/*
* https://github.com/OpenZeppelin/zeppelin-solidity
*
* The MIT License (MIT)
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*
* https://github.com/OnLivePlatform/onlive-contracts
*
* The BSD 3-Clause Clear License
* Copyright (c) 2018 OnLive LTD
*/
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);
}
/*
* https://github.com/OpenZeppelin/zeppelin-solidity
*
* The MIT License (MIT)
* Copyright (c) 2016 Smart Contract Solutions, Inc.
*
* https://github.com/OnLivePlatform/onlive-contracts
*
* The BSD 3-Clause Clear License
* Copyright (c) 2018 OnLive LTD
*/
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 ERC20 token with manual initial lock up period
* @author Jakub Stefanski (https://github.com/jstefanski)
*
* https://github.com/OnLivePlatform/onlive-contracts
*
* The BSD 3-Clause Clear License
* Copyright (c) 2018 OnLive LTD
*/
contract ReleasableToken is StandardToken, Ownable {
/**
* @dev Controls whether token transfers are enabled
* @dev If false, token is in transfer lock up period.
*/
bool public released;
/**
* @dev Contract or EOA that can enable token transfers
*/
address public releaseManager;
/**
* @dev Map of addresses allowed to transfer tokens despite the lock up period
*/
mapping (address => bool) public isTransferManager;
/**
* @dev Specified address set as a Release Manager
* @param addr address The approved address
*/
event ReleaseManagerSet(address addr);
/**
* @dev Approves specified address as Transfer Manager
* @param addr address The approved address
*/
event TransferManagerApproved(address addr);
/**
* @dev Revokes specified address as Transfer Manager
* @param addr address The denied address
*/
event TransferManagerRevoked(address addr);
/**
* @dev Marks token as released (transferable)
*/
event Released();
/**
* @dev Token is released or specified address is transfer manager
*/
modifier onlyTransferableFrom(address from) {
if (!released) {
require(isTransferManager[from]);
}
_;
}
/**
* @dev Specified address is transfer manager
*/
modifier onlyTransferManager(address addr) {
require(isTransferManager[addr]);
_;
}
/**
* @dev Sender is release manager
*/
modifier onlyReleaseManager() {
require(msg.sender == releaseManager);
_;
}
/**
* @dev Token is released (transferable)
*/
modifier onlyReleased() {
require(released);
_;
}
/**
* @dev Token is in lock up period
*/
modifier onlyNotReleased() {
require(!released);
_;
}
/**
* @dev Set release manager if token not released yet
* @param addr address The new Release Manager address
*/
function setReleaseManager(address addr)
public
onlyOwner
onlyNotReleased
{
releaseManager = addr;
ReleaseManagerSet(addr);
}
/**
* @dev Approve specified address to make transfers in lock up period
* @param addr address The approved Transfer Manager address
*/
function approveTransferManager(address addr)
public
onlyOwner
onlyNotReleased
{
isTransferManager[addr] = true;
TransferManagerApproved(addr);
}
/**
* @dev Forbid specified address to make transfers in lock up period
* @param addr address The denied Transfer Manager address
*/
function revokeTransferManager(address addr)
public
onlyOwner
onlyTransferManager(addr)
onlyNotReleased
{
delete isTransferManager[addr];
TransferManagerRevoked(addr);
}
/**
* @dev Release token and makes it transferable
*/
function release()
public
onlyReleaseManager
onlyNotReleased
{
released = true;
Released();
}
/**
* @dev Transfer token to a specified address
* @dev Available only after token release
* @param to address The address to transfer to
* @param amount uint256 The amount to be transferred
*/
function transfer(
address to,
uint256 amount
)
public
onlyTransferableFrom(msg.sender)
returns (bool)
{
return super.transfer(to, amount);
}
/**
* @dev Transfer tokens from one address to another
* @dev Available only after token release
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param amount uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 amount
)
public
onlyTransferableFrom(from)
returns (bool)
{
return super.transferFrom(from, to, amount);
}
}
/**
* @title OnLive Token
* @author Jakub Stefanski (https://github.com/jstefanski)
* @dev Implements ERC20 interface
* @dev Mintable by selected addresses until sale finishes
* @dev A cap on total supply of tokens
* @dev Burnable by anyone
* @dev Manual lock-up period (non-transferable) with a non-reversible release by the selected address
* @dev Modifiable symbol and name in case of collision
*
* https://github.com/OnLivePlatform/onlive-contracts
*
* The BSD 3-Clause Clear License
* Copyright (c) 2018 OnLive LTD
*/
contract OnLiveToken is DescriptiveToken, ReleasableToken, CappedMintableToken, BurnableToken {
function OnLiveToken(
string _name,
string _symbol,
uint256 _maxSupply
)
public
DescriptiveToken(_name, _symbol)
CappedMintableToken(_maxSupply)
{
owner = msg.sender;
}
}
|
* @dev Set release manager if token not released yet @param addr address The new Release Manager address/
|
function setReleaseManager(address addr)
public
onlyOwner
onlyNotReleased
{
releaseManager = addr;
ReleaseManagerSet(addr);
}
| 6,483,951 |
[
1,
694,
3992,
3301,
309,
1147,
486,
15976,
4671,
225,
3091,
1758,
1021,
394,
10819,
8558,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
444,
7391,
1318,
12,
2867,
3091,
13,
203,
3639,
1071,
203,
3639,
1338,
5541,
203,
3639,
1338,
1248,
26363,
203,
565,
288,
203,
3639,
3992,
1318,
273,
3091,
31,
203,
203,
3639,
10819,
1318,
694,
12,
4793,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256;
FlightSuretyData data;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
mapping(address => uint) private votesForAirline;
address private contractOwner;
uint public AIRLINE_REGISTRATION_FEE = 10 ether;
uint8 private nonce = 0;
uint256 public constant REGISTRATION_FEE = 1 ether;
uint256 private constant MIN_RESPONSES = 3;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
event AirlineRegistered(string id, string name, address airlineAddress, bool open);
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(data.isOperational(), "Contract is currently not operational");
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier to check if the timestamp is valid. Not very secure because miners can change the time of blockchain
*/
modifier requireValidTimestamp(uint _timestamp) {
require(_timestamp >= now,"Not valid timestamp");
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor(address dataContractAddress) public {
contractOwner = msg.sender;
data = FlightSuretyData(dataContractAddress);
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational() public view returns (bool){
return data.isOperational();
}
function setOperatingStatus(bool mode) public requireContractOwner {
return data.setOperatingStatus(mode);
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline(string _id, string _name, address _airlineAddress) public requireIsOperational returns (bool success, uint256 votes){
require(_airlineAddress != address(0), "'airline' must be a valid address.");
uint airlinesRegistered = data.fetchRegisteredAirlines();
if (airlinesRegistered < 4) {
data.registerAirline(msg.sender, _id, _name, _airlineAddress, true, false);
emit AirlineRegistered(_id, _name, _airlineAddress, false);
return (true, 0);
} else {
if (votesForAirline[_airlineAddress] < airlinesRegistered.div(2)) {
votesForAirline[_airlineAddress].add(1);
emit AirlineRegistered(_id, _name, _airlineAddress, true);
return (false, votesForAirline[_airlineAddress]);
} else {
data.registerAirline(msg.sender, _id, _name, _airlineAddress, true, false);
votesForAirline[_airlineAddress].add(1);
emit AirlineRegistered(_id, _name, _airlineAddress, false);
return (true, votesForAirline[_airlineAddress]);
}
}
}
function fetchRegisteredAirlines() requireIsOperational external view returns (address[]){
return data.fetchAllAirlines();
}
function payRegistrationFee(address airline) requireIsOperational public payable returns (bool success) {
require(msg.value >= AIRLINE_REGISTRATION_FEE, "Minimum fee to activate airline is not payed");
require(airline == msg.sender, "airline have to be the same with sender");
data.fund.value(msg.value)();
return data.updateAirlineFeePayed(airline, true);
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight(address _airline, string _flight, uint _timestamp) external requireIsOperational requireValidTimestamp(_timestamp) {
(string memory _id, string memory _name, bool _isRegistered, bool _registrationFeePayed) = data.fetchAirline(_airline);
require(_registrationFeePayed);
bytes32 _key = getFlightKey(_airline, _flight, _timestamp);
require(!flights[_key].isRegistered);
flights[_key] = Flight({
isRegistered : true,
statusCode : STATUS_CODE_UNKNOWN,
updatedTimestamp : _timestamp,
airline : _airline });
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus(address _airline, string memory _flight, uint256 _timestamp, uint8 _statusCode)
internal requireIsOperational requireValidTimestamp(_timestamp) {
require(_statusCode == STATUS_CODE_LATE_AIRLINE);
data.creditInsurees(getFlightKey(_airline, _flight, _timestamp));
}
/**
* @dev fetch data for a airline
*/
function fetchAirline(address _airline) external requireIsOperational view returns( string id, string name,
bool isRegistered, bool registrationFeePayed) {
return data.fetchAirline(_airline);
}
/**
* @dev Generate a request for oracles to fetch flight information
*/
function fetchFlightStatus(address airline, string flight, uint256 timestamp) external requireIsOperational {
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester : msg.sender,
isOpen : true
});
emit OracleRequest(index, airline, flight, timestamp);
}
function buy(address _passengerAddress, address airline, string flight, uint256 timestamp, uint _insuranceAmount) requireIsOperational external payable{
require(_insuranceAmount == msg.value,"not same money was sent");
bytes32 key = getFlightKey(airline, flight,timestamp);
data.buy.value(msg.value)(_passengerAddress,key,_insuranceAmount);
}
function pay(address _passengerAddress, uint _amount) external payable requireIsOperational {
data.pay(_passengerAddress, _amount);
}
// region ORACLE MANAGEMENT
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
// Register an oracle with the contract
function registerOracle() external payable {
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered : true,
indexes : indexes
});
}
function getMyIndexes() view external returns (uint8[3]){
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse(uint8 index, address airline, string flight, uint256 timestamp, uint8 statusCode) external {
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
function getFlightKey(address airline, string flight, uint256 timestamp) pure internal returns (bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes(address account) internal returns (uint8[3]) {
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while (indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex(address account) internal returns (uint8) {
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
nonce = 0;
// Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
}
contract FlightSuretyData {
// functions util
function isOperational() public view returns (bool);
function setOperatingStatus(bool mode) external;
function authorizeCaller(address contractAddress) external;
function deauthorizeCaller(address contractAddress) external;
//main functions
function updateAirlineFeePayed(address _airlineAddress, bool payed) external returns (bool);
function registerAirline(address _existingAirline, string _id, string _name, address _airlineAddress, bool isRegistered, bool registrationFeePayed) external;
function fetchAirline(address airlineAddress) external view returns (string id, string name, bool isRegistered, bool registrationFeePayed);
function fetchRegisteredAirlines() external view returns (uint numOfAirlines);
function fetchAllAirlines() external view returns (address[]);
function pay(address _passengerAddress, uint _amount) external payable;
function creditInsurees(bytes32 _flightKey) external;
function buy(address _passengerAddress, bytes32 _flightKey, uint _insuranceAmount) external payable;
function fetchPassengerBalance(address _passengerAddress) external returns (uint balance);
function fund() external payable;
}
|
functions utilmain functions
|
contract FlightSuretyData {
function isOperational() public view returns (bool);
function setOperatingStatus(bool mode) external;
function authorizeCaller(address contractAddress) external;
function deauthorizeCaller(address contractAddress) external;
function updateAirlineFeePayed(address _airlineAddress, bool payed) external returns (bool);
function registerAirline(address _existingAirline, string _id, string _name, address _airlineAddress, bool isRegistered, bool registrationFeePayed) external;
function fetchAirline(address airlineAddress) external view returns (string id, string name, bool isRegistered, bool registrationFeePayed);
function fetchRegisteredAirlines() external view returns (uint numOfAirlines);
function fetchAllAirlines() external view returns (address[]);
function pay(address _passengerAddress, uint _amount) external payable;
function creditInsurees(bytes32 _flightKey) external;
function buy(address _passengerAddress, bytes32 _flightKey, uint _insuranceAmount) external payable;
function fetchPassengerBalance(address _passengerAddress) external returns (uint balance);
function fund() external payable;
}
}
| 937,682 |
[
1,
10722,
1709,
5254,
4186,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
16351,
3857,
750,
55,
594,
4098,
751,
288,
203,
565,
445,
353,
2988,
287,
1435,
1071,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
444,
3542,
1776,
1482,
12,
6430,
1965,
13,
3903,
31,
203,
203,
565,
445,
12229,
11095,
12,
2867,
6835,
1887,
13,
3903,
31,
203,
203,
565,
445,
443,
22488,
11095,
12,
2867,
6835,
1887,
13,
3903,
31,
203,
203,
565,
445,
1089,
29752,
1369,
14667,
9148,
329,
12,
2867,
389,
1826,
1369,
1887,
16,
1426,
8843,
329,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
1744,
29752,
1369,
12,
2867,
389,
11711,
29752,
1369,
16,
533,
389,
350,
16,
533,
389,
529,
16,
1758,
389,
1826,
1369,
1887,
16,
1426,
353,
10868,
16,
1426,
7914,
14667,
9148,
329,
13,
3903,
31,
203,
203,
565,
445,
2158,
29752,
1369,
12,
2867,
23350,
1369,
1887,
13,
3903,
1476,
1135,
261,
1080,
612,
16,
533,
508,
16,
1426,
353,
10868,
16,
1426,
7914,
14667,
9148,
329,
1769,
203,
203,
565,
445,
2158,
10868,
29752,
3548,
1435,
3903,
1476,
1135,
261,
11890,
23153,
29752,
3548,
1769,
203,
203,
565,
445,
12817,
29752,
3548,
1435,
3903,
1476,
1135,
261,
2867,
8526,
1769,
203,
203,
565,
445,
8843,
12,
2867,
389,
5466,
14348,
1887,
16,
2254,
389,
8949,
13,
3903,
8843,
429,
31,
203,
203,
565,
445,
12896,
382,
2055,
281,
12,
3890,
1578,
389,
19131,
653,
13,
3903,
31,
203,
203,
565,
445,
30143,
12,
2867,
389,
5466,
14348,
1887,
16,
1731,
1578,
389,
19131,
653,
16,
2254,
389,
2679,
295,
1359,
2
] |
./partial_match/11297108109/0x4C1f6fCBd233241bF2f4D02811E3bF8429BC27B8/sources/project_/contracts/ERC20MinterBurnerPauser.sol
|
* @dev Creates a new token for `to`. Its token ID will be automatically assigned (and available on the emitted {Transfer} event), and the token URI autogenerated based on the base URI passed at construction. See {ERC20-_mint}. Requirements: - the caller must have the `MINTER_ROLE`./
|
function mint(address to, uint256 amount) public {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20MinterBurnerPauser: must have minter role to mint");
_mint(to, amount);
}
| 16,952,332 |
[
1,
2729,
279,
394,
1147,
364,
1375,
869,
8338,
29517,
1147,
1599,
903,
506,
6635,
6958,
261,
464,
2319,
603,
326,
17826,
288,
5912,
97,
871,
3631,
471,
326,
1147,
3699,
7840,
2511,
603,
326,
1026,
3699,
2275,
622,
16171,
18,
2164,
288,
654,
39,
3462,
17,
67,
81,
474,
5496,
29076,
30,
300,
326,
4894,
1297,
1240,
326,
1375,
6236,
2560,
67,
16256,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
312,
474,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
1071,
288,
203,
3639,
2583,
12,
5332,
2996,
12,
6236,
2560,
67,
16256,
16,
389,
3576,
12021,
1435,
3631,
315,
654,
39,
3462,
49,
2761,
38,
321,
264,
16507,
1355,
30,
1297,
1240,
1131,
387,
2478,
358,
312,
474,
8863,
203,
203,
3639,
389,
81,
474,
12,
869,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//"SPDX-License-Identifier: UNLICENSED"
/**
*Submitted for verification at Etherscan.io on 2021-03-01
*/
//"SPDX-License-Identifier: UNLICENSED"
pragma solidity ^0.6.6;
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;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface UniswapV2Router{
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 removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
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;
}
contract Owned {
//address of contract owner
address public owner;
//event for transfer of ownership
event OwnershipTransferred(address indexed _from, address indexed _to);
/**
* @dev Initializes the contract setting the _owner as the initial owner.
*/
constructor(address _owner) public {
owner = _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner {
require(msg.sender == owner, 'only owner allowed');
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`_newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address _newOwner) external onlyOwner {
owner = _newOwner;
emit OwnershipTransferred(owner, _newOwner);
}
}
interface Multiplier {
function updateLockupPeriod(address _user, uint _lockup) external returns(bool);
function getMultiplierCeiling() external pure returns (uint);
function balance(address user) external view returns (uint);
function approvedContract(address _user) external view returns(address);
function lockupPeriod(address user) external view returns (uint);
}
/*
* @dev PoolStakes contract for locking up liquidity to earn bonus rewards.
*/
contract PoolStake is Owned {
//instantiate SafeMath library
using SafeMath for uint;
IERC20 internal weth; //represents weth.
IERC20 internal token; //represents the project's token which should have a weth pair on uniswap
IERC20 internal lpToken; //lpToken for liquidity provisioning
address internal uToken; //utility token
address internal wallet; //company wallet
uint internal scalar = 10**36; //unit for scaling
uint internal cap; //ETH limit that can be provided
Multiplier internal multiplier; //Interface of Multiplier contract
UniswapV2Router internal uniswapRouter; //Interface of Uniswap V2 router
IUniswapV2Factory internal iUniswapV2Factory; //Interface of uniswap V2 factory
//user struct
struct User {
uint start; //starting period
uint release; //release period
uint tokenBonus; //user token bonus
uint wethBonus; //user weth bonus
uint tokenWithdrawn; //amount of token bonus withdrawn
uint wethWithdrawn; //amount of weth bonus withdrawn
uint liquidity; //user liquidity gotten from uniswap
bool migrated; //if migrated to uniswap V3
}
//address to User mapping
mapping(address => User) internal _users;
uint32 internal constant _012_HOURS_IN_SECONDS = 43200;
//term periods
uint32 internal period1;
uint32 internal period2;
uint32 internal period3;
uint32 internal period4;
//return percentages for ETH and token 1000 = 1%
uint internal period1RPWeth;
uint internal period2RPWeth;
uint internal period3RPWeth;
uint internal period4RPWeth;
uint internal period1RPToken;
uint internal period2RPToken;
uint internal period3RPToken;
uint internal period4RPToken;
//available bonuses rto be claimed
uint internal _pendingBonusesWeth;
uint internal _pendingBonusesToken;
//migration contract for Uniswap V3
address public migrationContract;
//events
event BonusAdded(address indexed sender, uint ethAmount, uint tokenAmount);
event BonusRemoved(address indexed sender, uint amount);
event CapUpdated(address indexed sender, uint amount);
event LPWithdrawn(address indexed sender, uint amount);
event LiquidityAdded(address indexed sender, uint liquidity, uint amountETH, uint amountToken);
event LiquidityWithdrawn(address indexed sender, uint liquidity, uint amountETH, uint amountToken);
event UserTokenBonusWithdrawn(address indexed sender, uint amount, uint fee);
event UserETHBonusWithdrawn(address indexed sender, uint amount, uint fee);
event VersionMigrated(address indexed sender, uint256 time, address to);
event LiquidityMigrated(address indexed sender, uint amount, address to);
/*
* @dev initiates a new PoolStake.
* ------------------------------------------------------
* @param _token --> token offered for staking liquidity.
* @param _Owner --> address for the initial contract owner.
*/
constructor(address _token, address _Owner) public Owned(_Owner) {
require(_token != address(0), "can not deploy a zero address");
token = IERC20(_token);
weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
iUniswapV2Factory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
address _lpToken = iUniswapV2Factory.getPair(address(token), address(weth));
require(_lpToken != address(0), "Pair must first be created on uniswap");
lpToken = IERC20(_lpToken);
uToken = 0x9Ed8e7C9604790F7Ec589F99b94361d8AAB64E5E;
wallet = 0xa7A4d919202DFA2f4E44FFAc422d21095bF9770a;
multiplier = Multiplier(0xbc962d7be33d8AfB4a547936D8CE6b9a1034E9EE);
uniswapRouter = UniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
}
/*
* @dev change the return percentage for locking up liquidity for ETH and Token (only Owner).
* ------------------------------------------------------------------------------------
* @param _period1RPETH - _period4RPToken --> the new return percentages.
* ----------------------------------------------
* returns whether successfully changed or not.
*/
function changeReturnPercentages(
uint _period1RPETH, uint _period2RPETH, uint _period3RPETH, uint _period4RPETH,
uint _period1RPToken, uint _period2RPToken, uint _period3RPToken, uint _period4RPToken
) external onlyOwner returns(bool) {
period1RPWeth = _period1RPETH;
period2RPWeth = _period2RPETH;
period3RPWeth = _period3RPETH;
period4RPWeth = _period4RPETH;
period1RPToken = _period1RPToken;
period2RPToken = _period2RPToken;
period3RPToken = _period3RPToken;
period4RPToken = _period4RPToken;
return true;
}
/*
* @dev change the lockup periods (only Owner).
* ------------------------------------------------------------------------------------
* @param _firstTerm - _fourthTerm --> the new term periods.
* ----------------------------------------------
* returns whether successfully changed or not.
*/
function changeTermPeriods(
uint32 _firstTerm, uint32 _secondTerm,
uint32 _thirdTerm, uint32 _fourthTerm
) external onlyOwner returns(bool) {
period1 = _firstTerm;
period2 = _secondTerm;
period3 = _thirdTerm;
period4 = _fourthTerm;
return true;
}
/*
* @dev change the maximum ETH that a user can enter with (only Owner).
* ------------------------------------------------------------------------------------
* @param _cap --> the new cap value.
* ----------------------------------------------
* returns whether successfully changed or not.
*/
function changeCap(uint _cap) external onlyOwner returns(bool) {
cap = _cap;
emit CapUpdated(msg.sender, _cap);
return true;
}
/*
* @dev makes migration possible for uniswap V3 (only Owner).
* ----------------------------------------------------------
* @param _unistakeMigrationContract --> the migration contract address.
* -------------------------------------------------------------------------
* returns whether successfully migrated or not.
*/
function allowMigration(address _unistakeMigrationContract) external onlyOwner returns (bool) {
require(_unistakeMigrationContract != address(0x0), "cannot migrate to a null address");
migrationContract = _unistakeMigrationContract;
emit VersionMigrated(msg.sender, now, migrationContract);
return true;
}
/*
* @dev initiates migration for a user (only when migration is allowed).
* -------------------------------------------------------------------
* @param _unistakeMigrationContract --> the migration contract address.
* -------------------------------------------------------------------------
* returns whether successfully migrated or not.
*/
function startMigration(address _unistakeMigrationContract) external returns (bool) {
require(_unistakeMigrationContract != address(0x0), "cannot migrate to a null address");
require(migrationContract == _unistakeMigrationContract, "must confirm endpoint");
require(!getUserMigration(msg.sender), "must not be migrated already");
_users[msg.sender].migrated = true;
uint256 liquidity = _users[msg.sender].liquidity;
lpToken.transfer(migrationContract, liquidity);
emit LiquidityMigrated(msg.sender, liquidity, migrationContract);
return true;
}
/*
* @dev add more staking bonuses to the pool.
* ----------------------------------------
* @param --> input value along with call to add ETH
* @param _tokenAmount --> the amount of token to be added.
* --------------------------------------------------------
* returns whether successfully added or not.
*/
function addBonus(uint _tokenAmount) external payable returns(bool) {
require(_tokenAmount > 0 || msg.value > 0, "must send value");
if (_tokenAmount > 0)
require(token.transferFrom(msg.sender, address(this), _tokenAmount), "must approve smart contract");
emit BonusAdded(msg.sender, msg.value, _tokenAmount);
return true;
}
/*
* @dev remove staking bonuses to the pool. (only owner)
* must have enough asset to be removed
* ----------------------------------------
* @param _amountETH --> eth amount to be removed
* @param _amountToken --> token amount to be removed.
* --------------------------------------------------------
* returns whether successfully added or not.
*/
function removeETHAndTokenBouses(uint _amountETH, uint _amountToken) external onlyOwner returns (bool success) {
require(_amountETH > 0 || _amountToken > 0, "amount must be larger than zero");
if (_amountETH > 0) {
require(_checkForSufficientStakingBonusesForETH(_amountETH), 'cannot withdraw above current ETH bonus balance');
msg.sender.transfer(_amountETH);
emit BonusRemoved(msg.sender, _amountETH);
}
if (_amountToken > 0) {
require(_checkForSufficientStakingBonusesForToken(_amountToken), 'cannot withdraw above current token bonus balance');
require(token.transfer(msg.sender, _amountToken), "error: token transfer failed");
emit BonusRemoved(msg.sender, _amountToken);
}
return true;
}
/*
* @dev add unwrapped liquidity to staking pool.
* --------------------------------------------
* @param _tokenAmount --> must input token amount along with call
* @param _term --> the lockup term.
* @param _multiplier --> whether multiplier should be used or not
* 1 means you want to use the multiplier. !1 means no multiplier
* --------------------------------------------------------------
* returns whether successfully added or not.
*/
function addLiquidity(uint _term, uint _multiplier) external payable returns(bool) {
require(!getUserMigration(msg.sender), "must not be migrated already");
require(now >= _users[msg.sender].release, "cannot override current term");
require(_isValidTerm(_term), "must select a valid term");
require(msg.value > 0, "must send ETH along with transaction");
if (cap != 0) require(msg.value <= cap, "cannot provide more than the cap");
uint rate = _proportion(msg.value, address(weth), address(token));
require(token.transferFrom(msg.sender, address(this), rate), "must approve smart contract");
(uint ETH_bonus, uint token_bonus) = getUserBonusPending(msg.sender);
require(ETH_bonus == 0 && token_bonus == 0, "must first withdraw available bonus");
uint oneTenthOfRate = (rate.mul(10)).div(100);
token.approve(address(uniswapRouter), rate);
(uint amountToken, uint amountETH, uint liquidity) =
uniswapRouter.addLiquidityETH{value: msg.value}(
address(token),
rate.add(oneTenthOfRate),
0,
0,
address(this),
now.add(_012_HOURS_IN_SECONDS));
_users[msg.sender].start = now;
_users[msg.sender].release = now.add(_term);
uint previousLiquidity = _users[msg.sender].liquidity;
_users[msg.sender].liquidity = previousLiquidity.add(liquidity);
uint wethRP = _calculateReturnPercentage(weth, _term);
uint tokenRP = _calculateReturnPercentage(token, _term);
(uint provided_ETH, uint provided_token) = getUserLiquidity(msg.sender);
if (_multiplier == 1)
_withMultiplier(_term, provided_ETH, provided_token, wethRP, tokenRP);
else _withoutMultiplier(provided_ETH, provided_token, wethRP, tokenRP);
emit LiquidityAdded(msg.sender, liquidity, amountETH, amountToken);
return true;
}
/*
* @dev uses the Multiplier contract for double rewarding
* ------------------------------------------------------
* @param _term --> the lockup term.
* @param amountETH --> ETH amount provided in liquidity
* @param amountToken --> token amount provided in liquidity
* @param wethRP --> return percentge for ETH based on term period
* @param tokenRP --> return percentge for token based on term period
* --------------------------------------------------------------------
*/
function _withMultiplier(
uint _term, uint amountETH, uint amountToken, uint wethRP, uint tokenRP
) internal {
require(multiplier.balance(msg.sender) > 0, "No Multiplier balance to use");
if (_term > multiplier.lockupPeriod(msg.sender)) multiplier.updateLockupPeriod(msg.sender, _term);
uint multipliedETH = _proportion(multiplier.balance(msg.sender), uToken, address(weth));
uint multipliedToken = _proportion(multipliedETH, address(weth), address(token));
uint addedBonusWeth;
uint addedBonusToken;
if (_offersBonus(weth) && _offersBonus(token)) {
if (multipliedETH > amountETH) {
multipliedETH = (_calculateBonus((amountETH.mul(multiplier.getMultiplierCeiling())), wethRP));
addedBonusWeth = multipliedETH;
} else {
addedBonusWeth = (_calculateBonus((amountETH.add(multipliedETH)), wethRP));
}
if (multipliedToken > amountToken) {
multipliedToken = (_calculateBonus((amountToken.mul(multiplier.getMultiplierCeiling())), tokenRP));
addedBonusToken = multipliedToken;
} else {
addedBonusToken = (_calculateBonus((amountToken.add(multipliedToken)), tokenRP));
}
require(_checkForSufficientStakingBonusesForETH(addedBonusWeth)
&& _checkForSufficientStakingBonusesForToken(addedBonusToken),
"must be sufficient staking bonuses available in pool");
_users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth);
_users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken);
_pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth);
_pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken);
} else if (_offersBonus(weth) && !_offersBonus(token)) {
if (multipliedETH > amountETH) {
multipliedETH = (_calculateBonus((amountETH.mul(multiplier.getMultiplierCeiling())), wethRP));
addedBonusWeth = multipliedETH;
} else {
addedBonusWeth = (_calculateBonus((amountETH.add(multipliedETH)), wethRP));
}
require(_checkForSufficientStakingBonusesForETH(addedBonusWeth),
"must be sufficient staking bonuses available in pool");
_users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth);
_pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth);
} else if (!_offersBonus(weth) && _offersBonus(token)) {
if (multipliedToken > amountToken) {
multipliedToken = (_calculateBonus((amountToken.mul(multiplier.getMultiplierCeiling())), tokenRP));
addedBonusToken = multipliedToken;
} else {
addedBonusToken = (_calculateBonus((amountToken.add(multipliedToken)), tokenRP));
}
require(_checkForSufficientStakingBonusesForToken(addedBonusToken),
"must be sufficient staking bonuses available in pool");
_users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken);
_pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken);
}
}
/*
* @dev distributes bonus without considering Multiplier
* ------------------------------------------------------
* @param amountETH --> ETH amount provided in liquidity
* @param amountToken --> token amount provided in liquidity
* @param wethRP --> return percentge for ETH based on term period
* @param tokenRP --> return percentge for token based on term period
* --------------------------------------------------------------------
*/
function _withoutMultiplier(
uint amountETH, uint amountToken, uint wethRP, uint tokenRP
) internal {
uint addedBonusWeth;
uint addedBonusToken;
if (_offersBonus(weth) && _offersBonus(token)) {
addedBonusWeth = _calculateBonus(amountETH, wethRP);
addedBonusToken = _calculateBonus(amountToken, tokenRP);
require(_checkForSufficientStakingBonusesForETH(addedBonusWeth)
&& _checkForSufficientStakingBonusesForToken(addedBonusToken),
"must be sufficient staking bonuses available in pool");
_users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth);
_users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken);
_pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth);
_pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken);
} else if (_offersBonus(weth) && !_offersBonus(token)) {
addedBonusWeth = _calculateBonus(amountETH, wethRP);
require(_checkForSufficientStakingBonusesForETH(addedBonusWeth),
"must be sufficient staking bonuses available in pool");
_users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth);
_pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth);
} else if (!_offersBonus(weth) && _offersBonus(token)) {
addedBonusToken = _calculateBonus(amountToken, tokenRP);
require(_checkForSufficientStakingBonusesForToken(addedBonusToken),
"must be sufficient staking bonuses available in pool");
_users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken);
_pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken);
}
}
/*
* @dev relocks liquidity already provided
* --------------------------------------------
* @param _term --> the lockup term.
* @param _multiplier --> whether multiplier should be used or not
* 1 means you want to use the multiplier. !1 means no multiplier
* --------------------------------------------------------------
* returns whether successfully relocked or not.
*/
function relockLiquidity(uint _term, uint _multiplier) external returns(bool) {
require(!getUserMigration(msg.sender), "must not be migrated already");
require(_users[msg.sender].liquidity > 0, "do not have any liquidity to lock");
require(now >= _users[msg.sender].release, "cannot override current term");
require(_isValidTerm(_term), "must select a valid term");
(uint ETH_bonus, uint token_bonus) = getUserBonusPending(msg.sender);
require (ETH_bonus == 0 && token_bonus == 0, 'must withdraw available bonuses first');
(uint provided_ETH, uint provided_token) = getUserLiquidity(msg.sender);
if (cap != 0) require(provided_ETH <= cap, "cannot provide more than the cap");
uint wethRP = _calculateReturnPercentage(weth, _term);
uint tokenRP = _calculateReturnPercentage(token, _term);
_users[msg.sender].start = now;
_users[msg.sender].release = now.add(_term);
if (_multiplier == 1) _withMultiplier(_term, provided_ETH, provided_token, wethRP, tokenRP);
else _withoutMultiplier(provided_ETH, provided_token, wethRP, tokenRP);
return true;
}
/*
* @dev withdraw unwrapped liquidity by user if released.
* -------------------------------------------------------
* @param _lpAmount --> takes the amount of user's lp token to be withdrawn.
* -------------------------------------------------------------------------
* returns whether successfully withdrawn or not.
*/
function withdrawLiquidity(uint _lpAmount) external returns(bool) {
require(!getUserMigration(msg.sender), "must not be migrated already");
uint liquidity = _users[msg.sender].liquidity;
require(_lpAmount > 0 && _lpAmount <= liquidity, "do not have any liquidity");
require(now >= _users[msg.sender].release, "cannot override current term");
_users[msg.sender].liquidity = liquidity.sub(_lpAmount);
lpToken.approve(address(uniswapRouter), _lpAmount);
(uint amountToken, uint amountETH) =
uniswapRouter.removeLiquidityETH(
address(token),
_lpAmount,
1,
1,
msg.sender,
now.add(_012_HOURS_IN_SECONDS));
emit LiquidityWithdrawn(msg.sender, _lpAmount, amountETH, amountToken);
return true;
}
/*
* @dev withdraw LP token by user if released.
* -------------------------------------------------------
* returns whether successfully withdrawn or not.
*/
function withdrawUserLP() external returns(bool) {
require(!getUserMigration(msg.sender), "must not be migrated already");
uint liquidity = _users[msg.sender].liquidity;
require(liquidity > 0, "do not have any liquidity");
require(now >= _users[msg.sender].release, "cannot override current term");
_users[msg.sender].liquidity = 0;
lpToken.transfer(msg.sender, liquidity);
emit LPWithdrawn(msg.sender, liquidity);
return true;
}
/*
* @dev withdraw available staking bonuses earned from locking up liquidity.
* --------------------------------------------------------------
* returns whether successfully withdrawn or not.
*/
function withdrawUserBonus() public returns(bool) {
(uint ETH_bonus, uint token_bonus) = getUserBonusAvailable(msg.sender);
require(ETH_bonus > 0 || token_bonus > 0, "you do not have any bonus available");
uint releasedToken = _calculateTokenReleasedAmount(msg.sender);
uint releasedETH = _calculateETHReleasedAmount(msg.sender);
if (releasedToken > 0 && releasedETH > 0) {
_withdrawUserTokenBonus(msg.sender, releasedToken);
_withdrawUserETHBonus(msg.sender, releasedETH);
} else if (releasedETH > 0 && releasedToken == 0)
_withdrawUserETHBonus(msg.sender, releasedETH);
else if (releasedETH == 0 && releasedToken > 0)
_withdrawUserTokenBonus(msg.sender, releasedToken);
if (_users[msg.sender].release <= now) {
_users[msg.sender].wethWithdrawn = 0;
_users[msg.sender].tokenWithdrawn = 0;
_users[msg.sender].wethBonus = 0;
_users[msg.sender].tokenBonus = 0;
}
return true;
}
/*
* @dev withdraw ETH bonus earned from locking up liquidity
* --------------------------------------------------------------
* @param _user --> address of the user making withdrawal
* @param releasedAmount --> released ETH to be withdrawn
* ------------------------------------------------------------------
* returns whether successfully withdrawn or not.
*/
function _withdrawUserETHBonus(address payable _user, uint releasedAmount) internal returns(bool) {
_users[_user].wethWithdrawn = _users[_user].wethWithdrawn.add(releasedAmount);
_pendingBonusesWeth = _pendingBonusesWeth.sub(releasedAmount);
(uint fee, uint feeInETH) = _calculateETHFee(releasedAmount);
require(IERC20(uToken).transferFrom(_user, wallet, fee), "must approve fee");
_user.transfer(releasedAmount);
emit UserETHBonusWithdrawn(_user, releasedAmount, feeInETH);
return true;
}
/*
* @dev withdraw token bonus earned from locking up liquidity
* --------------------------------------------------------------
* @param _user --> address of the user making withdrawal
* @param releasedAmount --> released token to be withdrawn
* ------------------------------------------------------------------
* returns whether successfully withdrawn or not.
*/
function _withdrawUserTokenBonus(address _user, uint releasedAmount) internal returns(bool) {
_users[_user].tokenWithdrawn = _users[_user].tokenWithdrawn.add(releasedAmount);
_pendingBonusesToken = _pendingBonusesToken.sub(releasedAmount);
(uint fee, uint feeInToken) = _calculateTokenFee(releasedAmount);
require(IERC20(uToken).transferFrom(_user, wallet, fee), "must approve fee");
token.transfer(_user, releasedAmount);
emit UserTokenBonusWithdrawn(_user, releasedAmount, feeInToken);
return true;
}
/*
* @dev gets an asset's amount in proportion of a pair asset
* ---------------------------------------------------------
* param _amount --> the amount of first asset
* param _tokenA --> the address of the first asset
* param _tokenB --> the address of the second asset
* -------------------------------------------------
* returns the propotion of the _tokenB
*/
function _proportion(uint _amount, address _tokenA, address _tokenB) internal view returns(uint tokenBAmount) {
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(address(iUniswapV2Factory), _tokenA, _tokenB);
return UniswapV2Library.quote(_amount, reserveA, reserveB);
}
/*
* @dev gets the released Token value
* --------------------------------
* param _user --> the address of the user
* ------------------------------------------------------
* returns the released amount in Token
*/
function _calculateTokenReleasedAmount(address _user) internal view returns(uint) {
uint release = _users[_user].release;
uint start = _users[_user].start;
uint taken = _users[_user].tokenWithdrawn;
uint tokenBonus = _users[_user].tokenBonus;
uint releasedPct;
if (now >= release) releasedPct = 100;
else releasedPct = ((now.sub(start)).mul(100000)).div((release.sub(start)).mul(1000));
uint released = (((tokenBonus).mul(releasedPct)).div(100));
return released.sub(taken);
}
/*
* @dev gets the released ETH value
* --------------------------------
* param _user --> the address of the user
* ------------------------------------------------------
* returns the released amount in ETH
*/
function _calculateETHReleasedAmount(address _user) internal view returns(uint) {
uint release = _users[_user].release;
uint start = _users[_user].start;
uint taken = _users[_user].wethWithdrawn;
uint wethBonus = _users[_user].wethBonus;
uint releasedPct;
if (now >= release) releasedPct = 100;
else releasedPct = ((now.sub(start)).mul(10000)).div((release.sub(start)).mul(100));
uint released = (((wethBonus).mul(releasedPct)).div(100));
return released.sub(taken);
}
/*
* @dev get the required fee for the released token bonus in the utility token
* -------------------------------------------------------------------------------
* param _user --> the address of the user
* ----------------------------------------------------------
* returns the fee amount in the utility token and Token
*/
function _calculateTokenFee(uint _amount) internal view returns(uint uTokenFee, uint tokenFee) {
uint fee = (_amount.mul(10)).div(100);
uint feeInETH = _proportion(fee, address(token), address(weth));
uint feeInUtoken = _proportion(feeInETH, address(weth), address(uToken));
return (feeInUtoken, fee);
}
/*
* @dev get the required fee for the released ETH bonus in the utility token
* -------------------------------------------------------------------------------
* param _user --> the address of the user
* ----------------------------------------------------------
* returns the fee amount in the utility token and ETH
*/
function _calculateETHFee(uint _amount) internal view returns(uint uTokenFee, uint ethFee) {
uint fee = (_amount.mul(10)).div(100);
uint feeInUtoken = _proportion(fee, address(weth), address(uToken));
return (feeInUtoken, fee);
}
/*
* @dev get the required fee for the released ETH bonus
* -------------------------------------------------------------------------------
* param _user --> the address of the user
* ----------------------------------------------------------
* returns the fee amount.
*/
function calculateETHBonusFee(address _user) external view returns(uint ETH_Fee) {
uint wethReleased = _calculateETHReleasedAmount(_user);
if (wethReleased > 0) {
(uint feeForWethInUtoken,) = _calculateETHFee(wethReleased);
return feeForWethInUtoken;
} else return 0;
}
/*
* @dev get the required fee for the released token bonus
* -------------------------------------------------------------------------------
* param _user --> the address of the user
* ----------------------------------------------------------
* returns the fee amount.
*/
function calculateTokenBonusFee(address _user) external view returns(uint token_Fee) {
uint tokenReleased = _calculateTokenReleasedAmount(_user);
if (tokenReleased > 0) {
(uint feeForTokenInUtoken,) = _calculateTokenFee(tokenReleased);
return feeForTokenInUtoken;
} else return 0;
}
/*
* @dev get the bonus based on the return percentage for a particular locking term.
* -------------------------------------------------------------------------------
* param _amount --> the amount to calculate bonus from.
* param _returnPercentage --> the returnPercentage of the term.
* ----------------------------------------------------------
* returns the bonus amount.
*/
function _calculateBonus(uint _amount, uint _returnPercentage) internal pure returns(uint) {
return ((_amount.mul(_returnPercentage)).div(100000)) / 2; // 1% = 1000
}
/*
* @dev get the correct return percentage based on locked term.
* -----------------------------------------------------------
* @param _token --> associated asset.
* @param _term --> the locking term.
* ----------------------------------------------------------
* returns the return percentage.
*/
function _calculateReturnPercentage(IERC20 _token, uint _term) internal view returns(uint) {
if (_token == weth) {
if (_term == period1) return period1RPWeth;
else if (_term == period2) return period2RPWeth;
else if (_term == period3) return period3RPWeth;
else if (_term == period4) return period4RPWeth;
else return 0;
} else if (_token == token) {
if (_term == period1) return period1RPToken;
else if (_term == period2) return period2RPToken;
else if (_term == period3) return period3RPToken;
else if (_term == period4) return period4RPToken;
else return 0;
}
}
/*
* @dev check whether the input locking term is one of the supported terms.
* ----------------------------------------------------------------------
* @param _term --> the locking term.
* -------------------------------
* returns whether true or not.
*/
function _isValidTerm(uint _term) internal view returns(bool) {
if (_term == period1
|| _term == period2
|| _term == period3
|| _term == period4)
return true;
else return false;
}
/*
* @dev get the amount ETH and Token liquidity provided by the user.
* ------------------------------------------------------------------
* @param _user --> the address of the user.
* ---------------------------------------
* returns the amount of ETH and Token liquidity provided.
*/
function getUserLiquidity(address _user) public view returns(uint provided_ETH, uint provided_token) {
uint total = lpToken.totalSupply();
uint ratio = ((_users[_user].liquidity).mul(scalar)).div(total);
uint tokenHeld = token.balanceOf(address(lpToken));
uint wethHeld = weth.balanceOf(address(lpToken));
return ((ratio.mul(wethHeld)).div(scalar), (ratio.mul(tokenHeld)).div(scalar));
}
/*
* @dev check whether the inputted user address has been migrated.
* ----------------------------------------------------------------------
* @param _user --> ddress of the user
* ---------------------------------------
* returns whether true or not.
*/
function getUserMigration(address _user) public view returns (bool) {
return _users[_user].migrated;
}
/*
* @dev check whether the inputted user token has currently offers bonus
* ----------------------------------------------------------------------
* @param _token --> associated token
* ---------------------------------------
* returns whether true or not.
*/
function _offersBonus(IERC20 _token) internal view returns (bool) {
if (_token == weth) {
uint wethRPTotal = period1RPWeth.add(period2RPWeth).add(period3RPWeth).add(period4RPWeth);
if (wethRPTotal > 0) return true;
else return false;
} else if (_token == token) {
uint tokenRPTotal = period1RPToken.add(period2RPToken).add(period3RPToken).add(period4RPToken);
if (tokenRPTotal > 0) return true;
else return false;
}
}
/*
* @dev check whether the pool has sufficient amount of bonuses available for new deposits/stakes.
* ----------------------------------------------------------------------------------------------
* @param amount --> the _amount to be evaluated against.
* ---------------------------------------------------
* returns whether true or not.
*/
function _checkForSufficientStakingBonusesForETH(uint _amount) internal view returns(bool) {
if ((address(this).balance).sub(_pendingBonusesWeth) >= _amount) {
return true;
} else {
return false;
}
}
/*
* @dev check whether the pool has sufficient amount of bonuses available for new deposits/stakes.
* ----------------------------------------------------------------------------------------------
* @param amount --> the _amount to be evaluated against.
* ---------------------------------------------------
* returns whether true or not.
*/
function _checkForSufficientStakingBonusesForToken(uint _amount) internal view returns(bool) {
if ((token.balanceOf(address(this)).sub(_pendingBonusesToken)) >= _amount) {
return true;
} else {
return false;
}
}
/*
* @dev get the timestamp of when the user balance will be released from locked term.
* ---------------------------------------------------------------------------------
* @param _user --> the address of the user.
* ---------------------------------------
* returns the timestamp for the release.
*/
function getUserRelease(address _user) external view returns(uint release_time) {
uint release = _users[_user].release;
if (release > now) {
return (release.sub(now));
} else {
return 0;
}
}
/*
* @dev get the amount of bonuses rewarded from staking to a user.
* --------------------------------------------------------------
* @param _user --> the address of the user.
* ---------------------------------------
* returns the amount of staking bonuses.
*/
function getUserBonusPending(address _user) public view returns(uint ETH_bonus, uint token_bonus) {
uint takenWeth = _users[_user].wethWithdrawn;
uint takenToken = _users[_user].tokenWithdrawn;
return (_users[_user].wethBonus.sub(takenWeth), _users[_user].tokenBonus.sub(takenToken));
}
/*
* @dev get the amount of released bonuses rewarded from staking to a user.
* --------------------------------------------------------------
* @param _user --> the address of the user.
* ---------------------------------------
* returns the amount of released staking bonuses.
*/
function getUserBonusAvailable(address _user) public view returns(uint ETH_Released, uint token_Released) {
uint ETHValue = _calculateETHReleasedAmount(_user);
uint tokenValue = _calculateTokenReleasedAmount(_user);
return (ETHValue, tokenValue);
}
/*
* @dev get the amount of liquidity pool tokens staked/locked by user.
* ------------------------------------------------------------------
* @param _user --> the address of the user.
* ---------------------------------------
* returns the amount of locked liquidity.
*/
function getUserLPTokens(address _user) external view returns(uint user_LP) {
return _users[_user].liquidity;
}
/*
* @dev get the lp token address for the pair.
* -----------------------------------------------------------
* returns the lp address for eth/token pair.
*/
function getLPAddress() external view returns(address) {
return address(lpToken);
}
/*
* @dev get the amount of staking bonuses available in the pool.
* -----------------------------------------------------------
* returns the amount of staking bounses available for ETH and Token.
*/
function getAvailableBonus() external view returns(uint available_ETH, uint available_token) {
available_ETH = (address(this).balance).sub(_pendingBonusesWeth);
available_token = (token.balanceOf(address(this))).sub(_pendingBonusesToken);
return (available_ETH, available_token);
}
/*
* @dev get the maximum amount of ETH allowed for provisioning.
* -----------------------------------------------------------
* returns the maximum ETH allowed
*/
function getCap() external view returns(uint maxETH) {
return cap;
}
/*
* @dev checks the term period and return percentages
* --------------------------------------------------
* returns term period and return percentages
*/
function getTermPeriodAndReturnPercentages() external view returns(
uint Term_Period_1, uint Term_Period_2, uint Term_Period_3, uint Term_Period_4,
uint Period_1_Return_Percentage_Token, uint Period_2_Return_Percentage_Token,
uint Period_3_Return_Percentage_Token, uint Period_4_Return_Percentage_Token,
uint Period_1_Return_Percentage_ETH, uint Period_2_Return_Percentage_ETH,
uint Period_3_Return_Percentage_ETH, uint Period_4_Return_Percentage_ETH
) {
return (
period1, period2, period3, period4, period1RPToken, period2RPToken, period3RPToken,
period4RPToken,period1RPWeth, period2RPWeth, period3RPWeth, period4RPWeth);
}
}
contract PoolStakeFactory {
//array of PoolStake contracts
address[] private _poolStakes;
//event on contract creation
event Created(address indexed Creator, address Contract, address indexed Token);
/*
* @dev get the length of all contracts created
* -----------------------------------------------------------
* returns number of contracts created
*/
function totalContracts() external view returns(uint256) {
return _poolStakes.length;
}
/*
* @dev get an array of all contracts created
* -----------------------------------------------------------
* returns all contracts created
*/
function getContracts() external view returns(address[] memory) {
return _poolStakes;
}
/*
* @dev create a new contract prototype.
* -------------------------------------
* @param _token --> the ETH-pair token address
* -------------------------------------------------
* returns whether successfully changed or not.
*/
function createContract(address _token) external returns(bool) {
PoolStake poolStake = new PoolStake(_token, msg.sender);
_poolStakes.push(address(poolStake));
emit Created(msg.sender, address(poolStake), _token);
return true;
}
}
|
@dev get the required fee for the released token bonus ------------------------------------------------------------------------------- param _user --> the address of the user ---------------------------------------------------------- returns the fee amount./
|
function calculateTokenBonusFee(address _user) external view returns(uint token_Fee) {
uint tokenReleased = _calculateTokenReleasedAmount(_user);
if (tokenReleased > 0) {
(uint feeForTokenInUtoken,) = _calculateTokenFee(tokenReleased);
return feeForTokenInUtoken;
} else return 0;
}
| 577,606 |
[
1,
588,
326,
1931,
14036,
364,
326,
15976,
1147,
324,
22889,
8879,
17908,
579,
389,
1355,
15431,
326,
1758,
434,
326,
729,
13420,
8567,
1135,
326,
14036,
3844,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
4604,
1345,
38,
22889,
14667,
12,
2867,
389,
1355,
13,
3903,
1476,
1135,
12,
11890,
1147,
67,
14667,
13,
288,
203,
540,
203,
3639,
2254,
1147,
26363,
273,
389,
11162,
1345,
26363,
6275,
24899,
1355,
1769,
203,
540,
203,
3639,
309,
261,
2316,
26363,
405,
374,
13,
288,
203,
2398,
203,
5411,
261,
11890,
14036,
1290,
1345,
382,
57,
2316,
16,
13,
273,
389,
11162,
1345,
14667,
12,
2316,
26363,
1769,
203,
2398,
203,
5411,
327,
14036,
1290,
1345,
382,
57,
2316,
31,
203,
2398,
203,
3639,
289,
469,
327,
374,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
contract BitOpterations {
// helper functions set
// to manipulate on bits
// with different widht of allocator
function set512(bytes32[2] storage allocator,uint16 pos,uint8 value) internal returns( bytes32[2] storage) {
bytes32 valueBits = (bytes32)(value);
uint8 posOffset = uint8(pos%255);
bytes32 one = 1;
bytes32 clearBit = (bytes32)(~(one << posOffset));
uint8 bytesIndex = pos>255?1:0;
allocator[bytesIndex] = (allocator[bytesIndex] & clearBit) | (valueBits << posOffset);
return allocator;
}
function get512(bytes32[2] allocator,uint16 pos) internal pure returns(uint8){
uint8 posOffset = uint8(pos%255);
uint8 bytesIndex = pos>255?1:0;
return (((allocator[bytesIndex] >> posOffset) & 1) == 1)?1:0;
}
function clear512(bytes32[2] storage allocator) internal {
allocator[0] = 0x0;
allocator[1] = 0x0;
}
function set32(bytes4 allocator,uint8 pos, uint8 value) internal pure returns(bytes4) {
bytes4 valueBits = (bytes4)(value);
bytes4 one = 1;
bytes4 clearBit = (bytes4)(~(one << pos));
allocator = (allocator & clearBit) | (valueBits << pos);
return allocator;
}
function get32(bytes4 allocator,uint8 pos) internal pure returns(uint8){
return (((allocator >> pos) & 1) == 1)?1:0;
}
}
contract Random32BigInteger is BitOpterations {
uint256[10] public randomBlockStart;
bytes4[10] private numberAllocator;
bool[10] internal generated;
uint256 private generationNumber = 0;
function generate(uint8 lotteryId) internal returns(bool) {
// to eliminate problem of `same random numbers` lets add
// some offset on each number generation
uint8 startOffset = uint8((generationNumber++) % 10);
if (randomBlockStart[lotteryId] == 0) {
// start random number generation from next block,
// so we can't influence it
randomBlockStart[lotteryId] = block.number + startOffset;
} else {
uint256 blockDiffNumber = block.number - randomBlockStart[lotteryId];
// revert tx if we haven't enough blocks to calc rand int
require(blockDiffNumber >= 32);
// its not possible to calc fair random number with start at randomBlockStart
// because part of blocks or all blocks are not visible from solidity anymore
// start generation process one more time
if (blockDiffNumber > 256) {
randomBlockStart[lotteryId] = block.number + startOffset;
} else {
for (uint8 i = 0; i < 32; i++) {
// get hash of appropriate block
uint256 blockHash = uint256(block.blockhash(randomBlockStart[lotteryId]+i));
// set appropriate bit in result number
numberAllocator[lotteryId] = set32(numberAllocator[lotteryId],i,uint8(blockHash));
}
generated[lotteryId] = true;
randomBlockStart[lotteryId] = 0;
}
}
return generated[lotteryId];
}
function clearNumber(uint8 lotteryId) internal {
randomBlockStart[lotteryId] = 0;
generated[lotteryId] = false;
}
function getNumberValue(uint8 lotteryId) internal constant returns(uint32) {
require(generated[lotteryId]);
return uint32(numberAllocator[lotteryId]);
}
}
contract EthereumJackpot is Random32BigInteger {
address private owner;
event WinnerPicked(uint8 indexed roomId,address winner,uint16 number);
event TicketsBought(uint8 indexed roomId,address owner,uint16[] ticketNumbers);
event LostPayment(address dest,uint256 amount);
struct Winner {
uint256 prize;
uint256 timestamp;
address addr;
uint16 number;
uint8 percent;
}
mapping (address => address) public affiliates;
Winner[] private winners;
uint32 public winnersCount;
modifier ownerOnly {
require(msg.sender == owner);
_;
}
uint8 public affiliatePercent = 1;
uint8 public maxPercentPerPlayer = 49;
uint8 public ownerComission = 20;
// time on which lottery has started
uint256[10] public started;
// last activity time on lottery
uint256[10] public lastTicketBought;
// one ticket price
uint256[10] public ticketPrice;
// max number of tickets in this lottery
uint16[10] public maxTickets;
// time to live before refund can be requested
uint256[10] public lifetime;
address[][10] ticketsAllocator;
struct Player {
uint256 changedOn;
uint16 ticketsCount;
}
mapping(address => Player)[10] private playerInfoMappings;
bytes32[2][10] bitMaskForPlayFields;
enum State {Uninitialized,Running,Paused,Finished,Refund}
State[10] public state;
// flag that indicates request for pause of lottery[id]
bool[10] private requestPause;
// number of sold tickets
uint16[10] public ticketsSold;
// this function set flag to pause room on next clearState call (at the game start)
function pauseLottery(uint8 lotteryId) public ownerOnly {
requestPause[lotteryId] = true;
}
function setOwner(address newOwner) public ownerOnly {
owner = newOwner;
}
function getTickets(uint8 lotteryId) public view returns(uint8[]) {
uint8[] memory result = new uint8[](maxTickets[lotteryId]);
for (uint16 i = 0; i < maxTickets[lotteryId]; i++) {
result[i] = get512(bitMaskForPlayFields[lotteryId],i);
}
return result;
}
function setLotteryOptions(uint8 lotteryId,uint256 price,uint16 tickets,uint256 timeToRefund) public ownerOnly {
require(lotteryId >= 0 && lotteryId < 10);
// only allow change of lottery opts when it's in pause state, unitialized or no tickets are sold there yet
require(state[lotteryId] == State.Paused || state[lotteryId] == State.Uninitialized || ticketsSold[lotteryId] == 0);
require(price > 0);
require(tickets > 0 && tickets <= 500);
require(timeToRefund >= 86400); // require at least one day to sell all tickets
ticketPrice[lotteryId] = price;
maxTickets[lotteryId] = tickets;
lifetime[lotteryId] = timeToRefund;
ticketsAllocator[lotteryId].length = tickets;
clearState(lotteryId);
}
// this methods clears the state
// of current lottery
function clearState(uint8 lotteryId) private {
if (!requestPause[lotteryId]) {
// set state of lottery to `running`
state[lotteryId] = State.Running;
// clear random number data
clearNumber(lotteryId);
// set current timestamp as start time
started[lotteryId] = block.timestamp;
// clear time of last ticket bought
lastTicketBought[lotteryId] = 0;
// clear number of sold tickets
ticketsSold[lotteryId] = 0;
// remove previous tickets owner info
clear512(bitMaskForPlayFields[lotteryId]);
} else {
// set state to `pause`
state[lotteryId] = State.Paused;
requestPause[lotteryId] = false;
}
}
function isInList(address element,address[] memory list) private pure returns (bool) {
for (uint16 i =0; i < list.length; i++) {
if (list[i] == element) {
return true;
}
}
return false;
}
function getPlayers(uint8 lotteryId) external view returns (uint16,address[],uint16[]) {
if (ticketsSold[lotteryId] == 0) {
return;
}
uint16 currentUser = 0;
address[] memory resultAddr = new address[](maxTickets[lotteryId]);
uint16[] memory resultCount = new uint16[](maxTickets[lotteryId]);
for (uint16 t = 0; t < maxTickets[lotteryId]; t++) {
uint8 ticketBoughtHere = get512(bitMaskForPlayFields[lotteryId],t);
if (ticketBoughtHere != 0) {
address currentAddr = ticketsAllocator[lotteryId][t];
if (!isInList(currentAddr,resultAddr)) {
Player storage pInfo = playerInfoMappings[lotteryId][currentAddr];
resultAddr[currentUser] = currentAddr;
resultCount[currentUser] = pInfo.ticketsCount;
++currentUser;
}
}
}
return (currentUser,resultAddr,resultCount);
}
// in case lottery tickets weren't sold due some time
// anybody who bought a ticket can
// ask to refund money (- comission to send them)
function refund(uint8 lotteryId) public {
// refund state could be reached only from `running` state
require (state[lotteryId] == State.Running);
require (block.timestamp > (started[lotteryId] + lifetime[lotteryId]));
require (ticketsSold[lotteryId] < maxTickets[lotteryId]);
// check if its a person which plays this lottery
// or it's a lottery owner
require(msg.sender == owner || playerInfoMappings[lotteryId][msg.sender].changedOn > started[lotteryId]);
uint256 notSend = 0;
// disallow re-entrancy
// refund process
state[lotteryId] = State.Refund;
for (uint16 i = 0; i < maxTickets[lotteryId]; i++) {
address tOwner = ticketsAllocator[lotteryId][i];
if (tOwner != address(0)) {
uint256 value = playerInfoMappings[lotteryId][tOwner].ticketsCount*ticketPrice[lotteryId];
bool sendResult = tOwner.send(value);
if (!sendResult) {
LostPayment(tOwner,value);
notSend += value;
}
}
}
// send rest to owner if there any
if (notSend > 0) {
owner.send(notSend);
}
// start new lottery
clearState(lotteryId);
}
// this method determines current game winner
function getWinner(uint8 lotteryId) private view returns(uint16,address) {
require(state[lotteryId] == State.Finished);
// apply modulo operation
// so any ticket number would be within 0 and totalTickets sold
uint16 winningTicket = uint16(getNumberValue(lotteryId)) % maxTickets[lotteryId];
return (winningTicket,ticketsAllocator[lotteryId][winningTicket]);
}
// this method is used to finalize Lottery
// it generates random number and sends prize
// it uses 32 blocks to generate pseudo random
// value to determine winner of lottery
function finalizeRoom(uint8 lotteryId) public {
// here we check for re-entrancy
require(state[lotteryId] == State.Running);
// only if all tickets are sold
if (ticketsSold[lotteryId] == maxTickets[lotteryId]) {
// if rand number is not yet generated
if (generate(lotteryId)) {
// rand number is generated
// set flag to allow getting winner
// disable re-entrancy
state[lotteryId] = State.Finished;
var (winNumber, winner) = getWinner(lotteryId);
uint256 prizeTotal = ticketsSold[lotteryId]*ticketPrice[lotteryId];
// at start, owner commision value equals to the approproate percent of the jackpot
uint256 ownerComValue = ((prizeTotal*ownerComission)/100);
// winner prize equals total jackpot sum - owner commision value in any case
uint256 prize = prizeTotal - ownerComValue;
address affiliate = affiliates[winner];
if (affiliate != address(0)) {
uint256 affiliatePrize = (prizeTotal*affiliatePercent)/100;
bool afPResult = affiliate.send(affiliatePrize);
if (!afPResult) {
LostPayment(affiliate,affiliatePrize);
} else {
// minus affiliate prize and "gas price" for that tx from owners com value
ownerComValue -= affiliatePrize;
}
}
// pay prize
bool prizeSendResult = winner.send(prize);
if (!prizeSendResult) {
LostPayment(winner,prize);
ownerComValue += prize;
}
// put winner to winners
uint8 winPercent = uint8(((playerInfoMappings[lotteryId][winner].ticketsCount*100)/maxTickets[lotteryId]));
addWinner(prize,winner,winNumber,winPercent);
WinnerPicked(lotteryId,winner,winNumber);
// send owner commision
owner.send(ownerComValue);
clearState(lotteryId);
}
}
}
function buyTicket(uint8 lotteryId,uint16[] tickets,address referer) payable public {
// we're actually in `running` state
require(state[lotteryId] == State.Running);
// not all tickets are sold yet
require(maxTickets[lotteryId] > ticketsSold[lotteryId]);
if (referer != address(0)) {
setReferer(referer);
}
uint16 ticketsToBuy = uint16(tickets.length);
// check payment for ticket
uint256 valueRequired = ticketsToBuy*ticketPrice[lotteryId];
require(valueRequired <= msg.value);
// soft check if player want to buy free tickets
require((maxTickets[lotteryId] - ticketsSold[lotteryId]) >= ticketsToBuy);
Player storage pInfo = playerInfoMappings[lotteryId][msg.sender];
if (pInfo.changedOn < started[lotteryId]) {
pInfo.changedOn = block.timestamp;
pInfo.ticketsCount = 0;
}
// check percentage of user's tickets
require ((pInfo.ticketsCount+ticketsToBuy) <= ((maxTickets[lotteryId]*maxPercentPerPlayer)/100));
for (uint16 i; i < ticketsToBuy; i++) {
require((tickets[i] - 1) >= 0);
// if the ticket is taken you would get your ethers back
require (get512(bitMaskForPlayFields[lotteryId],tickets[i]-1) == 0);
set512(bitMaskForPlayFields[lotteryId],tickets[i]-1,1);
ticketsAllocator[lotteryId][tickets[i]-1] = msg.sender;
}
pInfo.ticketsCount += ticketsToBuy;
// set last time of buy
lastTicketBought[lotteryId] = block.timestamp;
// set new amount of tickets
ticketsSold[lotteryId] += ticketsToBuy;
// start process of random number generation if last ticket was sold
if (ticketsSold[lotteryId] == maxTickets[lotteryId]) {
finalizeRoom(lotteryId);
}
// fire event
TicketsBought(lotteryId,msg.sender,tickets);
}
function roomNeedsFinalization(uint8 lotteryId) internal view returns (bool){
return (state[lotteryId] == State.Running && (ticketsSold[lotteryId] >= maxTickets[lotteryId]) && ((randomBlockStart[lotteryId] == 0) || ((randomBlockStart[lotteryId] > 0) && (block.number - randomBlockStart[lotteryId]) >= 32)));
}
function EthereumJackpot(address ownerAddress) public {
require(ownerAddress != address(0));
owner = ownerAddress;
winners.length = 5;
winnersCount = 0;
}
function addWinner(uint256 prize,address winner,uint16 number,uint8 percent) private {
// check winners size and resize it if needed
if (winners.length == winnersCount) {
winners.length += 10;
}
winners[winnersCount++] = Winner(prize,block.timestamp,winner,number,percent);
}
function setReferer(address a) private {
if (a != msg.sender) {
address addr = affiliates[msg.sender];
if (addr == address(0)) {
affiliates[msg.sender] = a;
}
}
}
// // returns only x last winners to prevent stack overflow of vm
function getWinners(uint256 page) public view returns(uint256[],address[],uint256[],uint16[],uint8[]) {
int256 start = winnersCount - int256(10*(page+1));
int256 end = start+10;
if (start < 0) {
start = 0;
}
if (end <= 0) {
return;
}
address[] memory addr = new address[](uint256(end- start));
uint256[] memory sum = new uint256[](uint256(end- start));
uint256[] memory time = new uint256[](uint256(end- start));
uint16[] memory number = new uint16[](uint256(end- start));
uint8[] memory percent = new uint8[](uint256(end- start));
for (uint256 i = uint256(start); i < uint256(end); i++) {
Winner storage winner = winners[i];
addr[i - uint256(start)] = winner.addr;
sum[i - uint256(start)] = winner.prize;
time[i - uint256(start)] = winner.timestamp;
number[i - uint256(start)] = winner.number;
percent[i - uint256(start)] = winner.percent;
}
return (sum,addr,time,number,percent);
}
function getRomms() public view returns(bool[] active,uint256[] price,uint16[] tickets,uint16[] ticketsBought,uint256[] prize,uint256[] lastActivity,uint8[] comission) {
uint8 roomsCount = 10;
price = new uint256[](roomsCount);
tickets = new uint16[](roomsCount);
lastActivity = new uint256[](roomsCount);
prize = new uint256[](roomsCount);
comission = new uint8[](roomsCount);
active = new bool[](roomsCount);
ticketsBought = new uint16[](roomsCount);
for (uint8 i = 0; i < roomsCount; i++) {
price[i] = ticketPrice[i];
ticketsBought[i] = ticketsSold[i];
tickets[i] = maxTickets[i];
prize[i] = maxTickets[i]*ticketPrice[i];
lastActivity[i] = lastTicketBought[i];
comission[i] = ownerComission;
active[i] = state[i] != State.Paused && state[i] != State.Uninitialized;
}
return (active,price,tickets,ticketsBought,prize,lastActivity,comission);
}
// this function allows to destroy current contract in case all rooms are paused or not used
function destroy() public ownerOnly {
for (uint8 i = 0; i < 10; i++) {
// paused or uninitialized
require(state[i] == State.Paused || state[i] == State.Uninitialized);
}
selfdestruct(owner);
}
// finalize methods
function needsFinalization() public view returns(bool) {
for (uint8 i = 0; i < 10; i++) {
if (roomNeedsFinalization(i)) {
return true;
}
}
return false;
}
function finalize() public {
for (uint8 i = 0; i < 10; i++) {
if (roomNeedsFinalization(i)) {
finalizeRoom(i);
}
}
}
}
|
set last time of buy
|
lastTicketBought[lotteryId] = block.timestamp;
| 13,054,399 |
[
1,
542,
1142,
813,
434,
30143,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
3639,
1142,
13614,
13809,
9540,
63,
23372,
387,
93,
548,
65,
273,
1203,
18,
5508,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xe380D8F33cBeC7d38e7450BC8cc554FBC7aD13ec/sources/contracts/sale.sol
|
* @notice Update NFT sale price. @dev Update price for each sale phase. Only owner can call this function. @param _phaseOnePrice Price of phase one sale in wei. @param _phaseTwoPrice Price of phase two sale in wei. @param _phaseThreePrice Price of phase three sale in wei./
|
function updateSalePrice(
uint256 _phaseOnePrice,
uint256 _phaseTwoPrice,
uint256 _phaseThreePrice
) external onlyOwner {
phaseOnePrice = _phaseOnePrice;
phaseTwoPrice = _phaseTwoPrice;
phaseThreePrice = _phaseThreePrice;
emit UpdateSalePrice(_phaseOnePrice, _phaseTwoPrice, _phaseThreePrice);
}
| 2,995,880 |
[
1,
1891,
423,
4464,
272,
5349,
6205,
18,
225,
2315,
6205,
364,
1517,
272,
5349,
6855,
18,
5098,
3410,
848,
745,
333,
445,
18,
225,
389,
13961,
3335,
5147,
20137,
434,
6855,
1245,
272,
5349,
316,
732,
77,
18,
225,
389,
13961,
11710,
5147,
20137,
434,
6855,
2795,
272,
5349,
316,
732,
77,
18,
225,
389,
13961,
28019,
5147,
20137,
434,
6855,
8925,
272,
5349,
316,
732,
77,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
1089,
30746,
5147,
12,
203,
3639,
2254,
5034,
389,
13961,
3335,
5147,
16,
203,
3639,
2254,
5034,
389,
13961,
11710,
5147,
16,
203,
3639,
2254,
5034,
389,
13961,
28019,
5147,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
6855,
3335,
5147,
273,
389,
13961,
3335,
5147,
31,
203,
3639,
6855,
11710,
5147,
273,
389,
13961,
11710,
5147,
31,
203,
3639,
6855,
28019,
5147,
273,
389,
13961,
28019,
5147,
31,
203,
3639,
3626,
2315,
30746,
5147,
24899,
13961,
3335,
5147,
16,
389,
13961,
11710,
5147,
16,
389,
13961,
28019,
5147,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/IERC20Permit.sol";
import "./lib/SafeERC20.sol";
import "./lib/ReentrancyGuard.sol";
/**
* @title Payments
* @dev Contract for streaming token payments for set periods of time
*/
contract Payments is ReentrancyGuard {
using SafeERC20 for IERC20;
/// @notice Payment definition
struct Payment {
address token;
address receiver;
address payer;
uint48 startTime;
uint48 stopTime;
uint16 cliffDurationInDays;
uint256 paymentDurationInSecs;
uint256 amount;
uint256 amountClaimed;
}
/// @notice Payment balance definition
struct PaymentBalance {
uint256 id;
uint256 claimableAmount;
Payment payment;
}
/// @notice Token balance definition
struct TokenBalance {
uint256 totalAmount;
uint256 claimableAmount;
uint256 claimedAmount;
}
/// @dev Used to translate payment periods specified in days to seconds
uint256 constant internal SECONDS_PER_DAY = 86400;
/// @notice Mapping of payment id > token payments
mapping (uint256 => Payment) public tokenPayments;
/// @notice Mapping of address to payment id
mapping (address => uint256[]) public paymentIds;
/// @notice Number of payments
uint256 public numPayments;
/// @notice Event emitted when a new payment is created
event PaymentCreated(address indexed token, address indexed payer, address indexed receiver, uint256 paymentId, uint256 amount, uint48 startTime, uint256 durationInSecs, uint16 cliffInDays);
/// @notice Event emitted when tokens are claimed by a receiver from an available balance
event TokensClaimed(address indexed receiver, address indexed token, uint256 indexed paymentId, uint256 amountClaimed);
/// @notice Event emitted when payment stopped
event PaymentStopped(uint256 indexed paymentId, uint256 indexed originalDuration, uint48 stopTime, uint48 startTime);
/**
* @notice Create payment, optionally providing voting power
* @param payer The account that is paymenting tokens
* @param receiver The account that will be able to retrieve available tokens
* @param startTime The unix timestamp when the payment period will start
* @param amount The amount of tokens being paid
* @param paymentDurationInSecs The payment period in seconds
* @param cliffDurationInDays The cliff duration in days
*/
function createPayment(
address token,
address payer,
address receiver,
uint48 startTime,
uint256 amount,
uint256 paymentDurationInSecs,
uint16 cliffDurationInDays
)
external
{
require(paymentDurationInSecs > 0, "Payments::createPayment: payment duration must be > 0");
require(paymentDurationInSecs <= 25*365*SECONDS_PER_DAY, "Payments::createPayment: payment duration more than 25 years");
require(paymentDurationInSecs >= SECONDS_PER_DAY*cliffDurationInDays, "Payments::createPayment: payment duration < cliff");
require(amount > 0, "Payments::createPayment: amount not > 0");
_createPayment(token, payer, receiver, startTime, amount, paymentDurationInSecs, cliffDurationInDays);
}
/**
* @notice Create payment, using permit for approval
* @dev It is up to the frontend developer to ensure the token implements permit - otherwise this will fail
* @param token Address of token to payment
* @param payer The account that is paymenting tokens
* @param receiver The account that will be able to retrieve available tokens
* @param startTime The unix timestamp when the payment period will start
* @param amount The amount of tokens being paid
* @param paymentDurationInSecs The payment period in seconds
* @param cliffDurationInDays The payment cliff duration in days
* @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 createPaymentWithPermit(
address token,
address payer,
address receiver,
uint48 startTime,
uint256 amount,
uint256 paymentDurationInSecs,
uint16 cliffDurationInDays,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(paymentDurationInSecs > 0, "Payments::createPaymentWithPermit: payment duration must be > 0");
require(paymentDurationInSecs <= 25*365*SECONDS_PER_DAY, "Payments::createPaymentWithPermit: payment duration more than 25 years");
require(paymentDurationInSecs >= SECONDS_PER_DAY*cliffDurationInDays, "Payments::createPaymentWithPermit: duration < cliff");
require(amount > 0, "Payments::createPaymentWithPermit: amount not > 0");
// Set approval using permit signature
IERC20Permit(token).permit(payer, address(this), amount, deadline, v, r, s);
_createPayment(token, payer, receiver, startTime, amount, paymentDurationInSecs, cliffDurationInDays);
}
/**
* @notice Get all active token payment ids
* @return the payment ids
*/
function allActivePaymentIds() external view returns(uint256[] memory){
uint256 activeCount;
// Get number of active payments
for (uint256 i; i < numPayments; i++) {
if(claimableBalance(i) > 0) {
activeCount++;
}
}
// Create result array of length `activeCount`
uint256[] memory result = new uint256[](activeCount);
uint256 j;
// Populate result array
for (uint256 i; i < numPayments; i++) {
if(claimableBalance(i) > 0) {
result[j] = i;
j++;
}
}
return result;
}
/**
* @notice Get all active token payments
* @return the payments
*/
function allActivePayments() external view returns(Payment[] memory){
uint256 activeCount;
// Get number of active payments
for (uint256 i; i < numPayments; i++) {
if(claimableBalance(i) > 0) {
activeCount++;
}
}
// Create result array of length `activeCount`
Payment[] memory result = new Payment[](activeCount);
uint256 j;
// Populate result array
for (uint256 i; i < numPayments; i++) {
if(claimableBalance(i) > 0) {
result[j] = tokenPayments[i];
j++;
}
}
return result;
}
/**
* @notice Get all active token payment balances
* @return the active payment balances
*/
function allActivePaymentBalances() external view returns(PaymentBalance[] memory){
uint256 activeCount;
// Get number of active payments
for (uint256 i; i < numPayments; i++) {
if(claimableBalance(i) > 0) {
activeCount++;
}
}
// Create result array of length `activeCount`
PaymentBalance[] memory result = new PaymentBalance[](activeCount);
uint256 j;
// Populate result array
for (uint256 i; i < numPayments; i++) {
if(claimableBalance(i) > 0) {
result[j] = paymentBalance(i);
j++;
}
}
return result;
}
/**
* @notice Get all active token payment ids for receiver
* @param receiver The address that has paid balances
* @return the active payment ids
*/
function activePaymentIds(address receiver) external view returns(uint256[] memory){
uint256 activeCount;
uint256[] memory receiverPaymentIds = paymentIds[receiver];
// Get number of active payments
for (uint256 i; i < receiverPaymentIds.length; i++) {
if(claimableBalance(receiverPaymentIds[i]) > 0) {
activeCount++;
}
}
// Create result array of length `activeCount`
uint256[] memory result = new uint256[](activeCount);
uint256 j;
// Populate result array
for (uint256 i; i < receiverPaymentIds.length; i++) {
if(claimableBalance(receiverPaymentIds[i]) > 0) {
result[j] = receiverPaymentIds[i];
j++;
}
}
return result;
}
/**
* @notice Get all token payments for receiver
* @param receiver The address that has paid balances
* @return the payments
*/
function allPayments(address receiver) external view returns(Payment[] memory){
uint256[] memory allPaymentIds = paymentIds[receiver];
Payment[] memory result = new Payment[](allPaymentIds.length);
for (uint256 i; i < allPaymentIds.length; i++) {
result[i] = tokenPayments[allPaymentIds[i]];
}
return result;
}
/**
* @notice Get all active token payments for receiver
* @param receiver The address that has paid balances
* @return the payments
*/
function activePayments(address receiver) external view returns(Payment[] memory){
uint256 activeCount;
uint256[] memory receiverPaymentIds = paymentIds[receiver];
// Get number of active payments
for (uint256 i; i < receiverPaymentIds.length; i++) {
if(claimableBalance(receiverPaymentIds[i]) > 0) {
activeCount++;
}
}
// Create result array of length `activeCount`
Payment[] memory result = new Payment[](activeCount);
uint256 j;
// Populate result array
for (uint256 i; i < receiverPaymentIds.length; i++) {
if(claimableBalance(receiverPaymentIds[i]) > 0) {
result[j] = tokenPayments[receiverPaymentIds[i]];
j++;
}
}
return result;
}
/**
* @notice Get all active token payment balances for receiver
* @param receiver The address that has paid balances
* @return the active payment balances
*/
function activePaymentBalances(address receiver) external view returns(PaymentBalance[] memory){
uint256 activeCount;
uint256[] memory receiverPaymentIds = paymentIds[receiver];
// Get number of active payments
for (uint256 i; i < receiverPaymentIds.length; i++) {
if(claimableBalance(receiverPaymentIds[i]) > 0) {
activeCount++;
}
}
// Create result array of length `activeCount`
PaymentBalance[] memory result = new PaymentBalance[](activeCount);
uint256 j;
// Populate result array
for (uint256 i; i < receiverPaymentIds.length; i++) {
if(claimableBalance(receiverPaymentIds[i]) > 0) {
result[j] = paymentBalance(receiverPaymentIds[i]);
j++;
}
}
return result;
}
/**
* @notice Get total token balance
* @param token The token to check
* @return balance the total active balance of `token`
*/
function totalTokenBalance(address token) external view returns(TokenBalance memory balance){
for (uint256 i; i < numPayments; i++) {
Payment memory tokenPayment = tokenPayments[i];
if(tokenPayment.token == token && tokenPayment.startTime != tokenPayment.stopTime){
balance.totalAmount = balance.totalAmount + tokenPayment.amount;
if(block.timestamp > tokenPayment.startTime) {
balance.claimedAmount = balance.claimedAmount + tokenPayment.amountClaimed;
uint256 elapsedTime = tokenPayment.stopTime > 0 && tokenPayment.stopTime < block.timestamp ? tokenPayment.stopTime - tokenPayment.startTime : block.timestamp - tokenPayment.startTime;
uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY;
if (
elapsedDays >= tokenPayment.cliffDurationInDays
) {
if (tokenPayment.stopTime == 0 && elapsedTime >= tokenPayment.paymentDurationInSecs) {
balance.claimableAmount = balance.claimableAmount + tokenPayment.amount - tokenPayment.amountClaimed;
} else {
uint256 paymentAmountPerSec = tokenPayment.amount / tokenPayment.paymentDurationInSecs;
uint256 amountAvailable = paymentAmountPerSec * elapsedTime;
balance.claimableAmount = balance.claimableAmount + amountAvailable - tokenPayment.amountClaimed;
}
}
}
}
}
}
/**
* @notice Get token balance of receiver
* @param token The token to check
* @param receiver The address that has available balances
* @return balance the total active balance of `token` for `receiver`
*/
function tokenBalance(address token, address receiver) external view returns(TokenBalance memory balance){
uint256[] memory receiverPaymentIds = paymentIds[receiver];
for (uint256 i; i < receiverPaymentIds.length; i++) {
Payment memory receiverPayment = tokenPayments[receiverPaymentIds[i]];
if(receiverPayment.token == token && receiverPayment.startTime != receiverPayment.stopTime){
balance.totalAmount = balance.totalAmount + receiverPayment.amount;
if(block.timestamp > receiverPayment.startTime) {
balance.claimedAmount = balance.claimedAmount + receiverPayment.amountClaimed;
uint256 elapsedTime = receiverPayment.stopTime > 0 && receiverPayment.stopTime < block.timestamp ? receiverPayment.stopTime - receiverPayment.startTime : block.timestamp - receiverPayment.startTime;
uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY;
if (
elapsedDays >= receiverPayment.cliffDurationInDays
) {
if (receiverPayment.stopTime == 0 && elapsedTime >= receiverPayment.paymentDurationInSecs) {
balance.claimableAmount = balance.claimableAmount + receiverPayment.amount - receiverPayment.amountClaimed;
} else {
uint256 paymentAmountPerSec = receiverPayment.amount / receiverPayment.paymentDurationInSecs;
uint256 amountAvailable = paymentAmountPerSec * elapsedTime;
balance.claimableAmount = balance.claimableAmount + amountAvailable - receiverPayment.amountClaimed;
}
}
}
}
}
}
/**
* @notice Get payment balance for a given payment id
* @param paymentId The payment ID
* @return balance the payment balance
*/
function paymentBalance(uint256 paymentId) public view returns (PaymentBalance memory balance) {
balance.id = paymentId;
balance.claimableAmount = claimableBalance(paymentId);
balance.payment = tokenPayments[paymentId];
}
/**
* @notice Get claimable balance for a given payment id
* @dev Returns 0 if cliff duration has not ended
* @param paymentId The payment ID
* @return The amount that can be claimed
*/
function claimableBalance(uint256 paymentId) public view returns (uint256) {
Payment storage payment = tokenPayments[paymentId];
// For payments created with a future start date or payments stopped before starting, that hasn't been reached, return 0
if (block.timestamp < payment.startTime || payment.startTime == payment.stopTime) {
return 0;
}
uint256 elapsedTime = payment.stopTime > 0 && payment.stopTime < block.timestamp ? payment.stopTime - payment.startTime : block.timestamp - payment.startTime;
uint256 elapsedDays = elapsedTime / SECONDS_PER_DAY;
if (elapsedDays < payment.cliffDurationInDays) {
return 0;
}
if (payment.stopTime == 0 && elapsedTime >= payment.paymentDurationInSecs) {
return payment.amount - payment.amountClaimed;
}
uint256 paymentAmountPerSec = payment.amount / payment.paymentDurationInSecs;
uint256 amountAvailable = paymentAmountPerSec * elapsedTime;
return amountAvailable - payment.amountClaimed;
}
/**
* @notice Allows receiver to claim all of their available tokens for a set of payments
* @dev Errors if no tokens are claimable
* @dev It is advised receivers check they are entitled to claim via `claimableBalance` before calling this
* @param payments The payment ids for available token balances
*/
function claimAllAvailableTokens(uint256[] memory payments) external nonReentrant {
for (uint i = 0; i < payments.length; i++) {
uint256 claimableAmount = claimableBalance(payments[i]);
require(claimableAmount > 0, "Payments::claimAllAvailableTokens: claimableAmount is 0");
_claimTokens(payments[i], claimableAmount);
}
}
/**
* @notice Allows receiver to claim a portion of their available tokens for a given payment
* @dev Errors if token amounts provided are > claimable amounts
* @dev It is advised receivers check they are entitled to claim via `claimableBalance` before calling this
* @param payments The payment ids for available token balances
* @param amounts The amount of each available token to claim
*/
function claimAvailableTokenAmounts(uint256[] memory payments, uint256[] memory amounts) external nonReentrant {
require(payments.length == amounts.length, "Payments::claimAvailableTokenAmounts: arrays must be same length");
for (uint i = 0; i < payments.length; i++) {
uint256 claimableAmount = claimableBalance(payments[i]);
require(claimableAmount >= amounts[i], "Payments::claimAvailableTokenAmounts: claimableAmount < amount");
_claimTokens(payments[i], amounts[i]);
}
}
/**
* @notice Allows payer or receiver to stop existing payments for a given paymentId
* @param paymentId The payment id for a payment
* @param stopTime Timestamp to stop payment, if 0 use current block.timestamp
*/
function stopPayment(uint256 paymentId, uint48 stopTime) external nonReentrant {
Payment storage payment = tokenPayments[paymentId];
require(msg.sender == payment.payer || msg.sender == payment.receiver, "Payments::stopPayment: msg.sender must be payer or receiver");
require(payment.stopTime == 0, "Payments::stopPayment: payment already stopped");
stopTime = stopTime == 0 ? uint48(block.timestamp) : stopTime;
require(stopTime < payment.startTime + payment.paymentDurationInSecs, "Payments::stopPayment: stop time > payment duration");
if(stopTime > payment.startTime) {
payment.stopTime = stopTime;
uint256 newPaymentDuration = stopTime - payment.startTime;
uint256 paymentAmountPerSec = payment.amount / payment.paymentDurationInSecs;
uint256 newPaymentAmount = paymentAmountPerSec * newPaymentDuration;
IERC20(payment.token).safeTransfer(payment.payer, payment.amount - newPaymentAmount);
emit PaymentStopped(paymentId, payment.paymentDurationInSecs, stopTime, payment.startTime);
} else {
payment.stopTime = payment.startTime;
IERC20(payment.token).safeTransfer(payment.payer, payment.amount);
emit PaymentStopped(paymentId, payment.paymentDurationInSecs, payment.startTime, payment.startTime);
}
}
/**
* @notice Internal implementation of createPayment
* @param payer The account that is paymenting tokens
* @param receiver The account that will be able to retrieve available tokens
* @param startTime The unix timestamp when the payment period will start
* @param amount The amount of tokens being paid
* @param paymentDurationInSecs The payment period in seconds
* @param cliffDurationInDays The cliff duration in days
*/
function _createPayment(
address token,
address payer,
address receiver,
uint48 startTime,
uint256 amount,
uint256 paymentDurationInSecs,
uint16 cliffDurationInDays
) internal {
// Transfer the tokens under the control of the payment contract
IERC20(token).safeTransferFrom(payer, address(this), amount);
uint48 paymentStartTime = startTime == 0 ? uint48(block.timestamp) : startTime;
// Create payment
Payment memory payment = Payment({
token: token,
receiver: receiver,
payer: payer,
startTime: paymentStartTime,
stopTime: 0,
paymentDurationInSecs: paymentDurationInSecs,
cliffDurationInDays: cliffDurationInDays,
amount: amount,
amountClaimed: 0
});
tokenPayments[numPayments] = payment;
paymentIds[receiver].push(numPayments);
emit PaymentCreated(token, payer, receiver, numPayments, amount, paymentStartTime, paymentDurationInSecs, cliffDurationInDays);
// Increment payment id
numPayments++;
}
/**
* @notice Internal implementation of token claims
* @param paymentId The payment id for claim
* @param claimAmount The amount to claim
*/
function _claimTokens(uint256 paymentId, uint256 claimAmount) internal {
Payment storage payment = tokenPayments[paymentId];
// Update claimed amount
payment.amountClaimed = payment.amountClaimed + claimAmount;
// Release tokens
IERC20(payment.token).safeTransfer(payment.receiver, claimAmount);
emit TokensClaimed(payment.receiver, payment.token, paymentId, claimAmount);
}
}
// 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";
interface IERC20Permit is IERC20 {
function getDomainSeparator() external view returns (bytes32);
function DOMAIN_TYPEHASH() external view returns (bytes32);
function VERSION_HASH() external view returns (bytes32);
function PERMIT_TYPEHASH() external view returns (bytes32);
function nonces(address) external view returns (uint);
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
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
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 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 "../interfaces/IERC20.sol";
import "./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");
}
}
}
|
* @notice Create payment, using permit for approval @dev It is up to the frontend developer to ensure the token implements permit - otherwise this will fail @param token Address of token to payment @param payer The account that is paymenting tokens @param receiver The account that will be able to retrieve available tokens @param startTime The unix timestamp when the payment period will start @param amount The amount of tokens being paid @param paymentDurationInSecs The payment period in seconds @param cliffDurationInDays The payment cliff duration in days @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/ Set approval using permit signature
|
function createPaymentWithPermit(
address token,
address payer,
address receiver,
uint48 startTime,
uint256 amount,
uint256 paymentDurationInSecs,
uint16 cliffDurationInDays,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(paymentDurationInSecs > 0, "Payments::createPaymentWithPermit: payment duration must be > 0");
require(paymentDurationInSecs <= 25*365*SECONDS_PER_DAY, "Payments::createPaymentWithPermit: payment duration more than 25 years");
require(paymentDurationInSecs >= SECONDS_PER_DAY*cliffDurationInDays, "Payments::createPaymentWithPermit: duration < cliff");
require(amount > 0, "Payments::createPaymentWithPermit: amount not > 0");
IERC20Permit(token).permit(payer, address(this), amount, deadline, v, r, s);
_createPayment(token, payer, receiver, startTime, amount, paymentDurationInSecs, cliffDurationInDays);
}
| 12,213,320 |
[
1,
1684,
5184,
16,
1450,
21447,
364,
23556,
225,
2597,
353,
731,
358,
326,
15442,
8751,
358,
3387,
326,
1147,
4792,
21447,
300,
3541,
333,
903,
2321,
225,
1147,
5267,
434,
1147,
358,
5184,
225,
293,
1773,
1021,
2236,
716,
353,
5184,
310,
2430,
225,
5971,
1021,
2236,
716,
903,
506,
7752,
358,
4614,
2319,
2430,
225,
8657,
1021,
9753,
2858,
1347,
326,
5184,
3879,
903,
787,
225,
3844,
1021,
3844,
434,
2430,
3832,
30591,
225,
5184,
5326,
382,
25059,
1021,
5184,
3879,
316,
3974,
225,
927,
3048,
5326,
382,
9384,
1021,
5184,
927,
3048,
3734,
316,
4681,
225,
14096,
1021,
813,
622,
1492,
358,
6930,
326,
3372,
225,
331,
1021,
11044,
1160,
434,
326,
3372,
225,
436,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
225,
272,
670,
6186,
434,
326,
7773,
19748,
3372,
3082,
19,
1000,
23556,
1450,
21447,
3372,
2,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
445,
752,
6032,
1190,
9123,
305,
12,
203,
3639,
1758,
1147,
16,
203,
3639,
1758,
293,
1773,
16,
203,
3639,
1758,
5971,
16,
203,
3639,
2254,
8875,
8657,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
2254,
5034,
5184,
5326,
382,
25059,
16,
203,
3639,
2254,
2313,
927,
3048,
5326,
382,
9384,
16,
203,
3639,
2254,
5034,
14096,
16,
203,
3639,
2254,
28,
331,
16,
7010,
3639,
1731,
1578,
436,
16,
7010,
3639,
1731,
1578,
272,
203,
565,
262,
7010,
3639,
3903,
203,
565,
288,
203,
3639,
2583,
12,
9261,
5326,
382,
25059,
405,
374,
16,
315,
23725,
2866,
2640,
6032,
1190,
9123,
305,
30,
5184,
3734,
1297,
506,
405,
374,
8863,
203,
3639,
2583,
12,
9261,
5326,
382,
25059,
1648,
6969,
14,
5718,
25,
14,
11609,
67,
3194,
67,
10339,
16,
315,
23725,
2866,
2640,
6032,
1190,
9123,
305,
30,
5184,
3734,
1898,
2353,
6969,
11387,
8863,
203,
3639,
2583,
12,
9261,
5326,
382,
25059,
1545,
17209,
67,
3194,
67,
10339,
14,
830,
3048,
5326,
382,
9384,
16,
315,
23725,
2866,
2640,
6032,
1190,
9123,
305,
30,
3734,
411,
927,
3048,
8863,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
23725,
2866,
2640,
6032,
1190,
9123,
305,
30,
3844,
486,
405,
374,
8863,
203,
203,
3639,
467,
654,
39,
3462,
9123,
305,
12,
2316,
2934,
457,
1938,
12,
84,
1773,
16,
1758,
12,
2211,
3631,
3844,
16,
14096,
16,
331,
16,
436,
16,
272,
1769,
203,
3639,
389,
2640,
6032,
12,
2316,
16,
293,
1773,
16,
5971,
16,
8657,
16,
2
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.