file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: MIT
// 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: GPL-3.0
pragma solidity 0.8.7;
interface ILiquidityGauge {
struct Reward {
address token;
address distributor;
uint256 period_finish;
uint256 rate;
uint256 last_update;
uint256 integral;
}
// solhint-disable-next-line
function deposit_reward_token(address _rewardToken, uint256 _amount) external;
// solhint-disable-next-line
function claim_rewards_for(address _user, address _recipient) external;
// // solhint-disable-next-line
// function claim_rewards_for(address _user) external;
// solhint-disable-next-line
function deposit(uint256 _value, address _addr) external;
// solhint-disable-next-line
function reward_tokens(uint256 _i) external view returns(address);
// solhint-disable-next-line
function reward_data(address _tokenReward) external view returns(Reward memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface ILocker {
function createLock(uint256, uint256) external;
function increaseAmount(uint256) external;
function increaseUnlockTime(uint256) external;
function release() external;
function claimRewards(address,address) external;
function claimFXSRewards(address) external;
function execute(
address,
uint256,
bytes calldata
) external returns (bool, bytes memory);
function setGovernance(address) external;
function voteGaugeWeight(address, uint256) external;
function setAngleDepositor(address) external;
function setFxsDepositor(address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface ISdToken {
function setOperator(address _operator) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface ITokenMinter {
function mint(address, uint256) external;
function burn(address, uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/ITokenMinter.sol";
import "../interfaces/ILocker.sol";
import "../interfaces/ISdToken.sol";
import "../interfaces/ILiquidityGauge.sol";
/// @title Contract that accepts tokens and locks them
/// @author StakeDAO
contract Depositor {
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
address public token;
uint256 private constant MAXTIME = 4 * 364 * 86400;
uint256 private constant WEEK = 7 * 86400;
uint256 public lockIncentive = 10; //incentive to users who spend gas to lock token
uint256 public constant FEE_DENOMINATOR = 10000;
address public gauge;
address public governance;
address public immutable locker;
address public immutable minter;
uint256 public incentiveToken = 0;
uint256 public unlockTime;
bool public relock = true;
/* ========== EVENTS ========== */
event Deposited(address indexed caller, address indexed user, uint256 amount, bool lock, bool stake);
event IncentiveReceived(address indexed caller, uint256 amount);
event TokenLocked(address indexed user, uint256 amount);
event GovernanceChanged(address indexed newGovernance);
event SdTokenOperatorChanged(address indexed newSdToken);
event FeesChanged(uint256 newFee);
/* ========== CONSTRUCTOR ========== */
constructor(
address _token,
address _locker,
address _minter
) {
governance = msg.sender;
token = _token;
locker = _locker;
minter = _minter;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/// @notice Set the new governance
/// @param _governance governance address
function setGovernance(address _governance) external {
require(msg.sender == governance, "!auth");
governance = _governance;
emit GovernanceChanged(_governance);
}
/// @notice Set the new operator for minting sdToken
/// @param _operator operator address
function setSdTokenOperator(address _operator) external {
require(msg.sender == governance, "!auth");
ISdToken(minter).setOperator(_operator);
emit SdTokenOperatorChanged(_operator);
}
/// @notice Enable the relock or not
/// @param _relock relock status
function setRelock(bool _relock) external {
require(msg.sender == governance, "!auth");
relock = _relock;
}
/// @notice Set the gauge to deposit token yielded
/// @param _gauge gauge address
function setGauge(address _gauge) external {
require(msg.sender == governance, "!auth");
gauge = _gauge;
}
/// @notice set the fees for locking incentive
/// @param _lockIncentive contract must have tokens to lock
function setFees(uint256 _lockIncentive) external {
require(msg.sender == governance, "!auth");
if (_lockIncentive >= 0 && _lockIncentive <= 30) {
lockIncentive = _lockIncentive;
emit FeesChanged(_lockIncentive);
}
}
/* ========== MUTATIVE FUNCTIONS ========== */
/// @notice Locks the tokens held by the contract
/// @dev The contract must have tokens to lock
function _lockToken() internal {
uint256 tokenBalance = IERC20(token).balanceOf(address(this));
// If there is Token available in the contract transfer it to the locker
if (tokenBalance > 0) {
IERC20(token).safeTransfer(locker, tokenBalance);
emit TokenLocked(msg.sender, tokenBalance);
}
uint256 tokenBalanceStaker = IERC20(token).balanceOf(locker);
// If the locker has no tokens then return
if (tokenBalanceStaker == 0) {
return;
}
ILocker(locker).increaseAmount(tokenBalanceStaker);
if (relock) {
uint256 unlockAt = block.timestamp + MAXTIME;
uint256 unlockInWeeks = (unlockAt / WEEK) * WEEK;
// it means that a 1 week + at least 1 second has been passed
// since last increased unlock time
if (unlockInWeeks - unlockTime > 1) {
ILocker(locker).increaseUnlockTime(unlockAt);
unlockTime = unlockInWeeks;
}
}
}
/// @notice Lock tokens held by the contract
/// @dev The contract must have Token to lock
function lockToken() external {
_lockToken();
// If there is incentive available give it to the user calling lockToken
if (incentiveToken > 0) {
ITokenMinter(minter).mint(msg.sender, incentiveToken);
emit IncentiveReceived(msg.sender, incentiveToken);
incentiveToken = 0;
}
}
/// @notice Deposit & Lock Token
/// @dev User needs to approve the contract to transfer the token
/// @param _amount The amount of token to deposit
/// @param _lock Whether to lock the token
/// @param _stake Whether to stake the token
/// @param _user User to deposit for
function deposit(
uint256 _amount,
bool _lock,
bool _stake,
address _user
) public {
require(_amount > 0, "!>0");
require(_user != address(0), "!user");
// If User chooses to lock Token
if (_lock) {
IERC20(token).safeTransferFrom(msg.sender, locker, _amount);
_lockToken();
if (incentiveToken > 0) {
_amount = _amount + incentiveToken;
emit IncentiveReceived(msg.sender, incentiveToken);
incentiveToken = 0;
}
} else {
//move tokens here
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
//defer lock cost to another user
uint256 callIncentive = (_amount * lockIncentive) / FEE_DENOMINATOR;
_amount = _amount - callIncentive;
incentiveToken = incentiveToken + callIncentive;
}
if (_stake && gauge != address(0)) {
ITokenMinter(minter).mint(address(this), _amount);
IERC20(minter).safeApprove(gauge, 0);
IERC20(minter).safeApprove(gauge, _amount);
ILiquidityGauge(gauge).deposit(_amount, _user);
} else {
ITokenMinter(minter).mint(_user, _amount);
}
emit Deposited(msg.sender, _user, _amount, _lock, _stake);
}
/// @notice Deposits all the token of a user & locks them based on the options choosen
/// @dev User needs to approve the contract to transfer Token tokens
/// @param _lock Whether to lock the token
/// @param _stake Whether to stake the token
/// @param _user User to deposit for
function depositAll(
bool _lock,
bool _stake,
address _user
) external {
uint256 tokenBal = IERC20(token).balanceOf(msg.sender);
deposit(tokenBal, _lock, _stake, _user);
}
}
|
Set the new operator for minting sdToken _operator operator address
|
function setSdTokenOperator(address _operator) external {
require(msg.sender == governance, "!auth");
ISdToken(minter).setOperator(_operator);
emit SdTokenOperatorChanged(_operator);
}
| 1,563,676 |
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view 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 { }
}
// File: contracts/interfaces/IMigratorChef.sol
pragma solidity 0.6.12;
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to SakeSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// SakeSwap must mint EXACTLY the same amount of SakeSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: contracts/SakeToken.sol
pragma solidity 0.6.12;
// SakeToken with Governance.
contract SakeToken is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name = "SakeToken";
string private _symbol = "SAKE";
uint8 private _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);
_moveDelegates(_delegates[sender], _delegates[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 is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev 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 { }
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (SakeMaster).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 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 Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SAKE::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SAKE::delegateBySig: invalid nonce");
require(now <= expiry, "SAKE::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 (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "SAKE::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];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SAKEs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "SAKE::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/SakeMaster.sol
pragma solidity 0.6.12;
// SakeMaster is the master of Sake. He can make Sake and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SAKE is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract SakeMaster is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
// File: contracts/interfaces/IStakingRewards.sol
pragma solidity 0.6.12;
// Uniswap Liquidity Mining
interface IStakingRewards {
function earned(address account) external view returns (uint256);
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
function balanceOf(address account) external view returns (uint256);
}
// File: contracts/SakeUniV2.sol
pragma solidity 0.6.12;
contract SakeUniV2 is Ownable, ERC20("Wrapped UniSwap Liquidity Token", "WULP") {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 sakeRewardDebt; // Sake reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
uint256 uniRewardDebt; // similar with sakeRewardDebt
uint256 firstDepositTime;
}
// Info of each user that stakes LP tokens.
mapping(address => UserInfo) public userInfo;
IStakingRewards public uniStaking;
uint256 public lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 public accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
uint256 public accUniPerShare; // Accumulated UNIs per share, times 1e12. See below.
// The UNI Token.
IERC20 public uniToken;
// The SAKE TOKEN!
SakeToken public sake;
SakeMaster public sakeMaster;
IERC20 public lpToken; // Address of LP token contract.
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// The address to receive UNI token fee.
address public uniTokenFeeReceiver;
// The ratio of UNI token fee (10%).
uint8 public uniFeeRatio = 10;
uint8 public isMigrateComplete = 0;
//Liquidity Event
event EmergencyWithdraw(address indexed user, uint256 amount);
event Deposit(address indexed user, uint256 amount);
event Withdraw(address indexed user, uint256 amount);
constructor(
SakeMaster _sakeMaster,
address _uniLpToken,
address _uniStaking,
address _uniToken,
SakeToken _sake,
address _uniTokenFeeReceiver
) public {
sakeMaster = _sakeMaster;
uniStaking = IStakingRewards(_uniStaking);
uniToken = IERC20(_uniToken);
sake = _sake;
uniTokenFeeReceiver = _uniTokenFeeReceiver;
lpToken = IERC20(_uniLpToken);
}
////////////////////////////////////////////////////////////////////
//Migrate liquidity to sakeswap
///////////////////////////////////////////////////////////////////
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
function migrate() public onlyOwner {
require(address(migrator) != address(0), "migrate: no migrator");
updatePool();
//get all lp and uni reward from uniStaking
uniStaking.withdraw(totalSupply());
//get all wrapped lp and sake reward from sakeMaster
uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1);
sakeMaster.withdraw(poolIdInSakeMaster, totalSupply());
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
lpToken = newLpToken;
isMigrateComplete = 1;
}
// View function to see pending SAKEs and UNIs on frontend.
function pending(address _user) external view returns (uint256 _sake, uint256 _uni) {
UserInfo storage user = userInfo[_user];
uint256 tempAccSakePerShare = accSakePerShare;
uint256 tempAccUniPerShare = accUniPerShare;
if (isMigrateComplete == 0 && block.number > lastRewardBlock && totalSupply() != 0) {
uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1);
uint256 sakeReward = sakeMaster.pendingSake(poolIdInSakeMaster, address(this));
tempAccSakePerShare = tempAccSakePerShare.add(sakeReward.mul(1e12).div(totalSupply()));
uint256 uniReward = uniStaking.earned(address(this));
tempAccUniPerShare = tempAccUniPerShare.add(uniReward.mul(1e12).div(totalSupply()));
}
_sake = user.amount.mul(tempAccSakePerShare).div(1e12).sub(user.sakeRewardDebt);
_uni = user.amount.mul(tempAccUniPerShare).div(1e12).sub(user.uniRewardDebt);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool() public {
if (block.number <= lastRewardBlock || isMigrateComplete == 1) {
return;
}
if (totalSupply() == 0) {
lastRewardBlock = block.number;
return;
}
uint256 sakeBalance = sake.balanceOf(address(this));
uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1);
// Get Sake Reward from SakeMaster
sakeMaster.deposit(poolIdInSakeMaster, 0);
uint256 sakeReward = sake.balanceOf(address(this)).sub(sakeBalance);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div((totalSupply())));
uint256 uniReward = uniStaking.earned(address(this));
uniStaking.getReward();
accUniPerShare = accUniPerShare.add(uniReward.mul(1e12).div(totalSupply()));
lastRewardBlock = block.number;
}
function _mintWulp(address _addr, uint256 _amount) internal {
lpToken.safeTransferFrom(_addr, address(this), _amount);
_mint(address(this), _amount);
}
function _burnWulp(address _to, uint256 _amount) internal {
lpToken.safeTransfer(address(_to), _amount);
_burn(address(this), _amount);
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _amount) public {
require(isMigrateComplete == 0 || (isMigrateComplete == 1 && _amount == 0), "already migrate");
UserInfo storage user = userInfo[msg.sender];
updatePool();
if (_amount > 0 && user.firstDepositTime == 0) user.firstDepositTime = block.number;
uint256 pendingSake = user.amount.mul(accSakePerShare).div(1e12).sub(user.sakeRewardDebt);
uint256 pendingUni = user.amount.mul(accUniPerShare).div(1e12).sub(user.uniRewardDebt);
user.amount = user.amount.add(_amount);
user.sakeRewardDebt = user.amount.mul(accSakePerShare).div(1e12);
user.uniRewardDebt = user.amount.mul(accUniPerShare).div(1e12);
if (pendingSake > 0) _safeSakeTransfer(msg.sender, pendingSake);
if (pendingUni > 0) {
uint256 uniFee = pendingUni.mul(uniFeeRatio).div(100);
uint256 uniToUser = pendingUni.sub(uniFee);
_safeUniTransfer(uniTokenFeeReceiver, uniFee);
_safeUniTransfer(msg.sender, uniToUser);
}
if (_amount > 0) {
//generate wrapped uniswap lp token
_mintWulp(msg.sender, _amount);
//approve and stake to uniswap
lpToken.approve(address(uniStaking), _amount);
uniStaking.stake(_amount);
//approve and stake to sakemaster
_approve(address(this), address(sakeMaster), _amount);
uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1);
sakeMaster.deposit(poolIdInSakeMaster, _amount);
}
emit Deposit(msg.sender, _amount);
}
// Withdraw LP tokens from SakeUni.
function withdraw(uint256 _amount) public {
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool();
uint256 pendingSake = user.amount.mul(accSakePerShare).div(1e12).sub(user.sakeRewardDebt);
uint256 pendingUni = user.amount.mul(accUniPerShare).div(1e12).sub(user.uniRewardDebt);
user.amount = user.amount.sub(_amount);
user.sakeRewardDebt = user.amount.mul(accSakePerShare).div(1e12);
user.uniRewardDebt = user.amount.mul(accUniPerShare).div(1e12);
if (pendingSake > 0) _safeSakeTransfer(msg.sender, pendingSake);
if (pendingUni > 0) {
uint256 uniFee = pendingUni.mul(uniFeeRatio).div(100);
uint256 uniToUser = pendingUni.sub(uniFee);
_safeUniTransfer(uniTokenFeeReceiver, uniFee);
_safeUniTransfer(msg.sender, uniToUser);
}
if (_amount > 0) {
if (isMigrateComplete == 0) {
uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1);
//unstake wrapped lp token from sake master
sakeMaster.withdraw(poolIdInSakeMaster, _amount);
//unstake uniswap lp token from uniswap
uniStaking.withdraw(_amount);
}
_burnWulp(address(msg.sender), _amount);
}
emit Withdraw(msg.sender, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() public {
UserInfo storage user = userInfo[msg.sender];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.sakeRewardDebt = 0;
user.uniRewardDebt = 0;
{
if (isMigrateComplete == 0) {
uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1);
//unstake wrapped lp token from sake master
sakeMaster.withdraw(poolIdInSakeMaster, _amount);
//unstake lp token from uniswap
uniStaking.withdraw(_amount);
}
_burnWulp(address(msg.sender), _amount);
}
emit EmergencyWithdraw(msg.sender, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function _safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Safe uni transfer function
function _safeUniTransfer(address _to, uint256 _amount) internal {
uint256 uniBal = uniToken.balanceOf(address(this));
if (_amount > uniBal) {
uniToken.transfer(_to, uniBal);
} else {
uniToken.transfer(_to, _amount);
}
}
function setUniTokenFeeReceiver(address _uniTokenFeeReceiver) public onlyOwner {
uniTokenFeeReceiver = _uniTokenFeeReceiver;
}
}
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool() public {
if (block.number <= lastRewardBlock || isMigrateComplete == 1) {
return;
}
if (totalSupply() == 0) {
lastRewardBlock = block.number;
return;
}
uint256 sakeBalance = sake.balanceOf(address(this));
uint256 poolIdInSakeMaster = sakeMaster.lpTokenPID(address(this)).sub(1);
uint256 sakeReward = sake.balanceOf(address(this)).sub(sakeBalance);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div((totalSupply())));
uint256 uniReward = uniStaking.earned(address(this));
uniStaking.getReward();
accUniPerShare = accUniPerShare.add(uniReward.mul(1e12).div(totalSupply()));
lastRewardBlock = block.number;
}
| 7,777,372 |
./partial_match/3/0x7c1051042268Ac634aEE7429180fe08CE253D4E0/sources/Creature.sol
|
function mintTo(address _to, uint256 _numOfTokens) public onlyOwner {
|
function mintTo(address _to, uint256 _numOfTokens) public {
for (uint256 i = 0; i < _numOfTokens; i++) {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
}
| 5,310,692 |
./full_match/5/0x1f85B789655fB4c3CEB448C2733B6b1e387867E0/sources/project_/contracts/extensions/TokenExtension.sol
|
The ERC1820 interface label the extension will be registered as in the ERC1820 registry/
|
function interfaceLabel() external view override returns (string memory) {
return _interfaceLabel;
}
| 11,602,557 |
pragma solidity 0.5.17;
import "./ERC721Token.sol";
import "./ERC20Interface.sol";
import "./Freezable.sol";
/**
* @title Base ERC721 token
* @author Prashant Prabhakar Singh [[email protected]]
* This contract implements basic ERC721 token functionality with bulk functionalities
*/
contract BaseERC721 is ERC721Token, Freezable {
constructor(string memory name, string memory symbol, string memory _baseTokenURI) public ERC721Token(name, symbol){
baseTokenURI = _baseTokenURI;
}
/**
* @dev Updates the base URL of token
* Reverts if the sender is not owner
* @param _newURI New base URL
*/
function updateBaseTokenURI(string memory _newURI)
public
onlyOwner
noEmergencyFreeze
{
baseTokenURI = _newURI;
}
/**
* @dev Mints new token on blockchain
* Reverts if the sender is not operator with level 1
* @param _id Id of NFT to be minted
* @dev URI is not provided because URI will be deducted based on baseURL
*/
function mint(uint256 _id, address _to)
public
onlyDeputyOrOwner
noEmergencyFreeze
returns (bool)
{
super._mint(_to, _id);
return true;
}
function bulkMint(uint[] memory _ids, address[] memory _users)
public
onlyDeputyOrOwner
noEmergencyFreeze
returns (bool)
{
require(_ids.length == _users.length, "Invalid params");
for(uint i=0; i<_ids.length; i++) {
super._mint(_users[i], _ids[i]);
}
return true;
}
/**
* @dev Transfer tokens (similar to ERC-20 transfer)
* Reverts if the sender is not owner of the NFT or approved
* @param _to address to which token is transferred
* @param _tokenId Id of NFT being transferred
*/
function transfer(address _to, uint256 _tokenId)
public
noEmergencyFreeze
returns (bool)
{
safeTransferFrom(msg.sender, _to, _tokenId);
return true;
}
/**
* @dev Burn an existing NFT
* @param _id Id of NFT to be burned
*/
function burn(uint _id)
public
noEmergencyFreeze
returns (bool)
{
super._burn(msg.sender, _id);
return true;
}
//////////////////////////////////////////
// PUBLICLY ACCESSIBLE METHODS (CONSTANT)
//////////////////////////////////////////
}
|
Burn an existing NFT _id Id of NFT to be burned/
|
function burn(uint _id)
public
noEmergencyFreeze
returns (bool)
{
super._burn(msg.sender, _id);
return true;
}
| 1,529,739 |
pragma solidity ^0.5.7;
/// @title DaiDaddy 2.0: Pay back your debt by unwinding your CDP
/// @author Chris Maree
import "./SaiTubInterface.sol";
import "./MedianizerInterface.sol";
import "./KyberNetworkProxyInterface.sol";
import "./ERC20Interface.sol";
contract Unwinder {
// constants
uint256 SAFE_NO_LIQUIDATION_RATE = 151 * 10**16; // a value of 1.51, just above the liquidation amount of a CDP
// contract instances for unwinding and trading
SaiTub public saiTubContract;
Medianizer public medianizerContract;
KyberNetworkProxy public kyberNetworkProxyContract;
ERC20 public daiContract;
ERC20 public wethContract;
ERC20 public dSToken;
ERC20 public mkrToken;
// state variables
mapping(address => bytes32) public cupOwners; // prove that you owned the CDP before transfering it to DaiDaddy
address daiDaddyFeeCollector;
struct Cup {
address lad; // CDP owner
uint256 ink; // Locked collateral (in SKR)
uint256 art; // Outstanding normalised debt (tax only)
uint256 ire; // Outstanding normalised debt
}
constructor(
address _saiTubAddress,
address _medianizerAddress,
address _kyberNetworkProxyAddress,
address _daiTokenAddress,
address _wethTokenAddress,
address _daiDaddyFeeCollector,
address _dSToken,
address _mkrToken
) public {
saiTubContract = SaiTub(_saiTubAddress);
medianizerContract = Medianizer(_medianizerAddress);
kyberNetworkProxyContract = KyberNetworkProxy(
_kyberNetworkProxyAddress
);
daiContract = ERC20(_daiTokenAddress);
wethContract = ERC20(_wethTokenAddress);
dSToken = ERC20(_dSToken);
mkrToken = ERC20(_mkrToken);
daiDaddyFeeCollector = _daiDaddyFeeCollector;
require(
daiContract.approve(address(kyberNetworkProxyContract), 10**26),
"Token approve did not complete successfully"
);
require(
daiContract.approve(address(saiTubContract), 10**26),
"Token approve did not complete successfully"
);
require(
wethContract.approve(address(kyberNetworkProxyContract), 10**26),
"Token approve did not complete successfully"
);
require(
dSToken.approve(address(saiTubContract), 10**26),
"Token approve did not complete successfully"
);
require(
mkrToken.approve(address(saiTubContract), 10**26),
"Token approve did not complete successfully"
);
}
// round number a to b decimal points
function ceil(uint256 a, uint256 m) public pure returns (uint256) {
return ((a + m - 1) / m) * m;
}
// takes in all the information about a CDP and returns the current collateralization ratio scaled *10 ^ 18
// uint256 ink Locked collateral (in Weth)
// uint256 art Outstanding normalised debt(including tax)
// uint256 etherPrice Current ether Price
// uint256 wpRatio Weth to Peth Ratio
function collateralizationRatio(
uint256 ink,
uint256 art,
uint256 etherPrice,
uint256 wpRatio
) public pure returns (uint256) {
uint256 cr = (ink * etherPrice * wpRatio) / (art * 10**18);
return cr;
}
// returns an interger representing how many unwinds are needed for a given collateralization ratio. The use of
// the ceil function and the scaling is to act as a round up
function unwindsNeeded(uint256 cr) public pure returns (uint256) {
//1.5 here represents the collateralization ratio needed to not get liquidated as a CDP on makerDao
uint256 repaymentsNeeded = (1 * 10**(18 * 2)) / (cr - 1.5 * 10**18);
return ceil(repaymentsNeeded / (10**14), 10000) / 10000;
}
function freeableCollateralEth(
uint256 ink,
uint256 art,
uint256 etherPrice,
uint256 wpRatio
) public view returns (uint256) {
return
(ink * wpRatio) /
(10**18) -
(art * SAFE_NO_LIQUIDATION_RATE) /
etherPrice;
}
function freeableCollateralWeth(
uint256 ink,
uint256 art,
uint256 etherPrice
) public view returns (uint256) {
if (art == 0) return ink; //if there is no debt then all ink is freeable
return ink - (art * SAFE_NO_LIQUIDATION_RATE) / etherPrice;
}
// called at step 1 to show DaiDaddy that you own the CDP.
function proveOwnershipOfCDP(bytes32 _cup) public {
(address lad, , , ) = saiTubContract.cups(_cup);
require(
lad == msg.sender,
"Only the current owner of the cup can prove ownership"
);
cupOwners[msg.sender] = _cup;
}
// See how much Dai can be gained from trading against keyber for the freed Ether
function ethToDaiKyberPrice(uint256 _etherToSell)
public
view
returns (uint256 expectedRate, uint256 slippageRate)
{
(expectedRate, slippageRate) = kyberNetworkProxyContract
.getExpectedRate(wethContract, daiContract, _etherToSell);
}
// Exchange x amount of weth for dai at the best price.
function swapWethToDai(uint256 _srcQty) public returns (uint256) {
require(
wethContract.balanceOf(address(this)) >= _srcQty,
"Does not have enough weth to make exchange"
);
uint256 _minConversionRate;
address _destAddress = address(this);
uint256 _maxDestAmount = 10**26; // 1 billion of the dest token.
ERC20 _srcToken = wethContract;
ERC20 _destToken = daiContract;
// Get the minimum conversion rate
(_minConversionRate, ) = kyberNetworkProxyContract.getExpectedRate(
_srcToken,
_destToken,
_srcQty
);
// Swap the ERC20 token and send to _destAddress
return
kyberNetworkProxyContract.trade(
_srcToken, //_srcToken source token contract address
_srcQty, //_srcQty amount of source tokens
_destToken, //_destToken destination token contract address
_destAddress, //_destAddress address to send swapped tokens to
_maxDestAmount, //_maxDestAmount address to send swapped tokens to
_minConversionRate, //bottom end rate that if below trade will revert
daiDaddyFeeCollector //walletId for fee sharing program
);
}
// free the maximum amount of ether possible from the CDP without liquidating it
function drawMaxWethFromCDP(bytes32 _cup) public returns (uint256) {
// get cup info
(, uint256 ink, uint256 art, ) = saiTubContract.cups(_cup);
// calculate how much ether can be freed from the cup
uint256 freeableWeth = freeableCollateralWeth(
ink,
art,
getEtherPrice());
// free peth from cdp
saiTubContract.free(_cup, freeableWeth);
//convert peth to Weth //this should include the wpratio...
saiTubContract.exit(freeableWeth);
return freeableWeth;
}
function getEtherPrice() public view returns (uint256) {
return uint256(medianizerContract.read());
}
//the per value stores the weth to peth ratio in the maker contracts.
//this is scaled by 10^27 so by devided by 10^9 get ouput wp ratio *10^18
function getWpRatio() public view returns (uint256) {
return saiTubContract.per() / (10**9);
}
function giveCDPBack(bytes32 _cup) public {
require(cupOwners[msg.sender] == _cup, "Cant send back a cup you down own");
saiTubContract.give(_cup, msg.sender);
}
function unwindCDP(bytes32 _cup) public {
(address lad, uint256 ink, uint256 art, uint256 ire) = saiTubContract
.cups(_cup);
require(
lad == address(this),
"Can only unwind CDPs that have been transfered to the Unwinder"
);
require(
cupOwners[msg.sender] == _cup,
"Can only unwind CDPs that were owned by the seller"
);
uint256 freedWeth = drawMaxWethFromCDP(_cup);
(uint256 expectedRate, uint256 slippageRate) = ethToDaiKyberPrice(
freedWeth
);
//the free collateral is more than enough to pay off debt in one go.
//use the slippage rate to make sure we get enough dai to pay off the debt. This can be
// further optomized into the future
if ((freedWeth * slippageRate) / (10**18) > art) {
uint256 etherNeededToSend = (art * 10**18) / slippageRate;
uint256 daiReceived = swapWethToDai(etherNeededToSend);
require(
daiReceived >= art,
"Not enough dai received to wipe all debt"
);
saiTubContract.wipe(_cup, art);
//get the debt and check it is all been wiped
(, uint256 inkEnd, uint256 artEnd, ) = saiTubContract.cups(_cup);
require(artEnd == 0, "Not all debt has been wiped");
// draw out the remaining ether
saiTubContract.free(_cup, inkEnd);
//convert peth to Weth //this should include the wpratio...
saiTubContract.exit(inkEnd);
// send all remaining eth and weth to sender.
require(
daiContract.transfer(
msg.sender,
daiContract.balanceOf(address(this))
),
"Dai transfer tailed"
);
require(
wethContract.transfer(
msg.sender,
wethContract.balanceOf(address(this))
),
"Weth transfer failed"
);
}
}
}
|
the per value stores the weth to peth ratio in the maker contracts.this is scaled by 10^27 so by devided by 10^9 get ouput wp ratio 10^18
|
function getWpRatio() public view returns (uint256) {
return saiTubContract.per() / (10**9);
}
| 6,455,179 |
./full_match/42161/0x9C3557204b93Ef8f050Ac748bba953249E801d10/sources/src/Airdrop.sol
|
_token ERC20 token to airdrop _recipients list of recipients _amounts list of amounts to send each recipient _total total amount to transfer from caller/ bytes selector for transferFrom(address,address,uint256) bytes selector for transfer(address,uint256) store transferFrom selector store caller address store address store _total call transferFrom for _total revert if call fails loop through _recipients increment i store offset for _amounts[i] store _amounts[i] store _recipients[i] store _recipients[i] in transferData store _amounts[i] in transferData call transfer for _amounts[i] to _recipients[i] revert if call fails
|
function airdropERC20(
IERC20 _token,
address[] calldata _recipients,
uint256[] calldata _amounts,
uint256 _total
) external {
bytes4 transferFrom = 0x23b872dd;
bytes4 transfer = 0xa9059cbb;
assembly {
let transferFromData := add(0x20, mload(0x40))
mstore(transferFromData, transferFrom)
mstore(add(transferFromData, 0x04), caller())
mstore(add(transferFromData, 0x24), address())
mstore(add(transferFromData, 0x44), _total)
let successTransferFrom := call(
gas(),
_token,
0,
transferFromData,
0x64,
0,
0
)
if iszero(successTransferFrom) {
revert(0, 0)
}
mstore(transferData, transfer)
for {
let i := 0
i := add(i, 1)
let offset := mul(i, 0x20)
let amt := calldataload(add(_amounts.offset, offset))
let recp := calldataload(add(_recipients.offset, offset))
mstore(
add(transferData, 0x04),
recp
)
mstore(
add(transferData, 0x24),
amt
)
let successTransfer := call(
gas(),
_token,
0,
transferData,
0x44,
0,
0
)
if iszero(successTransfer) {
revert(0, 0)
}
}
}
}
| 16,309,019 |
/*
Copyright 2018 CoinAlpha, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.21;
import "./zeppelin/SafeMath.sol";
import "./zeppelin/ERC20.sol";
import "./BasketRegistry.sol";
/// @title BasketEscrow -- Escrow contract to facilitate trading
/// @author CoinAlpha, Inc. <[email protected]>
contract BasketEscrow {
using SafeMath for uint;
// Constants set at contract inception
address public admin;
address public transactionFeeRecipient;
uint public transactionFee;
uint public FEE_DECIMALS;
uint public orderIndex;
address public basketRegistryAddress;
address public ETH_ADDRESS;
// mapping of token addresses to mapping of account balances (token=0 means Ether)
// ADDRESS USER || ADDRESS TOKEN || UINT BALANCE
mapping(address => mapping(address => uint)) public balances;
// mapping of user accounts to mapping of order hashes to orderIndex (equivalent to offchain signature)
// ADDRESS USER || ORDER HASH || uint
mapping(address => mapping(bytes32 => uint)) public orders;
// mapping of user accounts to mapping of order hashes to booleans (true = order has been filled)
// ADDRESS USER || ORDER HASH || BOOL
mapping(address => mapping(bytes32 => bool)) public filledOrders;
mapping(uint => Order) public orderMap; // Used to lookup existing orders
// Modules
IBasketRegistry public basketRegistry;
// Structs
struct Order {
address orderCreator;
address tokenGet;
uint amountGet;
address tokenGive;
uint amountGive;
uint expiration;
uint nonce;
}
// Modifiers
modifier onlyAdmin {
require(msg.sender == admin); // Check: "Only the admin can call this function"
_;
}
// Events
event LogBuyOrderCreated(uint newOrderIndex, address indexed buyer, address basket, uint amountEth, uint amountBasket, uint expiration, uint nonce);
event LogSellOrderCreated(uint newOrderIndex, address indexed seller, address basket, uint amountEth, uint amountBasket, uint expiration, uint nonce);
event LogBuyOrderCancelled(uint cancelledOrderIndex, address indexed buyer, address basket, uint amountEth, uint amountBasket);
event LogSellOrderCancelled(uint cancelledOrderIndex, address indexed seller, address basket, uint amountEth, uint amountBasket);
event LogBuyOrderFilled(uint filledOrderIndex, address indexed buyOrderFiller, address indexed orderCreator, address basket, uint amountEth, uint amountBasket);
event LogSellOrderFilled(uint filledOrderIndex, address indexed sellOrderFiller, address indexed orderCreator, address basket, uint amountEth, uint amountBasket);
event LogTransactionFeeRecipientChange(address oldRecipient, address newRecipient);
event LogTransactionFeeChange(uint oldFee, uint newFee);
/// @dev BasketEscrow constructor
/// @param _basketRegistryAddress Address of basket registry
/// @param _transactionFeeRecipient Address to send transactionFee
/// @param _transactionFee Transaction fee in ETH percentage
function BasketEscrow(
address _basketRegistryAddress,
address _transactionFeeRecipient,
uint _transactionFee
) public {
basketRegistryAddress = _basketRegistryAddress;
basketRegistry = IBasketRegistry(_basketRegistryAddress);
ETH_ADDRESS = 0; // Use address 0 to indicate Eth
orderIndex = 1; // Initialize order index at 1
admin = msg.sender; // record admin
transactionFeeRecipient = _transactionFeeRecipient;
transactionFee = _transactionFee;
FEE_DECIMALS = 18;
}
/// @dev Create an order to buy baskets with ETH
/// @param _basketAddress Address of basket to purchase
/// @param _amountBasket Amount of baskets to purchase
/// @param _expiration Unix timestamp
/// @param _nonce Random number to generate unique order hash
/// @return success Operation successful
function createBuyOrder(
address _basketAddress,
uint _amountBasket,
uint _expiration,
uint _nonce
) public payable returns (bool success) {
uint index = _createOrder(msg.sender, _basketAddress, _amountBasket, ETH_ADDRESS, msg.value, _expiration, _nonce);
emit LogBuyOrderCreated(index, msg.sender, _basketAddress, msg.value, _amountBasket, _expiration, _nonce);
return true;
}
/// @dev Create an order to sell baskets for ETH NOTE: REQUIRES TOKEN APPROVAL
/// @param _basketAddress Address of basket to sell
/// @param _amountBasket Amount of baskets to sell
/// @param _amountEth Amount of ETH to receive in exchange
/// @param _expiration Unix timestamp
/// @param _nonce Random number to generate unique order hash
/// @return success Operation successful
function createSellOrder(
address _basketAddress,
uint _amountBasket,
uint _amountEth,
uint _expiration,
uint _nonce
)
public
returns (bool success)
{
ERC20(_basketAddress).transferFrom(msg.sender, this, _amountBasket);
uint index = _createOrder(msg.sender, ETH_ADDRESS, _amountEth, _basketAddress, _amountBasket, _expiration, _nonce);
emit LogSellOrderCreated(index, msg.sender, _basketAddress, _amountEth, _amountBasket, _expiration, _nonce);
return true;
}
/// @dev Contract internal function to record submitted orders
/// @param _orderCreator Address of the order's creator
/// @param _tokenGet Address of token/ETH to receive
/// @param _amountGet Amount of token/ETH to receive
/// @param _tokenGive Address of token/ETH to give
/// @param _amountGive Amount of token/ETH to give
/// @param _expiration Unix timestamp
/// @param _nonce Random number to generate unique order hash
/// @return newOrderIndex
function _createOrder(
address _orderCreator,
address _tokenGet,
uint _amountGet,
address _tokenGive,
uint _amountGive,
uint _expiration,
uint _nonce
)
internal
returns (uint newOrderIndex)
{
require(_expiration > now);
require(_tokenGet == ETH_ADDRESS || basketRegistry.checkBasketExists(_tokenGet)); // Check: "Order not for ETH or invalid basket"
require(_tokenGive == ETH_ADDRESS || basketRegistry.checkBasketExists(_tokenGive)); // Check: "Order not for ETH or invalid basket"
bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expiration, _nonce);
require(orders[_orderCreator][hash] == 0); // Check: "Duplicate order"
orders[_orderCreator][hash] = orderIndex;
balances[_orderCreator][_tokenGive] = balances[_orderCreator][_tokenGive].add(_amountGive);
orderMap[orderIndex] = Order(_orderCreator, _tokenGet, _amountGet, _tokenGive, _amountGive, _expiration, _nonce);
orderIndex = orderIndex.add(1);
return orderIndex.sub(1);
}
/// @dev Cancel an existing buy order
/// @param _basketAddress Address of basket to purchase in original order
/// @param _amountBasket Amount of baskets to purchase in original order
/// @param _amountEth Amount of ETH sent in original order
/// @param _expiration Unix timestamp in original order
/// @param _nonce Random number in original order
/// @return success Operation successful
function cancelBuyOrder(
address _basketAddress,
uint _amountBasket,
uint _amountEth,
uint _expiration,
uint _nonce
) public returns (bool success) {
uint cancelledOrderIndex = _cancelOrder(msg.sender, _basketAddress, _amountBasket, ETH_ADDRESS, _amountEth, _expiration, _nonce);
if (now >= _expiration) {
msg.sender.transfer(_amountEth); // if order has expired, no transaction fee is charged
} else {
uint fee = _amountEth.mul(transactionFee).div(10 ** FEE_DECIMALS);
msg.sender.transfer(_amountEth.sub(fee));
transactionFeeRecipient.transfer(fee);
}
emit LogBuyOrderCancelled(cancelledOrderIndex, msg.sender, _basketAddress, _amountEth, _amountBasket);
return true;
}
/// @dev Cancel an existing sell order
/// @param _basketAddress Address of basket to sell in original order
/// @param _amountBasket Amount of baskets to sell in original order
/// @param _amountEth Amount of ETH to receive in original order
/// @param _expiration Unix timestamp in original order
/// @param _nonce Random number in original order
/// @return success Operation successful
function cancelSellOrder(
address _basketAddress,
uint _amountBasket,
uint _amountEth,
uint _expiration,
uint _nonce
) public returns (bool success) {
uint cancelledOrderIndex = _cancelOrder(msg.sender, ETH_ADDRESS, _amountEth, _basketAddress, _amountBasket, _expiration, _nonce);
ERC20(_basketAddress).transfer(msg.sender, _amountBasket);
emit LogSellOrderCancelled(cancelledOrderIndex, msg.sender, _basketAddress, _amountEth, _amountBasket);
return true;
}
/// @dev Contract internal function to cancel an existing order
/// @param _orderCreator Address of the original order's creator
/// @param _tokenGet Address of token/ETH to receive in original order
/// @param _amountGet Amount of token/ETH to receive in original order
/// @param _tokenGive Address of token/ETH to give in original order
/// @param _amountGive Amount of token/ETH to give in original order
/// @param _expiration Unix timestamp in original order
/// @param _nonce Random number in original order
/// @return cancelledOrderIndex Index of cancelled order
function _cancelOrder(
address _orderCreator,
address _tokenGet,
uint _amountGet,
address _tokenGive,
uint _amountGive,
uint _expiration,
uint _nonce
)
internal
returns (uint index)
{
bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expiration, _nonce);
uint cancelledOrderIndex = orders[_orderCreator][hash];
require(cancelledOrderIndex > 0); // Check: "Order does not exist"
require(filledOrders[_orderCreator][hash] != true); // Check: "Order has been filled"
orders[_orderCreator][hash] = 0;
balances[_orderCreator][_tokenGive] = balances[_orderCreator][_tokenGive].sub(_amountGive);
return cancelledOrderIndex;
}
/// @dev Fill an existing buy order NOTE: REQUIRES TOKEN APPROVAL
/// @param _orderCreator Address of order's creator
/// @param _basketAddress Address of basket to purchase in original order
/// @param _amountBasket Amount of baskets to purchase in original order
/// @param _amountEth Amount of ETH to sent in original order
/// @param _expiration Unix timestamp in original order
/// @param _nonce Random number in original order
/// @return success Operation successful
function fillBuyOrder(
address _orderCreator,
address _basketAddress,
uint _amountBasket,
uint _amountEth,
uint _expiration,
uint _nonce
) public returns (bool success) {
uint filledOrderIndex = _fillOrder(_orderCreator, _basketAddress, _amountBasket, ETH_ADDRESS, _amountEth, _expiration, _nonce);
ERC20(_basketAddress).transferFrom(msg.sender, _orderCreator, _amountBasket);
uint fee = _amountEth.mul(transactionFee).div(10 ** FEE_DECIMALS);
msg.sender.transfer(_amountEth.sub(fee));
transactionFeeRecipient.transfer(fee);
emit LogBuyOrderFilled(filledOrderIndex, msg.sender, _orderCreator, _basketAddress, _amountEth, _amountBasket);
return true;
}
/// @dev Fill an existing sell order
/// @param _orderCreator Address of order's creator
/// @param _basketAddress Address of basket to sell in original order
/// @param _amountBasket Amount of baskets to sell in original order
/// @param _expiration Unix timestamp in original order
/// @param _nonce Random number in original order
/// @return success Operation successful
function fillSellOrder(
address _orderCreator,
address _basketAddress,
uint _amountBasket,
uint _expiration,
uint _nonce
) public payable returns (bool success) {
uint filledOrderIndex = _fillOrder(_orderCreator, ETH_ADDRESS, msg.value, _basketAddress, _amountBasket, _expiration, _nonce);
ERC20(_basketAddress).transfer(msg.sender, _amountBasket);
uint fee = msg.value.mul(transactionFee).div(10 ** FEE_DECIMALS);
_orderCreator.transfer(msg.value.sub(fee));
transactionFeeRecipient.transfer(fee);
emit LogSellOrderFilled(filledOrderIndex, msg.sender, _orderCreator, _basketAddress, msg.value, _amountBasket);
return true;
}
/// @dev Contract internal function to fill an existing order
/// @param _orderCreator Address of the original order's creator
/// @param _tokenGet Address of token/ETH to receive in original order
/// @param _amountGet Amount of token/ETH to receive in original order
/// @param _tokenGive Address of token/ETH to give in original order
/// @param _amountGive Amount of token/ETH to give in original order
/// @param _expiration Unix timestamp in original order
/// @param _nonce Random number in original order
/// @return filledOrderIndex Index of filled order
function _fillOrder(
address _orderCreator,
address _tokenGet,
uint _amountGet,
address _tokenGive,
uint _amountGive,
uint _expiration,
uint _nonce
)
internal
returns (uint index)
{
bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expiration, _nonce);
uint filledOrderIndex = orders[_orderCreator][hash];
require(filledOrderIndex > 0); // Check: "Order does not exist"
require(filledOrders[_orderCreator][hash] != true); // Check: "Order has been filled"
require(now <= _expiration); // Check: "Order has expired"
filledOrders[_orderCreator][hash] = true;
balances[_orderCreator][_tokenGive] = balances[_orderCreator][_tokenGive].sub(_amountGive);
return filledOrderIndex;
}
/// @dev Get details of an order with its index;
/// @param _orderIndex Order index assigned at order creation
/// @return Order struct
function getOrderDetails(uint _orderIndex) public view returns (
address orderCreator,
address tokenGet,
uint amountGet,
address tokenGive,
uint amountGive,
uint expiration,
uint nonce,
bool _orderExists,
bool _isFilled
) {
Order memory o = orderMap[_orderIndex];
bytes32 hash = sha256(this, o.tokenGet, o.amountGet, o.tokenGive, o.amountGive, o.expiration, o.nonce);
bool orderExists = orders[o.orderCreator][hash] > 0;
bool isFilled = filledOrders[o.orderCreator][hash];
return (o.orderCreator, o.tokenGet, o.amountGet, o.tokenGive, o.amountGive, o.expiration, o.nonce, orderExists, isFilled);
}
/// @dev Change recipient of transaction fees
/// @param _newRecipient New fee recipient
/// @return success Operation successful
function changeTransactionFeeRecipient(address _newRecipient) public onlyAdmin returns (bool success) {
address oldRecipient = transactionFeeRecipient;
transactionFeeRecipient = _newRecipient;
emit LogTransactionFeeRecipientChange(oldRecipient, transactionFeeRecipient);
return true;
}
/// @dev Change percentage of fee charged for ETH transactions
/// @param _newFee New fee amount
/// @return success Operation successful
function changeTransactionFee(uint _newFee) public onlyAdmin returns (bool success) {
uint oldFee = transactionFee;
transactionFee = _newFee;
emit LogTransactionFeeChange(oldFee, transactionFee);
return true;
}
/// @dev Fallback to reject any ether sent directly to contract
// Check: "BasketEscrow does not accept ETH transfers"
function () public payable { revert(); }
}
|
BasketEscrow constructor _basketRegistryAddress Address of basket registry _transactionFeeRecipient Address to send transactionFee _transactionFee Transaction fee in ETH percentage
|
function BasketEscrow(
address _basketRegistryAddress,
address _transactionFeeRecipient,
uint _transactionFee
) public {
basketRegistryAddress = _basketRegistryAddress;
basketRegistry = IBasketRegistry(_basketRegistryAddress);
transactionFeeRecipient = _transactionFeeRecipient;
transactionFee = _transactionFee;
FEE_DECIMALS = 18;
}
| 5,491,141 |
./full_match/42220/0xe18033a1e93b3B516A2671c29631136E1fC68A78/sources/D/wannaswap/wannaswap-core/contracts/WannaSwapRouter.sol
|
SWAP send fee to referrer if you're a referral
|
function _refFeeTo(address user) internal view returns (address) {
return IWannaSwapTreasury(treasury).refFeeTo(user);
}
| 16,344,285 |
./partial_match/4/0x31051b00d2a6b99DC1255910B4B46C08e740faEB/sources/CandyMasterFarmer.sol
|
Deposit LP tokens to CandyMasterFarmer for $CNDY allocation.require(_amount > 0, "CandyMasterFarmer::deposit: amount must be greater than 0");
|
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
_harvest(_pid);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (user.amount == 0) {
user.rewardDebtAtBlock = block.number;
}
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accCandyPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 8,674,010 |
./full_match/4/0x6e936fE9E2c386c6BaF77FA21093b91d3dC027f6/sources/500balles.sol
|
--------------------------------------------------------PUBLIC FUNCTIONS -------------------------------------------------------- Update reward variables for all pools. Be careful of gas spending!
|
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
| 788,221 |
// SPDX-License-Identifier: MIT
/*
* TheBodega.sol
*
* Created: February 4, 2022
*
* Price: 0.088 ETH
*
* - 535 total supply
* - Pause/unpause minting
* - Limited to 3 mints per wallet
* - Whitelist restricted to Plug hodlers
*/
pragma solidity ^0.8.0;
import "./ERC721A.sol";
import "./access/Pausable.sol";
import "./utils/ReentrancyGuard.sol";
import "./utils/LibPart.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
abstract contract Plug {
function balanceOf(address a) public virtual returns (uint);
}
//@title The Bodega
//@author Jack Kasbeer (git:@jcksber, tw:@satoshigoat, og:overprivilegd)
contract TheBodega is ERC721A, Pausable, ReentrancyGuard {
using SafeMath for uint256;
//@dev Plug instance: mainnet!
Plug constant public thePlug = Plug(0x2Bb501A0374ff3Af41f2009509E9D6a36D56A6c0);
//@dev Supply
uint256 constant MAX_NUM_TOKENS = 545;//number of plug holders
//@dev Properties
string internal _contractURI;
string internal _baseTokenURI;
string internal _tokenHash;
address public payoutAddress;
uint256 public weiPrice;
uint256 constant public royaltyFeeBps = 1500;//15%
bool public openToPublic;
// ---------
// MODIFIERS
// ---------
modifier onlyValidTokenId(uint256 tid) {
require(
0 <= tid && tid < MAX_NUM_TOKENS,
"TheBodega: tid OOB"
);
_;
}
modifier enoughSupply(uint256 qty) {
require(
totalSupply() + qty < MAX_NUM_TOKENS,
"TheBodega: not enough left"
);
_;
}
modifier notEqual(string memory str1, string memory str2) {
require(
!_stringsEqual(str1, str2),
"TheBodega: must be different"
);
_;
}
modifier purchaseArgsOK(address to, uint256 qty, uint256 amount) {
require(
numberMinted(to) + qty <= 3,
"TheBodega: max 3 per wallet"
);
require(
amount >= weiPrice*qty,
"TheBodega: not enough ether"
);
require(
!_isContract(to),
"TheBodega: silly rabbit :P"
);
_;
}
// ------------
// CONSTRUCTION
// ------------
constructor() ERC721A("The Bodega", "") {
_baseTokenURI = "ipfs://";
_tokenHash = "QmbSH67UGGRWNycsNqMBqqnC8ikpriWYM7omqBnSvacm1F";//token metadata ipfs hash
_contractURI = "ipfs://Qmc6XcpjBdU5ZAa1DDFsWG8NyUqW549ejR6WK5XDrwqPUU";
weiPrice = 88000000000000000;//0.088 ETH
payoutAddress = address(0x6b8C6E15818C74895c31A1C91390b3d42B336799);//logik
}
// ----------
// MAIN LOGIC
// ----------
//@dev See {ERC721A16-_baseURI}
function _baseURI() internal view virtual override returns (string memory)
{
return _baseTokenURI;
}
//@dev See {ERC721A16-tokenURI}.
function tokenURI(uint256 tid) public view virtual override
returns (string memory)
{
require(_exists(tid), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_baseTokenURI, _tokenHash));
}
//@dev Controls the contract-level metadata to include things like royalties
function contractURI() external view returns (string memory)
{
return _contractURI;
}
//@dev Allows owners to mint for free whenever
function mint(address to, uint256 qty)
external isSquad enoughSupply(qty)
{
_safeMint(to, qty);
}
//@dev Allows public addresses (non-owners) to purchase
function plugPurchase(address payable to, uint256 qty)
external payable saleActive enoughSupply(qty) purchaseArgsOK(to, qty, msg.value)
{
require(
thePlug.balanceOf(to) > 0,
"TheBodega: plug hodlers only"
);
_safeMint(to, qty);
}
//@dev Allows public addresses (non-owners) to purchase
function publicPurchase(address payable to, uint256 qty)
external payable saleActive enoughSupply(qty) purchaseArgsOK(to, qty, msg.value)
{
require(
openToPublic,
"TheBodega: sale is not public"
);
_safeMint(to, qty);
}
//@dev Allows us to withdraw funds collected
function withdraw(address payable wallet, uint256 amount)
external isSquad nonReentrant
{
require(
amount <= address(this).balance,
"TheBodega: insufficient funds to withdraw"
);
wallet.transfer(amount);
}
//@dev Destroy contract and reclaim leftover funds
function kill() external onlyOwner
{
selfdestruct(payable(_msgSender()));
}
//@dev See `kill`; protects against being unable to delete a collection on OpenSea
function safe_kill() external onlyOwner
{
require(
balanceOf(_msgSender()) == totalSupply(),
"TheBodega: potential error - not all tokens owned"
);
selfdestruct(payable(_msgSender()));
}
/// -------
/// SETTERS
// --------
//@dev Ability to change the base token URI
function setBaseTokenURI(string calldata newBaseURI)
external isSquad notEqual(_baseTokenURI, newBaseURI) { _baseTokenURI = newBaseURI; }
//@dev Ability to update the token metadata
function setTokenHash(string calldata newHash)
external isSquad notEqual(_tokenHash, newHash) { _tokenHash = newHash; }
//@dev Ability to change the contract URI
function setContractURI(string calldata newContractURI)
external isSquad notEqual(_contractURI, newContractURI) { _contractURI = newContractURI; }
//@dev Change the price
function setPrice(uint256 newWeiPrice) external isSquad
{
require(
weiPrice != newWeiPrice,
"TheBodega: newWeiPrice must be different"
);
weiPrice = newWeiPrice;
}
//@dev Toggle the lock on public purchasing
function toggleOpenToPublic() external isSquad
{
openToPublic = openToPublic ? false : true;
}
// -------
// HELPERS
// -------
//@dev Gives us access to the otw internal function `_numberMinted`
function numberMinted(address owner) public view returns (uint256)
{
return _numberMinted(owner);
}
//@dev Determine if two strings are equal using the length + hash method
function _stringsEqual(string memory a, string memory b)
internal pure returns (bool)
{
bytes memory A = bytes(a);
bytes memory B = bytes(b);
if (A.length != B.length) {
return false;
} else {
return keccak256(A) == keccak256(B);
}
}
//@dev Determine if an address is a smart contract
function _isContract(address a) internal view returns (bool)
{
uint32 size;
assembly {
size := extcodesize(a)
}
return size > 0;
}
// ---------
// ROYALTIES
// ---------
//@dev Rarible Royalties V2
function getRaribleV2Royalties(uint256 tid)
external view onlyValidTokenId(tid)
returns (LibPart.Part[] memory)
{
LibPart.Part[] memory royalties = new LibPart.Part[](1);
royalties[0] = LibPart.Part({
account: payable(payoutAddress),
value: uint96(royaltyFeeBps)
});
return royalties;
}
// @dev See {EIP-2981}
function royaltyInfo(uint256 tid, uint256 salePrice)
external view onlyValidTokenId(tid)
returns (address, uint256)
{
uint256 ourCut = SafeMath.div(SafeMath.mul(salePrice, royaltyFeeBps), 10000);
return (payoutAddress, ourCut);
}
}
// SPDX-License-Identifier: MIT
/*
* ERC721A.sol (by Azuki)
*
* Created: February 4, 2022
*
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721]
* Non-Fungible Token Standard, including the Metadata and Enumerable extension.
* Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint256 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 internal currentIndex;
// 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;
// These are needed for contract compatability
bytes4 internal constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 internal constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 internal constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 internal constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
bytes4 internal constant _INTERFACE_ID_EIP2981 = 0x2a55205a;
bytes4 internal constant _INTERFACE_ID_ROYALTIES = 0xcad96cca;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), 'ERC721A: global index out of bounds');
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract,
* be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000),
* test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
require(index < balanceOf(owner), 'ERC721A: owner index out of bounds');
uint128 numMintedSoFar = uint128(totalSupply());
uint128 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when uint16 i is equal to another uint16 numMintedSoFar.
unchecked {
uint128 i;
for (i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert('ERC721A: unable to get token of owner by index');
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public view virtual override(ERC165, IERC165) returns (bool)
{
return interfaceId == _INTERFACE_ID_ERC165
|| interfaceId == _INTERFACE_ID_ROYALTIES
|| interfaceId == _INTERFACE_ID_ERC721
|| interfaceId == _INTERFACE_ID_ERC721_METADATA
|| interfaceId == _INTERFACE_ID_ERC721_ENUMERABLE
|| interfaceId == _INTERFACE_ID_EIP2981
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), 'ERC721A: balance query for the zero address');
return _addressData[owner].balance;
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), 'ERC721A: number minted query for the zero address');
return _addressData[owner].numberMinted;
}
/**
* 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) {
require(_exists(tokenId), 'ERC721A: owner query for nonexistent token');
unchecked {
uint256 curr;
for (curr = tokenId; curr >= 0; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
revert('ERC721A: unable to determine the owner of token');
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token');
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, 'ERC721A: approval to current owner');
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
'ERC721A: approve caller is not owner nor approved for all'
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), 'ERC721A: approved query for nonexistent token');
return _tokenApprovals[uint16(tokenId)];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), 'ERC721A: approve to caller');
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve}
* or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev 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;
require(to != address(0), 'ERC721A: mint to the zero address');
require(quantity != 0, 'ERC721A: quantity must be greater than 0');
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint128(quantity);
_addressData[to].numberMinted += uint128(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = block.timestamp;
uint256 updatedIndex = startTokenId;
uint256 i;
for (i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
updatedIndex++;
}
currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved');
require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner');
require(to != address(0), 'ERC721A: transfer to the zero address');
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// 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;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = block.timestamp;
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721A: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be
* transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred.
* This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
/*
* Pausable.sol
*
* Created: December 21, 2021
*
* Provides functionality for pausing and unpausing the sale (or other functionality)
*/
pragma solidity >=0.5.16 <0.9.0;
import "./SquadOwnable.sol";
//@title Pausable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract Pausable is SquadOwnable {
event Paused(address indexed a);
event Unpaused(address indexed a);
bool private _paused;
constructor() {
_paused = false;
}
//@dev This will require the sale to be unpaused
modifier saleActive()
{
require(!_paused, "Pausable: sale paused.");
_;
}
//@dev Pause or unpause minting
function toggleSaleActive() external isSquad
{
_paused = !_paused;
if (_paused) {
emit Paused(_msgSender());
} else {
emit Unpaused(_msgSender());
}
}
//@dev Determine if the sale is currently paused
function isPaused() public view virtual returns (bool)
{
return _paused;
}
}
// 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
/*
* LibPart.sol
*
* Author: Jack Kasbeer (taken from 'dot')
* Created: October 20, 2021
*/
pragma solidity >=0.5.16 <0.9.0;
//@dev We need this libary for Rarible
library LibPart {
bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
/*
* SquadOwnable.sol
*
* Created: December 21, 2021
*
* An extension of `Ownable.sol` to accomodate for a potential list of owners.
* NOTE: this will need to be the last inherited contract to give all parents
* access to the modifiers it provides
*/
pragma solidity >=0.5.16 <0.9.0;
import "@openzeppelin/contracts/access/Ownable.sol";
//@title SquadOwnable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract SquadOwnable is Ownable {
//@dev Ownership - list of squad members (owners)
mapping (address => bool) internal _squad;
constructor() {
//add myself and then client
_squad[0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b] = true;
_squad[0x6b8C6E15818C74895c31A1C91390b3d42B336799] = true;//logik
}
//@dev Custom modifier for multiple owners
modifier isSquad()
{
require(isInSquad(_msgSender()), "SquadOwnable: Caller not part of squad.");
_;
}
//@dev Determine if address `a` is an approved owner
function isInSquad(address a) public view returns (bool)
{
return _squad[a];
}
//@dev Add `a` to the squad
function addToSquad(address a) public onlyOwner
{
require(!isInSquad(a), "SquadOwnable: Address already in squad.");
_squad[a] = true;
}
//@dev Remove `a` from the squad
function removeFromSquad(address a) public onlyOwner
{
require(isInSquad(a), "SquadOwnable: Address already not in squad.");
_squad[a] = false;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
|
Determine if two strings are equal using the length + hash method
|
function _stringsEqual(string memory a, string memory b)
internal pure returns (bool)
{
bytes memory A = bytes(a);
bytes memory B = bytes(b);
if (A.length != B.length) {
return false;
return keccak256(A) == keccak256(B);
}
}
| 1,351,639 |
pragma solidity ^0.4.11;
// File: zeppelin-solidity/contracts/math/Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/StandingOrder.sol
/**
* @title Standing order
* @dev Lifecycle of a standing order:
* - the payment amount per interval is set at construction time and can not be changed afterwards
* - the payee is set by the owner and can not be changed after creation
* - at <startTime> (unix timestamp) the first payment is due
* - every <intervall> seconds the next payment is due
* - the owner can add funds to the order contract at any time
* - the owner can withdraw only funds that do not (yet) belong to the payee
* - the owner can terminate a standingorder anytime. Termination results in:
* - No further funding being allowed
* - order marked as "terminated" and not being displayed anymore in owner UI
* - as long as there are uncollected funds entitled to the payee, it is still displayed in payee UI
* - the payee can still collect funds owned to him
*
* * Terminology *
* "withdraw" -> performed by owner - transfer funds stored in contract back to owner
* "collect" -> performed by payee - transfer entitled funds from contract to payee
*
* * How does a payment work? *
* Since a contract can not trigger a payment by itself, it provides the method "collectFunds" for the payee.
* The payee can always query the contract to determine how many funds he is entitled to collect.
* The payee can call "collectFunds" to initiate transfer of entitled funds to his address.
*/
contract StandingOrder {
using SafeMath for uint;
using Math for uint;
address public owner; /** The owner of this order */
address public payee; /** The payee is the receiver of funds */
uint public startTime; /** Date and time (unix timestamp - seconds since 1970) when first payment can be claimed by payee */
uint public paymentInterval; /** Interval for payments (Unit: seconds) */
uint public paymentAmount; /** How much can payee claim per period (Unit: Wei) */
uint public claimedFunds; /** How much funds have been claimed already (Unit: Wei) */
string public ownerLabel; /** Label (set by contract owner) */
bool public isTerminated; /** Marks order as terminated */
uint public terminationTime; /** Date and time (unix timestamp - seconds since 1970) when order terminated */
modifier onlyPayee() {
require(msg.sender == payee);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/** Event triggered when payee collects funds */
event Collect(uint amount);
/** Event triggered when contract gets funded */
event Fund(uint amount);
/** Event triggered when owner withdraws funds */
event Withdraw(uint amount);
/**
* Constructor
* @param _owner The owner of the contract
* @param _payee The payee - the account that can collect payments from this contract
* @param _paymentInterval Interval for payments, unit: seconds
* @param _paymentAmount The amount payee can claim per period, unit: wei
* @param _startTime Date and time (unix timestamp - seconds since 1970) when first payment can be claimed by payee
* @param _label Label for contract, e.g "rent" or "weekly paycheck"
*/
function StandingOrder(
address _owner,
address _payee,
uint _paymentInterval,
uint _paymentAmount,
uint _startTime,
string _label
)
payable
{
// Sanity check parameters
require(_paymentInterval > 0);
require(_paymentAmount > 0);
// Following check is not exact for unicode strings, but here i just want to make sure that some label is provided
// See https://ethereum.stackexchange.com/questions/13862/is-it-possible-to-check-string-variables-length-inside-the-contract/13886
require(bytes(_label).length > 2);
// Set owner to _owner, as msg.sender is the StandingOrderFactory contract
owner = _owner;
payee = _payee;
paymentInterval = _paymentInterval;
paymentAmount = _paymentAmount;
ownerLabel = _label;
startTime = _startTime;
isTerminated = false;
}
/**
* Fallback function.
* Allows adding funds to existing order. Will throw in case the order is terminated!
*/
function() payable {
if (isTerminated) {
// adding funds not allowed for terminated orders
revert();
}
// Log Fund event
Fund(msg.value);
}
/**
* Determine how much funds payee is entitled to collect
* Note that this might be more than actual funds available!
* @return Number of wei that payee is entitled to collect
*/
function getEntitledFunds() constant returns (uint) {
// First check if the contract startTime has been reached at all
if (now < startTime) {
// startTime not yet reached
return 0;
}
// startTime has been reached, so add first payment
uint entitledAmount = paymentAmount;
// Determine endTime for calculation. If order has been terminated -> terminationTime, otherwise current time
uint endTime = isTerminated ? terminationTime : now;
// calculate number of complete intervals since startTime
uint runtime = endTime.sub(startTime);
uint completeIntervals = runtime.div(paymentInterval); // Division always truncates, so implicitly rounding down here.
entitledAmount = entitledAmount.add(completeIntervals.mul(paymentAmount));
// subtract already collected funds
return entitledAmount.sub(claimedFunds);
}
/**
* Determine how much funds are available for payee to collect
* This can be less than the entitled amount if the contract does not have enough funds to cover the due payments,
* in other words: The owner has not put enough funds into the contract.
* @return Number of wei that payee can collect
*/
function getUnclaimedFunds() constant returns (uint) {
// don't return more than available balance
return getEntitledFunds().min256(this.balance);
}
/**
* Determine how much funds are still owned by owner (not yet reserved for payee)
* Note that this can be negative in case contract is not funded enough to cover entitled amount for payee!
* @return number of wei belonging owner, negative if contract is missing funds to cover payments
*/
function getOwnerFunds() constant returns (int) {
// Conversion from unsigned int to int will produce unexpected results only for very large
// numbers (2^255 and greater). This is about 5.7e+58 ether.
// -> There will be no situation when the contract balance (this.balance) will hit this limit
// -> getEntitledFunds() might end up hitting this limit when the contract creator INTENTIONALLY sets
// any combination of absurdly high payment rate, low interval or a startTime way in the past.
// Being entitled to more than 5.7e+58 ether obviously will never be an expected usecase
// Therefor the conversion can be considered safe here.
return int256(this.balance) - int256(getEntitledFunds());
}
/**
* Collect payment
* Can only be called by payee. This will transfer all available funds (see getUnclaimedFunds) to payee
* @return amount that has been transferred!
*/
function collectFunds() onlyPayee returns(uint) {
uint amount = getUnclaimedFunds();
if (amount <= 0) {
// nothing to collect :-(
revert();
}
// keep track of collected funds
claimedFunds = claimedFunds.add(amount);
// create log entry
Collect(amount);
// initiate transfer of unclaimed funds to payee
payee.transfer(amount);
return amount;
}
/**
* Withdraw requested amount back to owner.
* Only funds not (yet) reserved for payee can be withdrawn. So it is not possible for the owner
* to withdraw unclaimed funds - They can only be claimed by payee!
* Withdrawing funds does not terminate the order, at any time owner can fund it again!
* @param amount Number of wei owner wants to withdraw
*/
function WithdrawOwnerFunds(uint amount) onlyOwner {
int intOwnerFunds = getOwnerFunds(); // this might be negative in case of underfunded contract!
if (intOwnerFunds <= 0) {
// nothing available to withdraw :-(
revert();
}
// conversion int -> uint is safe here as I'm checking <= 0 above!
uint256 ownerFunds = uint256(intOwnerFunds);
if (amount > ownerFunds) {
// Trying to withdraw more than available!
revert();
}
// Log Withdraw event
Withdraw(amount);
owner.transfer(amount);
}
/**
* Terminate order
* Marks the order as terminated.
* Can only be executed if no ownerfunds are left
*/
function Terminate() onlyOwner {
assert(getOwnerFunds() <= 0);
terminationTime = now;
isTerminated = true;
}
}
/**
* @title StandingOrder factory
*/
contract StandingOrderFactory {
// keep track who issued standing orders
mapping (address => StandingOrder[]) public standingOrdersByOwner;
// keep track of payees of standing orders
mapping (address => StandingOrder[]) public standingOrdersByPayee;
// Events
event LogOrderCreated(
address orderAddress,
address indexed owner,
address indexed payee
);
/**
* Create a new standing order
* The owner of the new order will be the address that called this function (msg.sender)
* @param _payee The payee - the account that can collect payments from this contract
* @param _paymentInterval Interval for payments, unit: seconds
* @param _paymentAmount The amount payee can claim per period, unit: wei
* @param _startTime Date and time (unix timestamp - seconds since 1970) when first payment can be claimed by payee
* @param _label Label for contract, e.g "rent" or "weekly paycheck"
* @return Address of new created standingOrder contract
*/
function createStandingOrder(address _payee, uint _paymentAmount, uint _paymentInterval, uint _startTime, string _label) returns (StandingOrder) {
StandingOrder so = new StandingOrder(msg.sender, _payee, _paymentInterval, _paymentAmount, _startTime, _label);
standingOrdersByOwner[msg.sender].push(so);
standingOrdersByPayee[_payee].push(so);
LogOrderCreated(so, msg.sender, _payee);
return so;
}
/**
* Determine how many orders are owned by caller (msg.sender)
* @return Number of orders
*/
function getNumOrdersByOwner() constant returns (uint) {
return standingOrdersByOwner[msg.sender].length;
}
/**
* Get order by index from the Owner mapping
* @param index Index of order
* @return standing order address
*/
function getOwnOrderByIndex(uint index) constant returns (StandingOrder) {
return standingOrdersByOwner[msg.sender][index];
}
/**
* Determine how many orders are paying to caller (msg.sender)
* @return Number of orders
*/
function getNumOrdersByPayee() constant returns (uint) {
return standingOrdersByPayee[msg.sender].length;
}
/**
* Get order by index from the Payee mapping
* @param index Index of order
* @return standing order address
*/
function getPaidOrderByIndex(uint index) constant returns (StandingOrder) {
return standingOrdersByPayee[msg.sender][index];
}
}
|
Get order by index from the Owner mapping index Index of order return standing order address/
|
function getOwnOrderByIndex(uint index) constant returns (StandingOrder) {
return standingOrdersByOwner[msg.sender][index];
}
| 2,526,008 |
./full_match/80001/0xaaE660f00db52D912173E9aEa1Af1e33fe9422C1/sources/contracts/Vault.sol
|
Function to collect native token fees _to Address to send fees to
|
function collectFees(address payable _to) external onlyOwner nonReentrant {
uint256 fee = getProratedFee(address(this).balance);
_feesByToken[address(0)] = 0;
_lastFeeCollection = block.timestamp;
uint256 totalFee = fee + _feesByToken[address(0)];
_to.transfer(totalFee);
emit FeeCollection(block.timestamp, totalFee);
}
| 852,203 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
//
interface IERC20 {
function TOTALSUPPLY709() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF1000(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER912(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE378(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM696(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER249(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL928(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
//
abstract contract Context {
function _MSGSENDER905() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA980() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
//
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED618(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER905();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED618(address(0), msgSender);
}
function OWNER941() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER378() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER905(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP149() public virtual ONLYOWNER378 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED618(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP687(address newOwner) public virtual ONLYOWNER378 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED618(_owner, newOwner);
_owner = newOwner;
}
}
//
library SafeMath {
function ADD236(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB786(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB786(a, b, "SafeMath: subtraction overflow");
}
function SUB786(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL747(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV140(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV140(a, b, "SafeMath: division by zero");
}
function DIV140(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD599(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD599(a, b, "SafeMath: modulo by zero");
}
function MOD599(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
//
library Address {
function ISCONTRACT863(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function SENDVALUE275(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL887(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL887(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL887(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE192(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE672(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE672(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE672(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE192(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE192(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT863(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _not_entered586 = 1; //inject NONSTANDARD NAMING
uint256 private constant _entered769 = 2; //inject NONSTANDARD NAMING
uint256 private _status;
constructor () internal {
_status = _not_entered586;
}
modifier NONREENTRANT44() { //inject NONSTANDARD NAMING
// On the first call to nonReentrant, _notEntered will be true
require(_status != _entered769, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _entered769;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _not_entered586;
}
}
//
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER115(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.TRANSFER912.selector, to, value));
}
function SAFETRANSFERFROM287(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.TRANSFERFROM696.selector, from, to, value));
}
function SAFEAPPROVE190(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.ALLOWANCE643(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, value));
}
function SAFEINCREASEALLOWANCE374(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE643(address(this), spender).ADD236(value);
_CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE80(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE643(address(this), spender).SUB786(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN516(token, abi.encodeWithSelector(token.APPROVE378.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN516(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).FUNCTIONCALL887(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
//
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME654() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL381() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS442() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY709() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF1000(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER912(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER205(_MSGSENDER905(), recipient, amount);
return true;
}
function ALLOWANCE643(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE378(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE516(_MSGSENDER905(), spender, amount);
return true;
}
function TRANSFERFROM696(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER205(sender, recipient, amount);
_APPROVE516(sender, _MSGSENDER905(), _allowances[sender][_MSGSENDER905()].SUB786(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE9(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE516(_MSGSENDER905(), spender, _allowances[_MSGSENDER905()][spender].ADD236(addedValue));
return true;
}
function DECREASEALLOWANCE999(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE516(_MSGSENDER905(), spender, _allowances[_MSGSENDER905()][spender].SUB786(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER205(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER183(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB786(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD236(amount);
emit TRANSFER249(sender, recipient, amount);
}
function _MINT985(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER183(address(0), account, amount);
_totalSupply = _totalSupply.ADD236(amount);
_balances[account] = _balances[account].ADD236(amount);
emit TRANSFER249(address(0), account, amount);
}
function _BURN126(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER183(account, address(0), amount);
_balances[account] = _balances[account].SUB786(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB786(amount);
emit TRANSFER249(account, address(0), amount);
}
function _APPROVE516(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL928(owner, spender, amount);
}
function _SETUPDECIMALS502(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER183(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
//
contract YieldDelegatingVaultEvent2 {
event NEWTREASURY741(address oldTreasury, address newTreasury); //inject NONSTANDARD NAMING
event NEWDELEGATEPERCENT315(uint256 oldDelegatePercent, uint256 newDelegatePercent); //inject NONSTANDARD NAMING
event NEWREWARDPERTOKEN257(uint256 oldRewardPerToken, uint256 newRewardPerToken); //inject NONSTANDARD NAMING
}
//
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
function _ADD330(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS441(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _REMOVE267(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _CONTAINS441(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH266(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT20(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD236(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD330(set._inner, bytes32(uint256(value)));
}
function REMOVE884(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE267(set._inner, bytes32(uint256(value)));
}
function CONTAINS556(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS441(set._inner, bytes32(uint256(value)));
}
function LENGTH118(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH266(set._inner);
}
function AT34(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT20(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD236(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD330(set._inner, bytes32(value));
}
function REMOVE884(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE267(set._inner, bytes32(value));
}
function CONTAINS556(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS441(set._inner, bytes32(value));
}
function LENGTH118(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH266(set._inner);
}
function AT34(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT20(set._inner, index));
}
}
//
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant default_admin_role567 = 0x00; //inject NONSTANDARD NAMING
event ROLEADMINCHANGED88(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING
event ROLEGRANTED826(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
event ROLEREVOKED185(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
function HASROLE367(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _roles[role].members.CONTAINS556(account);
}
function GETROLEMEMBERCOUNT938(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING
return _roles[role].members.LENGTH118();
}
function GETROLEMEMBER19(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING
return _roles[role].members.AT34(index);
}
function GETROLEADMIN235(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING
return _roles[role].adminRole;
}
function GRANTROLE137(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE367(_roles[role].adminRole, _MSGSENDER905()), "AccessControl: sender must be an admin to grant");
_GRANTROLE954(role, account);
}
function REVOKEROLE670(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE367(_roles[role].adminRole, _MSGSENDER905()), "AccessControl: sender must be an admin to revoke");
_REVOKEROLE460(role, account);
}
function RENOUNCEROLE777(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(account == _MSGSENDER905(), "AccessControl: can only renounce roles for self");
_REVOKEROLE460(role, account);
}
function _SETUPROLE461(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING
_GRANTROLE954(role, account);
}
function _SETROLEADMIN512(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING
emit ROLEADMINCHANGED88(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _GRANTROLE954(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.ADD236(account)) {
emit ROLEGRANTED826(role, account, _MSGSENDER905());
}
}
function _REVOKEROLE460(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.REMOVE884(account)) {
emit ROLEREVOKED185(role, account, _MSGSENDER905());
}
}
}
//
contract YDVRewardsDistributor is AccessControl, Ownable {
using SafeERC20 for IERC20;
using Address for address;
IERC20 public rewardToken;
address[] public ydvs;
bytes32 public constant ydv_rewards665 = keccak256("YDV_REWARDS"); //inject NONSTANDARD NAMING
constructor(address _rally) public {
rewardToken = IERC20(_rally);
_SETUPROLE461(default_admin_role567, msg.sender);
}
function TRANSFERREWARD486(uint256 _amount) external { //inject NONSTANDARD NAMING
require (HASROLE367(ydv_rewards665, msg.sender), "only ydv rewards");
rewardToken.SAFETRANSFER115(msg.sender, _amount);
}
function ADDYDV918(address _ydv) external ONLYOWNER378 { //inject NONSTANDARD NAMING
GRANTROLE137(ydv_rewards665, _ydv);
ydvs.push(_ydv);
}
function YDVSLENGTH403() external view returns (uint256) { //inject NONSTANDARD NAMING
return ydvs.length;
}
}
//
interface Vault {
function BALANCEOF1000(address) external view returns (uint256); //inject NONSTANDARD NAMING
function TOKEN783() external view returns (address); //inject NONSTANDARD NAMING
function CLAIMINSURANCE535() external; //inject NONSTANDARD NAMING
function GETPRICEPERFULLSHARE194() external view returns (uint256); //inject NONSTANDARD NAMING
function DEPOSIT941(uint) external; //inject NONSTANDARD NAMING
function WITHDRAW419(uint) external; //inject NONSTANDARD NAMING
}
//
contract YDVErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
REJECTION
}
enum FailureInfo {
SET_INDIVIDUAL_SOFT_CAP_CHECK,
SET_GLOBAL_SOFT_CAP_CHECK
}
event FAILURE308(uint error, uint info, uint detail); //inject NONSTANDARD NAMING
function FAIL273(Error err, FailureInfo info) internal returns (uint) { //inject NONSTANDARD NAMING
emit FAILURE308(uint(err), uint(info), 0);
return uint(err);
}
function FAILOPAQUE544(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { //inject NONSTANDARD NAMING
emit FAILURE308(uint(err), uint(info), opaqueError);
return uint(err);
}
}
//
contract RallyToken is ERC20 {
//15 billion fixed token supply with default 18 decimals
uint256 public constant token_supply159 = 15 * 10**9 * 10**18; //inject NONSTANDARD NAMING
constructor (
address _escrow
) public ERC20(
"Rally",
"RLY"
) {
_MINT985(_escrow, token_supply159);
}
}
//
contract NoMintLiquidityRewardPools is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of RLY
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accRallyPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accRallyPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. RLYs to distribute per block.
uint256 lastRewardBlock; // Last block number that RLYs distribution occurs.
uint256 accRallyPerShare; // Accumulated RLYs per share, times 1e12. See below.
}
// The RALLY TOKEN!
RallyToken public rally;
// RLY tokens created per block.
uint256 public rallyPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when RLY mining starts.
uint256 public startBlock;
event DEPOSIT927(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAW385(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW903(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
constructor(
RallyToken _rally,
uint256 _rallyPerBlock,
uint256 _startBlock
) public {
rally = _rally;
rallyPerBlock = _rallyPerBlock;
startBlock = _startBlock;
}
function POOLLENGTH610() external view returns (uint256) { //inject NONSTANDARD NAMING
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function ADD236(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public ONLYOWNER378 { //inject NONSTANDARD NAMING
if (_withUpdate) {
MASSUPDATEPOOLS681();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.ADD236(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accRallyPerShare: 0
}));
}
// Update the given pool's RLY allocation point. Can only be called by the owner.
function SET138(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public ONLYOWNER378 { //inject NONSTANDARD NAMING
if (_withUpdate) {
MASSUPDATEPOOLS681();
}
totalAllocPoint = totalAllocPoint.SUB786(poolInfo[_pid].allocPoint).ADD236(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// update the rate at which RLY is allocated to rewards, can only be called by the owner
function SETRALLYPERBLOCK200(uint256 _rallyPerBlock) public ONLYOWNER378 { //inject NONSTANDARD NAMING
MASSUPDATEPOOLS681();
rallyPerBlock = _rallyPerBlock;
}
// View function to see pending RLYs on frontend.
function PENDINGRALLY232(uint256 _pid, address _user) external view returns (uint256) { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accRallyPerShare = pool.accRallyPerShare;
uint256 lpSupply = pool.lpToken.BALANCEOF1000(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = block.number.SUB786(pool.lastRewardBlock);
uint256 rallyReward = multiplier.MUL747(rallyPerBlock).MUL747(pool.allocPoint).DIV140(totalAllocPoint);
accRallyPerShare = accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(lpSupply));
}
return user.amount.MUL747(accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function MASSUPDATEPOOLS681() public { //inject NONSTANDARD NAMING
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
UPDATEPOOL112(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
// No new RLY are minted, distribution is dependent on sufficient RLY tokens being sent to this contract
function UPDATEPOOL112(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.BALANCEOF1000(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = block.number.SUB786(pool.lastRewardBlock);
uint256 rallyReward = multiplier.MUL747(rallyPerBlock).MUL747(pool.allocPoint).DIV140(totalAllocPoint);
pool.accRallyPerShare = pool.accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to pool for RLY allocation.
function DEPOSIT941(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
UPDATEPOOL112(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt);
if(pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.SAFETRANSFERFROM287(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD236(_amount);
}
user.rewardDebt = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12);
emit DEPOSIT927(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from pool.
function WITHDRAW419(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
UPDATEPOOL112(_pid);
uint256 pending = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12).SUB786(user.rewardDebt);
if(pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.SUB786(_amount);
pool.lpToken.SAFETRANSFER115(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.MUL747(pool.accRallyPerShare).DIV140(1e12);
emit WITHDRAW385(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function EMERGENCYWITHDRAW757(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.SAFETRANSFER115(address(msg.sender), user.amount);
emit EMERGENCYWITHDRAW903(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe RLY transfer function, just in case pool does not have enough RLY; either rounding error or we're not supplying more rewards
function SAFERALLYTRANSFER520(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
uint256 rallyBal = rally.BALANCEOF1000(address(this));
if (_amount > rallyBal) {
rally.TRANSFER912(_to, rallyBal);
} else {
rally.TRANSFER912(_to, _amount);
}
}
}
//
contract YieldDelegatingVaultStorage2 {
address public vault;
YDVRewardsDistributor rewards;
IERC20 public rally;
address public treasury;
IERC20 public token;
uint256 public delegatePercent;
mapping(address => uint256) public rewardDebt;
uint256 public totalDeposits;
uint256 public rewardPerToken;
uint256 public accRallyPerShare;
bool public lrEnabled;
uint256 public pid;
NoMintLiquidityRewardPools lrPools;
}
//
contract YieldDelegatingVault2 is ERC20, YieldDelegatingVaultStorage2, YieldDelegatingVaultEvent2, Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
constructor (
address _vault,
address _rewards,
address _treasury,
uint256 _delegatePercent,
uint256 _rewardPerToken
) public ERC20(
string(abi.encodePacked("rally delegating ", ERC20(Vault(_vault).TOKEN783()).NAME654())),
string(abi.encodePacked("rd", ERC20(Vault(_vault).TOKEN783()).SYMBOL381()))
) {
_SETUPDECIMALS502(ERC20(Vault(_vault).TOKEN783()).DECIMALS442());
token = IERC20(Vault(_vault).TOKEN783()); //token being deposited in the referenced vault
vault = _vault; //address of the vault we're proxying
rewards = YDVRewardsDistributor(_rewards);
rally = rewards.rewardToken();
treasury = _treasury;
delegatePercent = _delegatePercent;
rewardPerToken = _rewardPerToken;
totalDeposits = 0;
accRallyPerShare = 0;
lrEnabled = false;
}
function SETTREASURY672(address newTreasury) public ONLYOWNER378 { //inject NONSTANDARD NAMING
require(newTreasury != address(0), "treasure should be valid address");
address oldTreasury = treasury;
treasury = newTreasury;
emit NEWTREASURY741(oldTreasury, newTreasury);
}
function SETNEWREWARDPERTOKEN724(uint256 newRewardPerToken) public ONLYOWNER378 { //inject NONSTANDARD NAMING
uint256 oldRewardPerToken = rewardPerToken;
rewardPerToken = newRewardPerToken;
emit NEWREWARDPERTOKEN257(oldRewardPerToken, newRewardPerToken);
}
function EARNED974(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return BALANCEFORREWARDSCALC156(account).MUL747(accRallyPerShare).DIV140(1e12).SUB786(rewardDebt[account]);
}
function BALANCE265() public view returns (uint256) { //inject NONSTANDARD NAMING
return (IERC20(vault)).BALANCEOF1000(address(this)); //how many shares do we have in the vault we are delegating to
}
//for the purpose of rewards calculations, a user's balance is the total of what's in their wallet
//and what they have deposited in the rewards pool (if it's active).
//transfer restriction ensures accuracy of this sum
function BALANCEFORREWARDSCALC156(address account) internal view returns (uint256) { //inject NONSTANDARD NAMING
if (lrEnabled) {
(uint256 amount, ) = lrPools.userInfo(pid, account);
return BALANCEOF1000(account).ADD236(amount);
}
return BALANCEOF1000(account);
}
function DEPOSITALL490() external { //inject NONSTANDARD NAMING
DEPOSIT941(token.BALANCEOF1000(msg.sender));
}
function DEPOSIT941(uint256 _amount) public NONREENTRANT44 { //inject NONSTANDARD NAMING
uint256 pending = EARNED974(msg.sender);
if (pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
uint256 _pool = BALANCE265();
uint256 _before = token.BALANCEOF1000(address(this));
token.SAFETRANSFERFROM287(msg.sender, address(this), _amount);
uint256 _after = token.BALANCEOF1000(address(this));
_amount = _after.SUB786(_before);
totalDeposits = totalDeposits.ADD236(_amount);
token.APPROVE378(vault, _amount);
Vault(vault).DEPOSIT941(_amount);
uint256 _after_pool = BALANCE265();
uint256 _new_shares = _after_pool.SUB786(_pool); //new vault tokens representing my added vault shares
//translate vault shares into delegating vault shares
uint256 shares = 0;
if (TOTALSUPPLY709() == 0) {
shares = _new_shares;
} else {
shares = (_new_shares.MUL747(TOTALSUPPLY709())).DIV140(_pool);
}
_MINT985(msg.sender, shares);
rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12);
}
function DEPOSITYTOKEN556(uint256 _yamount) public NONREENTRANT44 { //inject NONSTANDARD NAMING
uint256 pending = EARNED974(msg.sender);
if (pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
uint256 _before = IERC20(vault).BALANCEOF1000(address(this));
IERC20(vault).SAFETRANSFERFROM287(msg.sender, address(this), _yamount);
uint256 _after = IERC20(vault).BALANCEOF1000(address(this));
_yamount = _after.SUB786(_before);
uint _underlyingAmount = _yamount.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18);
totalDeposits = totalDeposits.ADD236(_underlyingAmount);
//translate vault shares into delegating vault shares
uint256 shares = 0;
if (TOTALSUPPLY709() == 0) {
shares = _yamount;
} else {
shares = (_yamount.MUL747(TOTALSUPPLY709())).DIV140(_before);
}
_MINT985(msg.sender, shares);
rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12);
}
function WITHDRAWALL908() external { //inject NONSTANDARD NAMING
WITHDRAW419(BALANCEOF1000(msg.sender));
}
function WITHDRAW419(uint256 _shares) public NONREENTRANT44 { //inject NONSTANDARD NAMING
uint256 pending = EARNED974(msg.sender);
if (pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
uint256 r = (BALANCE265().MUL747(_shares)).DIV140(TOTALSUPPLY709());
_BURN126(msg.sender, _shares);
SAFEREDUCETOTALDEPOSITS144(r.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18));
rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12);
uint256 _before = token.BALANCEOF1000(address(this));
Vault(vault).WITHDRAW419(r);
uint256 _after = token.BALANCEOF1000(address(this));
uint256 toTransfer = _after.SUB786(_before);
token.SAFETRANSFER115(msg.sender, toTransfer);
}
//in case of rounding errors converting between vault tokens and underlying value
function SAFEREDUCETOTALDEPOSITS144(uint256 _amount) internal { //inject NONSTANDARD NAMING
if (_amount > totalDeposits) {
totalDeposits = 0;
} else {
totalDeposits = totalDeposits.SUB786(_amount);
}
}
function WITHDRAWYTOKEN466(uint256 _shares) public NONREENTRANT44 { //inject NONSTANDARD NAMING
uint256 pending = EARNED974(msg.sender);
if (pending > 0) {
SAFERALLYTRANSFER520(msg.sender, pending);
}
uint256 r = (BALANCE265().MUL747(_shares)).DIV140(TOTALSUPPLY709());
_BURN126(msg.sender, _shares);
rewardDebt[msg.sender] = BALANCEFORREWARDSCALC156(msg.sender).MUL747(accRallyPerShare).DIV140(1e12);
uint256 _amount = r.MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18);
SAFEREDUCETOTALDEPOSITS144(_amount);
IERC20(vault).SAFETRANSFER115(msg.sender, r);
}
// Safe RLY transfer function, just in case pool does not have enough RLY due to rounding error
function SAFERALLYTRANSFER520(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
uint256 rallyBal = rally.BALANCEOF1000(address(this));
if (_amount > rallyBal) {
rally.TRANSFER912(_to, rallyBal);
} else {
rally.TRANSFER912(_to, _amount);
}
}
//how much are our shares of the underlying vault worth relative to the deposit value? returns value denominated in vault tokens
function AVAILABLEYIELD882() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 totalValue = BALANCE265().MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18);
if (totalValue > totalDeposits) {
uint256 earnings = totalValue.SUB786(totalDeposits);
return earnings.MUL747(1e18).DIV140(Vault(vault).GETPRICEPERFULLSHARE194());
}
return 0;
}
//transfer accumulated yield to treasury, update totalDeposits to ensure availableYield following
//harvest is 0, and increase accumulated rally rewards
//harvest fails if we're unable to fund rewards
function HARVEST82() public ONLYOWNER378 { //inject NONSTANDARD NAMING
uint256 _availableYield = AVAILABLEYIELD882();
if (_availableYield > 0) {
uint256 rallyReward = _availableYield.MUL747(delegatePercent).DIV140(10000).MUL747(rewardPerToken).DIV140(1e18);
rewards.TRANSFERREWARD486(rallyReward);
IERC20(vault).SAFETRANSFER115(treasury, _availableYield.MUL747(delegatePercent).DIV140(10000));
accRallyPerShare = accRallyPerShare.ADD236(rallyReward.MUL747(1e12).DIV140(TOTALSUPPLY709()));
totalDeposits = BALANCE265().MUL747(Vault(vault).GETPRICEPERFULLSHARE194()).DIV140(1e18);
}
}
//one way ticket and only callable once
function ENABLELIQUIDITYREWARDS505(address _lrPools, uint256 _pid) public ONLYOWNER378 { //inject NONSTANDARD NAMING
(IERC20 lpToken,,,) = NoMintLiquidityRewardPools(_lrPools).poolInfo(_pid);
require(address(lpToken) == address(this), "invalid liquidity rewards setup");
require(lrEnabled == false, "liquidity rewards already enabled");
lrEnabled = true;
lrPools = NoMintLiquidityRewardPools(_lrPools);
pid = _pid;
}
//override underlying _transfer implementation; YDV shares can only be transferred to/from the liquidity rewards pool
function _TRANSFER205(address sender, address recipient, uint256 amount) internal override { //inject NONSTANDARD NAMING
require(lrEnabled, "transfer rejected");
require(sender == address(lrPools) || recipient == address(lrPools), "transfer rejected");
super._TRANSFER205(sender, recipient, amount);
}
}
|
inject NONSTANDARD NAMING
|
function TRANSFERFROM696(address sender, address recipient, uint256 amount) external returns (bool);
| 12,852,044 |
pragma solidity ^0.4.23;
// File: contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
contract SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
// File: contracts/token/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: contracts/Ownerable.sol
contract Ownerable {
/// @notice The address of the owner is the only address that can call
/// a function with this modifier
modifier onlyOwner { require(msg.sender == owner); _; }
address public owner;
constructor() public { owner = msg.sender;}
/// @notice Changes the owner of the contract
/// @param _newOwner The new owner of the contract
function setOwner(address _newOwner) public onlyOwner {
owner = _newOwner;
}
}
// File: contracts/KYC.sol
/**
* @title KYC
* @dev KYC contract handles the white list for ASTCrowdsale contract
* Only accounts registered in KYC contract can buy AST token.
* Admins can register account, and the reason why
*/
contract KYC is Ownerable {
// check the address is registered for token sale
mapping (address => bool) public registeredAddress;
// check the address is admin of kyc contract
mapping (address => bool) public admin;
event Registered(address indexed _addr);
event Unregistered(address indexed _addr);
event NewAdmin(address indexed _addr);
event ClaimedTokens(address _token, address owner, uint256 balance);
/**
* @dev check whether the address is registered for token sale or not.
* @param _addr address
*/
modifier onlyRegistered(address _addr) {
require(registeredAddress[_addr]);
_;
}
/**
* @dev check whether the msg.sender is admin or not
*/
modifier onlyAdmin() {
require(admin[msg.sender]);
_;
}
constructor () public {
admin[msg.sender] = true;
}
/**
* @dev set new admin as admin of KYC contract
* @param _addr address The address to set as admin of KYC contract
*/
function setAdmin(address _addr)
public
onlyOwner
{
require(_addr != address(0) && admin[_addr] == false);
admin[_addr] = true;
emit NewAdmin(_addr);
}
/**
* @dev register the address for token sale
* @param _addr address The address to register for token sale
*/
function register(address _addr)
public
onlyAdmin
{
require(_addr != address(0) && registeredAddress[_addr] == false);
registeredAddress[_addr] = true;
emit Registered(_addr);
}
/**
* @dev register the addresses for token sale
* @param _addrs address[] The addresses to register for token sale
*/
function registerByList(address[] _addrs)
public
onlyAdmin
{
for(uint256 i = 0; i < _addrs.length; i++) {
require(_addrs[i] != address(0) && registeredAddress[_addrs[i]] == false);
registeredAddress[_addrs[i]] = true;
emit Registered(_addrs[i]);
}
}
/**
* @dev unregister the registered address
* @param _addr address The address to unregister for token sale
*/
function unregister(address _addr)
public
onlyAdmin
onlyRegistered(_addr)
{
registeredAddress[_addr] = false;
emit Unregistered(_addr);
}
/**
* @dev unregister the registered addresses
* @param _addrs address[] The addresses to unregister for token sale
*/
function unregisterByList(address[] _addrs)
public
onlyAdmin
{
for(uint256 i = 0; i < _addrs.length; i++) {
require(registeredAddress[_addrs[i]]);
registeredAddress[_addrs[i]] = false;
emit Unregistered(_addrs[i]);
}
}
function claimTokens(address _token) public onlyOwner {
if (_token == 0x0) {
owner.transfer( address(this).balance );
return;
}
ERC20Basic token = ERC20Basic(_token);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
emit ClaimedTokens(_token, owner, balance);
}
}
// File: contracts/token/Controlled.sol
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
constructor() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
// File: contracts/token/TokenController.sol
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
// File: contracts/token/MiniMeToken.sol
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.2'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
require (allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
uint previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
//if (previousBalanceFrom < _amount) {
// return false;
//}
// Alerts the token controller of the transfer
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
emit NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
emit Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer( address(this).balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
emit ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
// File: contracts/HEX.sol
contract HEX is MiniMeToken {
mapping (address => bool) public blacklisted;
bool public generateFinished;
constructor (address _tokenFactory)
MiniMeToken(
_tokenFactory,
0x0, // no parent token
0, // no snapshot block number from parent
"Health Evolution on X.blockchain", // Token name
18, // Decimals
"HEX", // Symbol
false // Enable transfers
) {
}
function generateTokens(address _holder, uint _amount) public onlyController returns (bool) {
require(generateFinished == false);
return super.generateTokens(_holder, _amount);
}
function doTransfer(address _from, address _to, uint _amount) internal returns(bool) {
require(blacklisted[_from] == false);
return super.doTransfer(_from, _to, _amount);
}
function finishGenerating() public onlyController returns (bool) {
generateFinished = true;
return true;
}
function blacklistAccount(address tokenOwner) public onlyController returns (bool success) {
blacklisted[tokenOwner] = true;
return true;
}
function unBlacklistAccount(address tokenOwner) public onlyController returns (bool success) {
blacklisted[tokenOwner] = false;
return true;
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer( address(this).balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(address(this));
token.transfer(controller, balance);
emit ClaimedTokens(_token, controller, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
}
// File: contracts/atxinf/ATXICOToken.sol
contract ATXICOToken {
function atxBuy(address _from, uint256 _amount) public returns(bool);
}
// File: contracts/HEXCrowdSale.sol
contract HEXCrowdSale is Ownerable, SafeMath, ATXICOToken {
uint256 public maxHEXCap;
uint256 public minHEXCap;
uint256 public ethRate;
uint256 public atxRate;
/* uint256 public ethFunded;
uint256 public atxFunded; */
address[] public ethInvestors;
mapping (address => uint256) public ethInvestorFunds;
address[] public atxInvestors;
mapping (address => uint256) public atxInvestorFunds;
address[] public atxChangeAddrs;
mapping (address => uint256) public atxChanges;
KYC public kyc;
HEX public hexToken;
address public hexControllerAddr;
ERC20Basic public atxToken;
address public atxControllerAddr;
//Vault public vault;
address[] public memWallets;
address[] public vaultWallets;
struct Period {
uint256 startTime;
uint256 endTime;
uint256 bonus; // used to calculate rate with bonus. ragne 0 ~ 15 (0% ~ 15%)
}
Period[] public periods;
bool public isInitialized;
bool public isFinalized;
function init (
address _kyc,
address _token,
address _hexController,
address _atxToken,
address _atxController,
// address _vault,
address[] _memWallets,
address[] _vaultWallets,
uint256 _ethRate,
uint256 _atxRate,
uint256 _maxHEXCap,
uint256 _minHEXCap ) public onlyOwner {
require(isInitialized == false);
kyc = KYC(_kyc);
hexToken = HEX(_token);
hexControllerAddr = _hexController;
atxToken = ERC20Basic(_atxToken);
atxControllerAddr = _atxController;
memWallets = _memWallets;
vaultWallets = _vaultWallets;
/* vault = Vault(_vault);
vault.setFundTokenAddr(_atxToken); */
ethRate = _ethRate;
atxRate = _atxRate;
maxHEXCap = _maxHEXCap;
minHEXCap = _minHEXCap;
isInitialized = true;
}
function () public payable {
ethBuy();
}
function ethBuy() internal {
// check validity
require(msg.value >= 50e18); // minimum fund
require(isInitialized);
require(!isFinalized);
require(msg.sender != 0x0 && msg.value != 0x0);
require(kyc.registeredAddress(msg.sender));
require(maxReached() == false);
require(onSale());
uint256 fundingAmt = msg.value;
uint256 bonus = getPeriodBonus();
uint256 currTotalSupply = hexToken.totalSupply();
uint256 fundableHEXRoom = sub(maxHEXCap, currTotalSupply);
uint256 reqedHex = eth2HexWithBonus(fundingAmt, bonus);
uint256 toFund;
uint256 reFund;
if(reqedHex > fundableHEXRoom) {
reqedHex = fundableHEXRoom;
toFund = hex2EthWithBonus(reqedHex, bonus); //div(fundableHEXRoom, mul(ethRate, add(1, div(bonus,100))));
reFund = sub(fundingAmt, toFund);
// toFund 로 계산한 HEX 수량이 fundableHEXRoom 과 같아야 한다.
// 그러나 소수점 문제로 인하여 정확히 같아지지 않을 경우가 발생한다.
//require(reqedHex == eth2HexWithBonus(toFund, bonus) );
} else {
toFund = fundingAmt;
reFund = 0;
}
require(fundingAmt >= toFund);
require(toFund > 0);
// pushInvestorList
if(ethInvestorFunds[msg.sender] == 0x0) {
ethInvestors.push(msg.sender);
}
ethInvestorFunds[msg.sender] = add(ethInvestorFunds[msg.sender], toFund);
/* ethFunded = add(ethFunded, toFund); */
hexToken.generateTokens(msg.sender, reqedHex);
if(reFund > 0) {
msg.sender.transfer(reFund);
}
//vault.ethDeposit.value(toFund)(msg.sender);
emit SaleToken(msg.sender, msg.sender, 0, toFund, reqedHex);
}
//
// ATXICOToken 메소드 구현.
// 외부에서 이 함수가 바로 호출되면 코인 생성됨.
// 반드시 ATXController 에서만 호출 허용 할 것.
//
function atxBuy(address _from, uint256 _amount) public returns(bool) {
// check validity
require(_amount >= 250000e18); // minimum fund
require(isInitialized);
require(!isFinalized);
require(_from != 0x0 && _amount != 0x0);
require(kyc.registeredAddress(_from));
require(maxReached() == false);
require(onSale());
// Only from ATX Controller.
require(msg.sender == atxControllerAddr);
// 수신자(현재컨트랙트) atx 수신후 잔액 오버플로우 확인.
uint256 currAtxBal = atxToken.balanceOf( address(this) );
require(currAtxBal + _amount >= currAtxBal); // Check for overflow
uint256 fundingAmt = _amount;
uint256 bonus = getPeriodBonus();
uint256 currTotalSupply = hexToken.totalSupply();
uint256 fundableHEXRoom = sub(maxHEXCap, currTotalSupply);
uint256 reqedHex = atx2HexWithBonus(fundingAmt, bonus); //mul(add(fundingAmt, mul(fundingAmt, div(bonus, 100))), atxRate);
uint256 toFund;
uint256 reFund;
if(reqedHex > fundableHEXRoom) {
reqedHex = fundableHEXRoom;
toFund = hex2AtxWithBonus(reqedHex, bonus); //div(fundableHEXRoom, mul(atxRate, add(1, div(bonus,100))));
reFund = sub(fundingAmt, toFund);
// toFund 로 계산한 HEX 수량이 fundableHEXRoom 과 같아야 한다.
// 그러나 소수점 문제로 인하여 정확히 같아지지 않을 경우가 발생한다.
//require(reqedHex == atx2HexWithBonus(toFund, bonus) );
} else {
toFund = fundingAmt;
reFund = 0;
}
require(fundingAmt >= toFund);
require(toFund > 0);
// pushInvestorList
if(atxInvestorFunds[_from] == 0x0) {
atxInvestors.push(_from);
}
atxInvestorFunds[_from] = add(atxInvestorFunds[_from], toFund);
/* atxFunded = add(atxFunded, toFund); */
hexToken.generateTokens(_from, reqedHex);
// 현재 시점에서
// HEXCrowdSale 이 수신한 ATX 는
// 아직 HEXCrowdSale 계정의 잔액에 반영되지 않았다....
// _amount 는 아직 this 의 잔액에 반영되지 않았기때문에,
// 이것을 vault 로 전송할 수도 없고,
// 잔액을 되돌릴 수도 없다.
if(reFund > 0) {
//atxToken.transfer(_from, reFund);
if(atxChanges[_from] == 0x0) {
atxChangeAddrs.push(_from);
}
atxChanges[_from] = add(atxChanges[_from], reFund);
}
// 현재 시점에서
// HEXCrowdSale 이 수신한 ATX 는
// 아직 HEXCrowdSale 계정의 잔액에 반영되지 않았다....
// 그래서 vault 로 전송할 수가 없다.
//if( atxToken.transfer( address(vault), toFund) ) {
//vault.atxDeposit(_from, toFund);
//}
emit SaleToken(msg.sender, _from, 1, toFund, reqedHex);
return true;
}
function finish() public onlyOwner {
require(!isFinalized);
returnATXChanges();
if(minReached()) {
//vault.close();
require(vaultWallets.length == 31);
uint eachATX = div(atxToken.balanceOf(address(this)), vaultWallets.length);
for(uint idx = 0; idx < vaultWallets.length; idx++) {
// atx
atxToken.transfer(vaultWallets[idx], eachATX);
}
// atx remained
if(atxToken.balanceOf(address(this)) > 0) {
atxToken.transfer(vaultWallets[vaultWallets.length - 1], atxToken.balanceOf(address(this)));
}
// ether
//if(address(this).balance > 0) {
vaultWallets[vaultWallets.length - 1].transfer( address(this).balance );
//}
require(memWallets.length == 6);
hexToken.generateTokens(memWallets[0], 14e26); // airdrop
hexToken.generateTokens(memWallets[1], 84e25); // team locker
hexToken.generateTokens(memWallets[2], 84e25); // advisors locker
hexToken.generateTokens(memWallets[3], 80e25); // healthdata mining
hexToken.generateTokens(memWallets[4], 92e25); // marketing
hexToken.generateTokens(memWallets[5], 80e25); // reserved
//hexToken.enableTransfers(true);
} else {
//vault.enableRefunds();
}
hexToken.finishGenerating();
hexToken.changeController(hexControllerAddr);
isFinalized = true;
emit SaleFinished();
}
function maxReached() public view returns (bool) {
return (hexToken.totalSupply() >= maxHEXCap);
}
function minReached() public view returns (bool) {
return (hexToken.totalSupply() >= minHEXCap);
}
function addPeriod(uint256 _start, uint256 _end) public onlyOwner {
require(now < _start && _start < _end);
if (periods.length != 0) {
//require(sub(_endTime, _startTime) <= 7 days);
require(periods[periods.length - 1].endTime < _start);
}
Period memory newPeriod;
newPeriod.startTime = _start;
newPeriod.endTime = _end;
newPeriod.bonus = 0;
if(periods.length == 0) {
newPeriod.bonus = 50; // Private
}
else if(periods.length == 1) {
newPeriod.bonus = 30; // pre
}
else if(periods.length == 2) {
newPeriod.bonus = 20; // crowd 1
}
else if (periods.length == 3) {
newPeriod.bonus = 15; // crowd 2
}
else if (periods.length == 4) {
newPeriod.bonus = 10; // crowd 3
}
else if (periods.length == 5) {
newPeriod.bonus = 5; // crowd 4
}
periods.push(newPeriod);
}
function getPeriodBonus() public view returns (uint256) {
bool nowOnSale;
uint256 currentPeriod;
for (uint i = 0; i < periods.length; i++) {
if (periods[i].startTime <= now && now <= periods[i].endTime) {
nowOnSale = true;
currentPeriod = i;
break;
}
}
require(nowOnSale);
return periods[currentPeriod].bonus;
}
function eth2HexWithBonus(uint256 _eth, uint256 bonus) public view returns(uint256) {
uint basic = mul(_eth, ethRate);
return div(mul(basic, add(bonus, 100)), 100);
//return add(basic, div(mul(basic, bonus), 100));
}
function hex2EthWithBonus(uint256 _hex, uint256 bonus) public view returns(uint256) {
return div(mul(_hex, 100), mul(ethRate, add(100, bonus)));
//return div(_hex, mul(ethRate, add(1, div(bonus,100))));
}
function atx2HexWithBonus(uint256 _atx, uint256 bonus) public view returns(uint256) {
uint basic = mul(_atx, atxRate);
return div(mul(basic, add(bonus, 100)), 100);
//return add(basic, div(mul(basic, bonus), 100));
}
function hex2AtxWithBonus(uint256 _hex, uint256 bonus) public view returns(uint256) {
return div(mul(_hex, 100), mul(atxRate, add(100, bonus)));
//return div(_hex, mul(atxRate, add(1, div(bonus,100))));
}
function onSale() public view returns (bool) {
bool nowOnSale;
// Except Private Sale...
for (uint i = 1; i < periods.length; i++) {
if (periods[i].startTime <= now && now <= periods[i].endTime) {
nowOnSale = true;
break;
}
}
return nowOnSale;
}
function atxChangeAddrCount() public view returns(uint256) {
return atxChangeAddrs.length;
}
function returnATXChanges() public onlyOwner {
//require(atxChangeAddrs.length > 0);
for(uint256 i=0; i<atxChangeAddrs.length; i++) {
if(atxChanges[atxChangeAddrs[i]] > 0) {
if( atxToken.transfer(atxChangeAddrs[i], atxChanges[atxChangeAddrs[i]]) ) {
atxChanges[atxChangeAddrs[i]] = 0x0;
}
}
}
}
//
// Safety Methods
function claimTokens(address _claimToken) public onlyOwner {
if (hexToken.controller() == address(this)) {
hexToken.claimTokens(_claimToken);
}
if (_claimToken == 0x0) {
owner.transfer(address(this).balance);
return;
}
ERC20Basic claimToken = ERC20Basic(_claimToken);
uint256 balance = claimToken.balanceOf( address(this) );
claimToken.transfer(owner, balance);
emit ClaimedTokens(_claimToken, owner, balance);
}
//
// Event
event SaleToken(address indexed _sender, address indexed _investor, uint256 indexed _fundType, uint256 _toFund, uint256 _hexTokens);
event ClaimedTokens(address indexed _claimToken, address indexed owner, uint256 balance);
event SaleFinished();
}
|
require(atxChangeAddrs.length > 0);
|
function returnATXChanges() public onlyOwner {
for(uint256 i=0; i<atxChangeAddrs.length; i++) {
if(atxChanges[atxChangeAddrs[i]] > 0) {
if( atxToken.transfer(atxChangeAddrs[i], atxChanges[atxChangeAddrs[i]]) ) {
atxChanges[atxChangeAddrs[i]] = 0x0;
}
}
}
}
| 12,738,894 |
pragma solidity ^0.4.24;
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
// @title SafeMath: overflow/underflow checks
// @notice Math operations with safety checks that throw on error
library SafeMath {
// @notice Multiplies two numbers, throws on overflow.
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
// @notice 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;
}
// @notice 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;
}
// @notice Adds two numbers, throws on overflow.
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
// @notice Returns fractional amount
function getFractionalAmount(uint256 _amount, uint256 _percentage)
internal
pure
returns (uint256) {
return div(mul(_amount, _percentage), 100);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface ERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _who) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/// @dev The token controller contract must implement these functions
interface ITokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) external payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) external returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) external returns(bool);
}
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina (with modifications by Peter Phillips)
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController {
require(msg.sender == controller);
_;
}
address public controller;
constructor() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController public {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(
address from,
uint256 _amount,
address _token,
bytes _data
) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
using SafeMath for uint;
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = "MMT_0.1"; //An arbitrary versioning scheme
ERC20 public erc20; //The token that is distributed by this contract (0x0 if Ether)
// @notice Token Income Information
uint constant scalingFactor = 1e32;//Value to scale numbers to avoid rounding issues
uint public valuePerToken; //The current value each token has received in funding
uint public assetIncome; //The amount of income this contract has received
uint public assetIncomeIssued; //The amount of income that has been withdrawn
mapping (address => uint) public incomeOwed; //The income owed for each address
mapping (address => uint) public previousValuePerToken;//The value of each token last time the address has withdrawn
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
constructor(
MiniMeTokenFactory _tokenFactory,
MiniMeToken _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled,
address _erc20Address
) public
{
tokenFactory = _tokenFactory;
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = _parentToken;
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
if(_erc20Address != address(0)){
erc20 = ERC20(_erc20Address); //Set the address of the ERC20 token that will be issued as dividends
}
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount)
public
updateIncomeClaimed(msg.sender)
updateIncomeClaimed(_to)
returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount)
public
updateIncomeClaimed(_from)
updateIncomeClaimed(_to)
returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount)
return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
uint256 previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onTransfer(_from, _to, _amount) == true);
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint256 previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo.add(_amount));
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
// Adding the ` == true` makes the linter shut up so...
require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true);
}
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData)
public
updateIncomeClaimed(msg.sender)
updateIncomeClaimed(_spender)
returns (bool success) {
require(approve(_spender, _amount));
_spender.receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Distribution methods
////////////////
// @notice token holders can withdraw income here
function withdraw()
external
updateIncomeClaimed(msg.sender)
returns (bool) {
uint amount = incomeOwed[msg.sender].div(scalingFactor);
delete incomeOwed[msg.sender];
assetIncomeIssued = assetIncomeIssued.add(amount);
if(address(erc20) == address(0)){
msg.sender.transfer(amount);
} else {
require(erc20.transfer(msg.sender, amount));
}
emit LogIncomeCollected(msg.sender, amount);
return true;
}
// @notice assets can send their income here to be collected by investors
function issueDividends(uint256 _amount)
payable
external
returns (bool) {
require(_amount > 0, "Cannot send zero");
if(address(erc20) == address(0)){
require(msg.value == _amount);
} else {
require(msg.value == 0);
require(erc20.transferFrom(msg.sender, address(this), _amount), "Transfer failed");
}
assetIncome = assetIncome.add(_amount);
valuePerToken = valuePerToken.add(_amount.mul(scalingFactor).div(totalSupply()));
emit LogIncomeReceived(msg.sender, _amount);
return true;
}
//In case a investor transferred a token directly to this contract
//anyone can run this function to clean up the balances
//and distribute the difference to token holders
function checkForTransfers()
external {
uint bookBalance = assetIncome.sub(assetIncomeIssued);
uint actualBalance;
if(address(erc20) == address(0)){
actualBalance = address(this).balance;
} else {
actualBalance = erc20.balanceOf(this);
}
uint diffBalance = actualBalance.sub(bookBalance);
if(diffBalance > 0){
//Update value per token
valuePerToken = valuePerToken.add(diffBalance.mul(scalingFactor).div(totalSupply()));
assetIncome = assetIncome.add(diffBalance);
}
emit LogCheckBalance(diffBalance);
}
// ------------------------------------------------------------------------
// View functions
// ------------------------------------------------------------------------
// @notice Calculates how much more income is owed to investor since last calculation
function collectLatestPayments(address _investor)
private
view
returns (uint) {
uint valuePerTokenDifference = valuePerToken.sub(previousValuePerToken[_investor]);
return valuePerTokenDifference.mul(balanceOf(_investor));
}
// @notice Calculates how much wei investor is owed. (points + incomeOwed) / 10**32
function getAmountOwed(address _investor)
public
view
returns (uint) {
return (collectLatestPayments(_investor).add(incomeOwed[_investor]).div(scalingFactor));
}
// @notice returns ERC20 token. Returns null if the token uses Ether.
function getERC20()
external
view
returns(address){
return address(erc20);
}
// ------------------------------------------------------------------------
// Modifiers
// ------------------------------------------------------------------------
// Updates the amount owed to investor while holding tokenSupply
// @dev must be called before transfering tokens
modifier updateIncomeClaimed(address _investor) {
incomeOwed[_investor] = incomeOwed[_investor].add(collectLatestPayments(_investor));
previousValuePerToken[_investor] = valuePerToken;
_;
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled,
address _erc20Address
) public returns(MiniMeToken)
{
uint256 snapshot = _snapshotBlock == 0 ? block.number.sub(1) : _snapshotBlock;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
snapshot,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled,
_erc20Address
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
emit NewCloneToken(address(cloneToken), snapshot);
return cloneToken;
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount)
onlyController
updateIncomeClaimed(_owner)
public
returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply.add(_amount) >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo.add(_amount) >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount));
updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount));
emit Transfer(0, _owner, _amount);
return true;
}
// @notice Removing this function as we don't want to destroy investors' assets
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
/*
function destroyTokens(address _owner, uint _amount)
onlyController
updateIncomeClaimed(_owner)
public
returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, 0, _amount);
return true;
}
*/
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) onlyController public {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) {
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock)
return checkpoints[checkpoints.length.sub(1)].value;
if (_block < checkpoints[0].fromBlock)
return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length.sub(1);
while (max > min) {
uint mid = (max.add(min.add(1))).sub(2);
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid.sub(1);
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length.sub(1)];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0)
return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
// Fallback function: receives Ether and updates income ledger
function ()
payable
external {
require(address(erc20) == address(0));
assetIncome = assetIncome.add(msg.value);
valuePerToken = valuePerToken.add(msg.value.mul(scalingFactor).div(totalSupply()));
emit LogIncomeReceived(msg.sender, msg.value);
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract. (Except the token used for profit distribution)
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) onlyController public {
require(_token != address(erc20));
if (_token == 0x0) {
controller.transfer(address(this).balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
emit ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event LogIncomeReceived(address indexed _sender, uint _paymentAmount);
event LogIncomeCollected(address _address, uint _amount);
event LogCheckBalance(uint _difference);
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
MiniMeToken _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled,
address _erc20Address
) public returns (MiniMeToken)
{
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled,
_erc20Address
);
newToken.changeController(msg.sender);
emit NewToken(address(newToken), address(_parentToken), _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled, _erc20Address);
return newToken;
}
event NewToken(address token, address parent, uint block, string name, uint decimals, string symbol, bool transfersEnabled, address erc20);
}
|
Removing this function as we don't want to destroy investors' assets Burns `_amount` tokens from `_owner` _owner The address that will lose the tokens _amount The quantity of tokens to burn return True if the tokens are burned correctly
|
function destroyTokens(address _owner, uint _amount)
onlyController
updateIncomeClaimed(_owner)
public
returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, 0, _amount);
return true;
}
| 1,492,707 |
./partial_match/1/0xbc446fA602Ece8A4fD163cD356B598ef1C8aaE4E/sources/lib/core-cash/src/core/engines/mixins/OptionTransferable.sol
|
Transfers collateral to another account. _subAccount subaccount that will be update in place/ decode parameters update the account in state
|
function _transferCollateral(address _subAccount, bytes calldata _data) internal virtual {
(uint80 amount, address to, uint8 collateralId) = abi.decode(_data, (uint80, address, uint8));
_removeCollateralFromAccount(_subAccount, collateralId, amount);
_addCollateralToAccount(to, collateralId, amount);
emit CollateralTransferred(_subAccount, to, collateralId, amount);
}
| 4,192,694 |
pragma solidity ^0.4.18;
// File: contracts-origin/AetherAccessControl.sol
/// @title A facet of AetherCore that manages special access privileges.
/// @dev See the AetherCore contract documentation to understand how the various contract facets are arranged.
contract AetherAccessControl {
// This facet controls access control for Laputa. 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 AetherCore constructor.
//
// - The CFO: The CFO can withdraw funds from AetherCore and its auction contracts.
//
// - The COO: The COO can release properties to auction.
//
// 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) public 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) public 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) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function withdrawBalance() external onlyCFO {
cfoAddress.transfer(this.balance);
}
/*** 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() public 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.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
// File: contracts-origin/AetherBase.sol
/// @title Base contract for Aether. Holds all common structs, events and base variables.
/// @author Project Aether (https://www.aether.city)
/// @dev See the PropertyCore contract documentation to understand how the various contract facets are arranged.
contract AetherBase is AetherAccessControl {
/*** EVENTS ***/
/// @dev The Construct event is fired whenever a property updates.
event Construct (
address indexed owner,
uint256 propertyId,
PropertyClass class,
uint8 x,
uint8 y,
uint8 z,
uint8 dx,
uint8 dz,
string data
);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every
/// time a property ownership is assigned.
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/*** DATA ***/
enum PropertyClass { DISTRICT, BUILDING, UNIT }
/// @dev The main Property struct. Every property in Aether is represented
/// by a variant of this structure.
struct Property {
uint32 parent;
PropertyClass class;
uint8 x;
uint8 y;
uint8 z;
uint8 dx;
uint8 dz;
}
/*** STORAGE ***/
/// @dev Ensures that property occupies unique part of the universe.
bool[100][100][100] public world;
/// @dev An array containing the Property struct for all properties in existence. The ID
/// of each property is actually an index into this array.
Property[] properties;
/// @dev An array containing the district addresses in existence.
uint256[] districts;
/// @dev A measure of world progression.
uint256 public progress;
/// @dev The fee associated with constructing a unit property.
uint256 public unitCreationFee = 0.05 ether;
/// @dev Keeps track whether updating data is paused.
bool public updateEnabled = true;
/// @dev A mapping from property IDs to the address that owns them. All properties have
/// some valid owner address, even gen0 properties are created with a non-zero owner.
mapping (uint256 => address) public propertyIndexToOwner;
/// @dev A mapping from property IDs to the data that is stored on them.
mapping (uint256 => string) public propertyIndexToData;
/// @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 Mappings between property nodes.
mapping (uint256 => uint256) public districtToBuildingsCount;
mapping (uint256 => uint256[]) public districtToBuildings;
mapping (uint256 => uint256) public buildingToUnitCount;
mapping (uint256 => uint256[]) public buildingToUnits;
/// @dev A mapping from building propertyId to unit construction privacy.
mapping (uint256 => bool) public buildingIsPublic;
/// @dev A mapping from PropertyIDs to an address that has been approved to call
/// transferFrom(). Each Property can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public propertyIndexToApproved;
/// @dev Assigns ownership of a specific Property to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// since the number of properties is capped to 2^32
// there is no way to overflow this
ownershipTokenCount[_to]++;
// transfer ownership
propertyIndexToOwner[_tokenId] = _to;
// When creating new properties _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete propertyIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
function _createUnit(
uint256 _parent,
uint256 _x,
uint256 _y,
uint256 _z,
address _owner
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_y == uint256(uint8(_y)));
require(_z == uint256(uint8(_z)));
require(!world[_x][_y][_z]);
world[_x][_y][_z] = true;
return _createProperty(
_parent,
PropertyClass.UNIT,
_x,
_y,
_z,
0,
0,
_owner
);
}
function _createBuilding(
uint256 _parent,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _dx,
uint256 _dz,
address _owner,
bool _public
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_y == uint256(uint8(_y)));
require(_z == uint256(uint8(_z)));
require(_dx == uint256(uint8(_dx)));
require(_dz == uint256(uint8(_dz)));
// Looping over world space.
for(uint256 i = 0; i < _dx; i++) {
for(uint256 j = 0; j <_dz; j++) {
if (world[_x + i][0][_z + j]) {
revert();
}
world[_x + i][0][_z + j] = true;
}
}
uint propertyId = _createProperty(
_parent,
PropertyClass.BUILDING,
_x,
_y,
_z,
_dx,
_dz,
_owner
);
districtToBuildingsCount[_parent]++;
districtToBuildings[_parent].push(propertyId);
buildingIsPublic[propertyId] = _public;
return propertyId;
}
function _createDistrict(
uint256 _x,
uint256 _z,
uint256 _dx,
uint256 _dz
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_z == uint256(uint8(_z)));
require(_dx == uint256(uint8(_dx)));
require(_dz == uint256(uint8(_dz)));
uint propertyId = _createProperty(
districts.length,
PropertyClass.DISTRICT,
_x,
0,
_z,
_dx,
_dz,
cooAddress
);
districts.push(propertyId);
return propertyId;
}
/// @dev An internal method that creates a new property 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 Construct event
/// and a Transfer event.
function _createProperty(
uint256 _parent,
PropertyClass _class,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _dx,
uint256 _dz,
address _owner
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_y == uint256(uint8(_y)));
require(_z == uint256(uint8(_z)));
require(_dx == uint256(uint8(_dx)));
require(_dz == uint256(uint8(_dz)));
require(_parent == uint256(uint32(_parent)));
require(uint256(_class) <= 3);
Property memory _property = Property({
parent: uint32(_parent),
class: _class,
x: uint8(_x),
y: uint8(_y),
z: uint8(_z),
dx: uint8(_dx),
dz: uint8(_dz)
});
uint256 _tokenId = properties.push(_property) - 1;
// It's never going to happen, 4 billion properties is A LOT, but
// let's just be 100% sure we never let this happen.
require(_tokenId <= 4294967295);
Construct(
_owner,
_tokenId,
_property.class,
_property.x,
_property.y,
_property.z,
_property.dx,
_property.dz,
""
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, _tokenId);
return _tokenId;
}
/// @dev Computing height of a building with respect to city progression.
function _computeHeight(
uint256 _x,
uint256 _z,
uint256 _height
) internal view returns (uint256) {
uint256 x = _x < 50 ? 50 - _x : _x - 50;
uint256 z = _z < 50 ? 50 - _z : _z - 50;
uint256 distance = x > z ? x : z;
if (distance > progress) {
return 1;
}
uint256 scale = 100 - (distance * 100) / progress ;
uint256 height = 2 * progress * _height * scale / 10000;
return height > 0 ? height : 1;
}
/// @dev Convenience function to see if this building has room for a unit.
function canCreateUnit(uint256 _buildingId)
public
view
returns(bool)
{
Property storage _property = properties[_buildingId];
if (_property.class == PropertyClass.BUILDING &&
(buildingIsPublic[_buildingId] ||
propertyIndexToOwner[_buildingId] == msg.sender)
) {
uint256 totalVolume = _property.dx * _property.dz *
(_computeHeight(_property.x, _property.z, _property.y) - 1);
uint256 totalUnits = buildingToUnitCount[_buildingId];
return totalUnits < totalVolume;
}
return false;
}
/// @dev This internal function skips all validation checks. Ensure that
// canCreateUnit() is required before calling this method.
function _createUnitHelper(uint256 _buildingId, address _owner)
internal
returns(uint256)
{
// Grab a reference to the property in storage.
Property storage _property = properties[_buildingId];
uint256 totalArea = _property.dx * _property.dz;
uint256 index = buildingToUnitCount[_buildingId];
// Calculate next location.
uint256 y = index / totalArea + 1;
uint256 intermediate = index % totalArea;
uint256 z = intermediate / _property.dx;
uint256 x = intermediate % _property.dx;
uint256 unitId = _createUnit(
_buildingId,
x + _property.x,
y,
z + _property.z,
_owner
);
buildingToUnitCount[_buildingId]++;
buildingToUnits[_buildingId].push(unitId);
// Return the new unit's ID.
return unitId;
}
/// @dev Update allows for setting a building privacy.
function updateBuildingPrivacy(uint _tokenId, bool _public) public {
require(propertyIndexToOwner[_tokenId] == msg.sender);
buildingIsPublic[_tokenId] = _public;
}
/// @dev Update allows for setting the data associated to a property.
function updatePropertyData(uint _tokenId, string _data) public {
require(updateEnabled);
address _owner = propertyIndexToOwner[_tokenId];
require(msg.sender == _owner);
propertyIndexToData[_tokenId] = _data;
Property memory _property = properties[_tokenId];
Construct(
_owner,
_tokenId,
_property.class,
_property.x,
_property.y,
_property.z,
_property.dx,
_property.dz,
_data
);
}
}
// File: contracts-origin/ERC721Draft.sol
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed 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) public view returns (string infoUrl);
}
// File: contracts-origin/AetherOwnership.sol
/// @title The facet of the Aether core contract that manages ownership, ERC-721 (draft) compliant.
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the PropertyCore contract documentation to understand how the various contract facets are arranged.
contract AetherOwnership is AetherBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public name = "Aether";
string public symbol = "AETH";
function implementsERC721() public pure returns (bool)
{
return true;
}
// 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 Property.
/// @param _claimant the address we are validating against.
/// @param _tokenId property id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return propertyIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Property.
/// @param _claimant the address we are confirming property is approved for.
/// @param _tokenId property id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return propertyIndexToApproved[_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 Properties on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
propertyIndexToApproved[_tokenId] = _approved;
}
/// @dev Transfers a property owned by this contract to the specified address.
/// Used to rescue lost properties. (There is no "proper" flow where this contract
/// should be the owner of any Property. This function exists for us to reassign
/// the ownership of Properties that users may have accidentally sent to our address.)
/// @param _propertyId - ID of property
/// @param _recipient - Address to send the property to
function rescueLostProperty(uint256 _propertyId, address _recipient) public onlyCOO whenNotPaused {
require(_owns(this, _propertyId));
_transfer(this, _recipient, _propertyId);
}
/// @notice Returns the number of Properties 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 Property to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// Laputa specifically) or your Property may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Property to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// You can only send your own property.
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 Property 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 Property that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Property 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 Property to be transfered.
/// @param _to The address that should take ownership of the Property. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Property to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
// 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 Properties currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return properties.length;
}
function totalDistrictSupply() public view returns(uint count) {
return districts.length;
}
/// @notice Returns the address currently assigned ownership of a given Property.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = propertyIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all Property IDs assigned to an address.
/// @param _owner The owner whose Properties 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 totalProperties = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all properties have IDs starting at 1 and increasing
// sequentially up to the totalProperties count.
uint256 tokenId;
for (tokenId = 1; tokenId <= totalProperties; tokenId++) {
if (propertyIndexToOwner[tokenId] == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
}
// File: contracts-origin/Auction/ClockAuctionBase.sol
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
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 DON'T give me your money.
function() external {}
// Modifiers to check that inputs can be safely stored with a certain
// number of bits. We use constants and multiple modifiers to save gas.
modifier canBeStoredWith64Bits(uint256 _value) {
require(_value <= 18446744073709551615);
_;
}
modifier canBeStoredWith128Bits(uint256 _value) {
require(_value < 340282366920938463463374607431768211455);
_;
}
/// @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;
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);
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 incoming bid is higher than 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);
}
// Tell the world!
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;
}
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @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 returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
// File: contracts-origin/Auction/ClockAuction.sol
/// @title Clock auction for non-fungible tokens.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @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 {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.implementsERC721());
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
);
nftAddress.transfer(this.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
)
public
whenNotPaused
canBeStoredWith128Bits(_startingPrice)
canBeStoredWith128Bits(_endingPrice)
canBeStoredWith64Bits(_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)
public
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)
public
{
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
public
{
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)
public
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)
public
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
// File: contracts-origin/Auction/AetherClockAuction.sol
/// @title Clock auction modified for sale of property
contract AetherClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isAetherClockAuction = true;
// Tracks last 5 sale price of gen0 property sales
uint256 public saleCount;
uint256[5] public lastSalePrices;
// Delegate constructor
function AetherClockAuction(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
)
public
canBeStoredWith128Bits(_startingPrice)
canBeStoredWith128Bits(_endingPrice)
canBeStoredWith64Bits(_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)
public
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
lastSalePrices[saleCount % 5] = price;
saleCount++;
}
}
function averageSalePrice() public view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastSalePrices[i];
}
return sum / 5;
}
}
// File: contracts-origin/AetherAuction.sol
/// @title Handles creating auctions for sale and siring of properties.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract AetherAuction is AetherOwnership{
/// @dev The address of the ClockAuction contract that handles sales of Aether. This
/// same contract handles both peer-to-peer sales as well as the gen0 sales which are
/// initiated every 15 minutes.
AetherClockAuction public saleAuction;
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) public onlyCEO {
AetherClockAuction candidateContract = AetherClockAuction(_address);
// NOTE: verify that a contract is what we expect
require(candidateContract.isAetherClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Put a property up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _propertyId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
public
whenNotPaused
{
// Auction contract checks input sizes
// If property is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _propertyId));
_approve(_propertyId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the property.
saleAuction.createAuction(
_propertyId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Transfers the balance of the sale auction contract
/// to the AetherCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCOO {
saleAuction.withdrawBalance();
}
}
// File: contracts-origin/AetherConstruct.sol
// Auction wrapper functions
/// @title all functions related to creating property
contract AetherConstruct is AetherAuction {
uint256 public districtLimit = 16;
uint256 public startingPrice = 1 ether;
uint256 public auctionDuration = 1 days;
/// @dev Units can be contructed within public and owned buildings.
function createUnit(uint256 _buildingId)
public
payable
returns(uint256)
{
require(canCreateUnit(_buildingId));
require(msg.value >= unitCreationFee);
if (msg.value > unitCreationFee)
msg.sender.transfer(msg.value - unitCreationFee);
uint256 propertyId = _createUnitHelper(_buildingId, msg.sender);
return propertyId;
}
/// @dev Creation of unit properties. Only callable by COO
function createUnitOmni(
uint32 _buildingId,
address _owner
)
public
onlyCOO
{
if (_owner == address(0)) {
_owner = cooAddress;
}
require(canCreateUnit(_buildingId));
_createUnitHelper(_buildingId, _owner);
}
/// @dev Creation of building properties. Only callable by COO
function createBuildingOmni(
uint32 _districtId,
uint8 _x,
uint8 _y,
uint8 _z,
uint8 _dx,
uint8 _dz,
address _owner,
bool _open
)
public
onlyCOO
{
if (_owner == address(0)) {
_owner = cooAddress;
}
_createBuilding(_districtId, _x, _y, _z, _dx, _dz, _owner, _open);
}
/// @dev Creation of district properties, up to a limit. Only callable by COO
function createDistrictOmni(
uint8 _x,
uint8 _z,
uint8 _dx,
uint8 _dz
)
public
onlyCOO
{
require(districts.length < districtLimit);
_createDistrict(_x, _z, _dx, _dz);
}
/// @dev Creates a new property with the given details and
/// creates an auction for it. Only callable by COO.
function createBuildingAuction(
uint32 _districtId,
uint8 _x,
uint8 _y,
uint8 _z,
uint8 _dx,
uint8 _dz,
bool _open
) public onlyCOO {
uint256 propertyId = _createBuilding(_districtId, _x, _y, _z, _dx, _dz, address(this), _open);
_approve(propertyId, saleAuction);
saleAuction.createAuction(
propertyId,
_computeNextPrice(),
0,
auctionDuration,
address(this)
);
}
/// @dev Updates the minimum payment required for calling createUnit(). Can only
/// be called by the COO address.
function setUnitCreationFee(uint256 _value) public onlyCOO {
unitCreationFee = _value;
}
/// @dev Update world progression factor allowing for buildings to grow taller
// as the city expands. Only callable by COO.
function setProgress(uint256 _progress) public onlyCOO {
require(_progress <= 100);
require(_progress > progress);
progress = _progress;
}
/// @dev Set property data updates flag. Only callable by COO.
function setUpdateState(bool _updateEnabled) public onlyCOO {
updateEnabled = _updateEnabled;
}
/// @dev Computes the next auction starting price, given the average of the past
/// 5 prices + 50%.
function _computeNextPrice() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageSalePrice();
// sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1).
require(avePrice < 340282366920938463463374607431768211455);
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < startingPrice) {
nextPrice = startingPrice;
}
return nextPrice;
}
}
// File: contracts-origin/AetherCore.sol
/// @title Aether: A city on the Ethereum blockchain.
/// @author Axiom Zen (https://www.axiomzen.co)
contract AetherCore is AetherConstruct {
// This is the main Aether contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. 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 property ownership.
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of Aether. 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:
//
// - AetherBase: 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.
//
// - AetherAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - AetherOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - AetherAuction: Here we have the public methods for auctioning or bidding on property.
// The actual auction functionality is handled in two sibling contracts while auction
// creation and bidding is mostly mediated through this facet of the core contract.
//
// - AetherConstruct: This final facet contains the functionality we use for creating new gen0 cats.
// the community is new).
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main Aether smart contract instance.
function AetherCore() 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;
}
/// @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) public onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
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 property.
/// @param _id The ID of the property of interest.
function getProperty(uint256 _id)
public
view
returns (
uint32 parent,
uint8 class,
uint8 x,
uint8 y,
uint8 z,
uint8 dx,
uint8 dz,
uint8 height
) {
Property storage property = properties[_id];
parent = uint32(property.parent);
class = uint8(property.class);
height = uint8(property.y);
if (property.class == PropertyClass.BUILDING) {
y = uint8(_computeHeight(property.x, property.z, property.y));
} else {
y = uint8(property.y);
}
x = uint8(property.x);
z = uint8(property.z);
dx = uint8(property.dx);
dz = uint8(property.dz);
}
/// @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.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
}
|
Looping over world space.
|
function _createBuilding(
uint256 _parent,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _dx,
uint256 _dz,
address _owner,
bool _public
)
internal
returns (uint)
{
require(_x == uint256(uint8(_x)));
require(_y == uint256(uint8(_y)));
require(_z == uint256(uint8(_z)));
require(_dx == uint256(uint8(_dx)));
require(_dz == uint256(uint8(_dz)));
for(uint256 i = 0; i < _dx; i++) {
for(uint256 j = 0; j <_dz; j++) {
if (world[_x + i][0][_z + j]) {
revert();
}
world[_x + i][0][_z + j] = true;
}
}
uint propertyId = _createProperty(
_parent,
PropertyClass.BUILDING,
_x,
_y,
_z,
_dx,
_dz,
_owner
);
districtToBuildingsCount[_parent]++;
districtToBuildings[_parent].push(propertyId);
buildingIsPublic[propertyId] = _public;
return propertyId;
}
| 1,090,819 |
./full_match/1/0xff42D75F5a9e5b72bc7d51708BEaC4F2E3aC8569/sources/@unrealaccelerator/contracts/packages/CreatorERC721/CreatorERC721Mintable.sol
|
Returns the metadata for a given token id/
|
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "Nonexistent token");
return string(abi.encodePacked(basePrefix, _creationCIDList[tokenId]));
}
| 9,765,530 |
pragma solidity ^0.6.2;
// SPDX-License-Identifier: MIT
abstract contract Context {
function _MSGSENDER583() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA879() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
interface IERC20 {
function TOTALSUPPLY430() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF616(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER244(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE387(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE425(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM381(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER617(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL460(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// SPDX-License-Identifier: MIT
library SafeMath {
function ADD135(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB321(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB321(a, b, "SafeMath: subtraction overflow");
}
function SUB321(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL733(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV136(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV136(a, b, "SafeMath: division by zero");
}
function DIV136(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD593(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD593(a, b, "SafeMath: modulo by zero");
}
function MOD593(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
library Address {
function ISCONTRACT469(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function SENDVALUE193(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL340(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL340(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL340(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE922(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE944(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE944(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE944(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE922(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE922(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT469(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME100() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL131() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS904() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY430() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF616(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER244(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER73(_MSGSENDER583(), recipient, amount);
return true;
}
function ALLOWANCE387(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE425(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, amount);
return true;
}
function TRANSFERFROM381(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER73(sender, recipient, amount);
_APPROVE319(sender, _MSGSENDER583(), _allowances[sender][_MSGSENDER583()].SUB321(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE808(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].ADD135(addedValue));
return true;
}
function DECREASEALLOWANCE515(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE319(_MSGSENDER583(), spender, _allowances[_MSGSENDER583()][spender].SUB321(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER73(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER129(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB321(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD135(amount);
emit TRANSFER617(sender, recipient, amount);
}
function _MINT517(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER129(address(0), account, amount);
_totalSupply = _totalSupply.ADD135(amount);
_balances[account] = _balances[account].ADD135(amount);
emit TRANSFER617(address(0), account, amount);
}
function _BURN171(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER129(account, address(0), amount);
_balances[account] = _balances[account].SUB321(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB321(amount);
emit TRANSFER617(account, address(0), amount);
}
function _APPROVE319(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL460(owner, spender, amount);
}
function _SETUPDECIMALS874(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
// SPDX-License-Identifier: MIT
abstract contract ERC20Capped is ERC20 {
uint256 private _cap;
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
function CAP360() public view returns (uint256) { //inject NONSTANDARD NAMING
return _cap;
}
function _BEFORETOKENTRANSFER129(address from, address to, uint256 amount) internal virtual override { //inject NONSTANDARD NAMING
super._BEFORETOKENTRANSFER129(from, to, amount);
if (from == address(0)) { // When minting tokens
require(TOTALSUPPLY430().ADD135(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
}
// SPDX-License-Identifier: MIT
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED797(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER583();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED797(address(0), msgSender);
}
function OWNER971() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER607() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER583(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP525() public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED797(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP777(address newOwner) public virtual ONLYOWNER607 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED797(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Router01 {
function FACTORY439() external pure returns (address); //inject NONSTANDARD NAMING
function WETH181() external pure returns (address); //inject NONSTANDARD NAMING
function ADDLIQUIDITY85( //inject NONSTANDARD NAMING
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 ADDLIQUIDITYETH216( //inject NONSTANDARD NAMING
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function REMOVELIQUIDITY344( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function REMOVELIQUIDITYETH742( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function REMOVELIQUIDITYWITHPERMIT491( //inject NONSTANDARD NAMING
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 REMOVELIQUIDITYETHWITHPERMIT317( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENS917( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTTOKENS879( //inject NONSTANDARD NAMING
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPEXACTETHFORTOKENS817(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTETH856(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPEXACTTOKENSFORETH218(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPETHFOREXACTTOKENS998(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function QUOTE315(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING
function GETAMOUNTOUT816(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING
function GETAMOUNTIN684(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING
function GETAMOUNTSOUT241(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
function GETAMOUNTSIN775(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS846( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS1( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS219( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS501( //inject NONSTANDARD NAMING
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS54( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Pair {
event APPROVAL460(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER617(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME100() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL131() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS904() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY430() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF616(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE387(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE425(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM381(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR749() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH945() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES546(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT654(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT786(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN405(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP722( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC303(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY735() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY439() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0934() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1318() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES691() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST150() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST277() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST634() external view returns (uint); //inject NONSTANDARD NAMING
function MINT615(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN664(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP816(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM21(address to) external; //inject NONSTANDARD NAMING
function SYNC269() external; //inject NONSTANDARD NAMING
function INITIALIZE267(address, address) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
event PAIRCREATED762(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO789() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER578() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR592(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS410(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH90() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR614(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO894(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER1(address) external; //inject NONSTANDARD NAMING
}
interface IWETH {
function DEPOSIT145() external payable; //inject NONSTANDARD NAMING
function TRANSFER244(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW78(uint) external; //inject NONSTANDARD NAMING
}
contract CGLB is ERC20Capped, Ownable {
using SafeMath for uint;
address public UNIPAIR;
address public DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
IUniswapV2Router02 public UNIROUTER = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Factory public UNIFACTORY = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
bool public isRunning = false;
bool private liquidityFlag;
uint public constant supplycap690 = (10**4)*(10**18); //inject NONSTANDARD NAMING
uint public constant tokensforinitialliquidity143 = 3*(10**3)*(10**18); //inject NONSTANDARD NAMING
bytes32 public airdropRoot;
mapping (address => bool) public claimedAirdrop;
string public website = "www.cglb.fi";
constructor() public ERC20Capped(supplycap690) ERC20("Cant go lower boys", "CGLB") {
airdropRoot = 0x185065ab3d54b516ee3ed54dc30e04758300a4b41e207cf3ba91715f378d7728;
}
function TRANSFER244(address recipient, uint256 amount) //inject NONSTANDARD NAMING
public override
returns (bool) {
require(msg.sender == UNIPAIR || msg.sender == address(UNIROUTER));
super.TRANSFER244(recipient, amount);
return true;
}
function TRANSFERFROM381(address sender, address recipient, uint256 amount) //inject NONSTANDARD NAMING
public override
returns (bool) {
require(liquidityFlag);
_TRANSFER73(sender, recipient, amount);
return true;
}
function ADDLIQUIDITYTOUNISWAPPAIR951( //inject NONSTANDARD NAMING
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountDAIDesired,
uint256 amountDAImin
) public payable {
require(isRunning);
require(IERC20(DAI).TRANSFERFROM381(msg.sender, address(this), amountDAIDesired));
require(IERC20(DAI).APPROVE425(address(UNIROUTER), amountDAIDesired));
_TRANSFER73(msg.sender, address(this), amountTokenDesired);
liquidityFlag = true;
(uint amountToken, uint amountDAI, uint liquidity) = UNIROUTER.ADDLIQUIDITY85(
address(this),
DAI,
amountTokenDesired,
amountDAIDesired,
amountTokenMin,
amountDAImin,
msg.sender,
now + 10 minutes
);
liquidityFlag = false;
//sends dust back
if (amountTokenDesired - amountToken > 0 ) _TRANSFER73(address(this), msg.sender, amountTokenDesired-amountToken);
if (amountDAIDesired - amountDAI > 0) require(IERC20(DAI).TRANSFER244(msg.sender, amountDAIDesired - amountDAI));
}
function ADDINITIALLIQUIDITYWITHPAIR729() public ONLYOWNER607 { //inject NONSTANDARD NAMING
CREATEUNISWAPPAIR64();
uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this));
require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI));
_MINT517(UNIPAIR, tokensforinitialliquidity143);
IUniswapV2Pair(UNIPAIR).MINT615(msg.sender);
isRunning = true;
}
function ADDINITIALLIQUIDITY209() public ONLYOWNER607 { //inject NONSTANDARD NAMING
uint256 amountDAI = IERC20(DAI).BALANCEOF616(address(this));
require(IERC20(DAI).TRANSFER244(UNIPAIR, amountDAI));
_MINT517(UNIPAIR, tokensforinitialliquidity143);
IUniswapV2Pair(UNIPAIR).MINT615(msg.sender);
isRunning = true;
}
function SETAIRDROPROOT894(bytes32 _root) public ONLYOWNER607 { //inject NONSTANDARD NAMING
airdropRoot = _root;
}
function SETPAIR246(address _pair) public ONLYOWNER607 { //inject NONSTANDARD NAMING
UNIPAIR = _pair;
}
function CREATEUNISWAPPAIR64() internal { //inject NONSTANDARD NAMING
require(UNIPAIR == address(0), "Token: pool already created");
UNIPAIR = UNIFACTORY.CREATEPAIR614(
DAI,
address(this)
);
}
function CHECKPROOF499(bytes memory proof, bytes32 root, bytes32 hash) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 el;
bytes32 h = hash;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
el := mload(add(proof, i))
}
if (h < el) {
h = keccak256(abi.encodePacked(h, el));
} else {
h = keccak256(abi.encodePacked(el, h));
}
}
return h == root;
}
function CLAIMAIRDROP701(bytes memory proof, uint amount) public { //inject NONSTANDARD NAMING
require(!claimedAirdrop[msg.sender]);
bytes32 hash = keccak256(abi.encodePacked(msg.sender, amount));
require(CHECKPROOF499(proof, airdropRoot, hash), "Invalid proof");
claimedAirdrop[msg.sender] = true;
_MINT517(msg.sender, amount);
}
function WITHDRAWERC20742(address token) ONLYOWNER607 public { //inject NONSTANDARD NAMING
uint balance = IERC20(token).BALANCEOF616(address(this));
require(IERC20(token).TRANSFER244(msg.sender, balance));
}
}
|
inject NONSTANDARD NAMING
|
function ALLOWANCE387(address owner, address spender) public view virtual override returns (uint256) {
| 1,820,525 |
/**
*Submitted for verification at Etherscan.io on 2022-03-26
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// 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 (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/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/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 (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: contracts/abc.sol
pragma solidity >=0.7.0 <0.9.0;
contract StrongDragons is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private supply;
string public uriPrefix = "";
string public uriSuffix = ".json";
string public hiddenMetadataUri;
uint256 public cost = 0.05 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmountPerTx = 10 ;
uint256 public maxMintAmount = 150;
bool public paused = true;
bool public revealed = false;
constructor() ERC721("STRONG DRAGONS", "DRGNS") {
setHiddenMetadataUri("ipfs://QmUFTrnvXsuRcdyc5XEizFtxHjyXEYzSywrtyZBAnEXdBe/hidden_Dragon_Metadata.json");
}
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
require(balanceOf(msg.sender) < 150, 'You have reached the max wallet limit');
require(_mintAmount <= maxMintAmount, 'transaction exceeds the maximum amount of tokens');
_;
}
function totalSupply() public view returns (uint256) {
return supply.current();
}
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
require(msg.value >= cost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner {
_mintLoop(_receiver, _mintAmount);
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function setRevealed(bool _state) public onlyOwner {
revealed = _state;
}
function setCost(uint256 _cost) public onlyOwner {
cost = _cost;
}
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner {
maxMintAmountPerTx = _maxMintAmountPerTx;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
function setUriPrefix(string memory _uriPrefix) public onlyOwner {
uriPrefix = _uriPrefix;
}
function setUriSuffix(string memory _uriSuffix) public onlyOwner {
uriSuffix = _uriSuffix;
}
function setPaused(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public onlyOwner {
// This will transfer the remaining contract balance to the owner.
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
function _baseURI() internal view virtual override returns (string memory) {
return uriPrefix;
}
}
|
Required interface of an ERC721 compliant contract./
|
interface IERC721 is IERC165 {
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) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
| 8,025,862 |
./partial_match/42/0x5fd9A1cA8fbbf50D1832F425DC262f263a5FE2F1/sources/FluxAggregator.sol
|
Returns the sorted middle, or the average of the two middle indexed items if the array has an even number of elements. The list passed as an argument isn't modified. This algorithm has expected runtime O(n), but for adversarially chosen inputs the runtime is O(n^2). list The list of elements to compare/
|
function calculate(int256[] memory list) internal pure returns (int256) {
return calculateInplace(copy(list));
}
| 8,935,813 |
// File: contracts/interfaces/IDelegable.sol
pragma solidity ^0.6.10;
interface IDelegable {
function ADDDELEGATE653(address) external; //inject NONSTANDARD NAMING
function ADDDELEGATEBYSIGNATURE882(address, address, uint, uint8, bytes32, bytes32) external; //inject NONSTANDARD NAMING
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
interface IERC20 {
function TOTALSUPPLY521() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF833(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER582(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE506(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE147(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM451(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER75(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL533(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IVat.sol
pragma solidity ^0.6.10;
interface IVat {
// function can(address, address) external view returns (uint);
function HOPE952(address) external; //inject NONSTANDARD NAMING
function NOPE303(address) external; //inject NONSTANDARD NAMING
function LIVE610() external view returns (uint); //inject NONSTANDARD NAMING
function ILKS57(bytes32) external view returns (uint, uint, uint, uint, uint); //inject NONSTANDARD NAMING
function URNS490(bytes32, address) external view returns (uint, uint); //inject NONSTANDARD NAMING
function GEM988(bytes32, address) external view returns (uint); //inject NONSTANDARD NAMING
// function dai(address) external view returns (uint);
function FROB42(bytes32, address, address, address, int, int) external; //inject NONSTANDARD NAMING
function FORK314(bytes32, address, address, int, int) external; //inject NONSTANDARD NAMING
function MOVE289(address, address, uint) external; //inject NONSTANDARD NAMING
function FLUX433(bytes32, address, address, uint) external; //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IWeth.sol
pragma solidity ^0.6.10;
interface IWeth {
function DEPOSIT338() external payable; //inject NONSTANDARD NAMING
function WITHDRAW817(uint) external; //inject NONSTANDARD NAMING
function APPROVE147(address, uint) external returns (bool) ; //inject NONSTANDARD NAMING
function TRANSFER582(address, uint) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM451(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IGemJoin.sol
pragma solidity ^0.6.10;
interface IGemJoin {
function RELY66(address usr) external; //inject NONSTANDARD NAMING
function DENY577(address usr) external; //inject NONSTANDARD NAMING
function CAGE307() external; //inject NONSTANDARD NAMING
function JOIN369(address usr, uint WAD) external; //inject NONSTANDARD NAMING
function EXIT932(address usr, uint WAD) external; //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IDaiJoin.sol
pragma solidity ^0.6.10;
interface IDaiJoin {
function RELY66(address usr) external; //inject NONSTANDARD NAMING
function DENY577(address usr) external; //inject NONSTANDARD NAMING
function CAGE307() external; //inject NONSTANDARD NAMING
function JOIN369(address usr, uint WAD) external; //inject NONSTANDARD NAMING
function EXIT932(address usr, uint WAD) external; //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IPot.sol
pragma solidity ^0.6.10;
interface IPot {
function CHI612() external view returns (uint256); //inject NONSTANDARD NAMING
function PIE445(address) external view returns (uint256); // Not a function, but a public variable. //inject NONSTANDARD NAMING
function RHO514() external returns (uint256); //inject NONSTANDARD NAMING
function DRIP65() external returns (uint256); //inject NONSTANDARD NAMING
function JOIN369(uint256) external; //inject NONSTANDARD NAMING
function EXIT932(uint256) external; //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IChai.sol
pragma solidity ^0.6.10;
interface IChai {
function BALANCEOF833(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER582(address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING
function MOVE289(address src, address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM451(address src, address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE147(address usr, uint wad) external returns (bool); //inject NONSTANDARD NAMING
function DAI858(address usr) external returns (uint wad); //inject NONSTANDARD NAMING
function JOIN369(address dst, uint wad) external; //inject NONSTANDARD NAMING
function EXIT932(address src, uint wad) external; //inject NONSTANDARD NAMING
function DRAW289(address src, uint wad) external; //inject NONSTANDARD NAMING
function PERMIT233(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
function NONCES538(address account) external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/ITreasury.sol
pragma solidity ^0.6.10;
interface ITreasury {
function DEBT715() external view returns(uint256); //inject NONSTANDARD NAMING
function SAVINGS903() external view returns(uint256); //inject NONSTANDARD NAMING
function PUSHDAI613(address user, uint256 dai) external; //inject NONSTANDARD NAMING
function PULLDAI166(address user, uint256 dai) external; //inject NONSTANDARD NAMING
function PUSHCHAI91(address user, uint256 chai) external; //inject NONSTANDARD NAMING
function PULLCHAI479(address user, uint256 chai) external; //inject NONSTANDARD NAMING
function PUSHWETH634(address to, uint256 weth) external; //inject NONSTANDARD NAMING
function PULLWETH548(address to, uint256 weth) external; //inject NONSTANDARD NAMING
function SHUTDOWN178() external; //inject NONSTANDARD NAMING
function LIVE610() external view returns(bool); //inject NONSTANDARD NAMING
function VAT519() external view returns (IVat); //inject NONSTANDARD NAMING
function WETH278() external view returns (IWeth); //inject NONSTANDARD NAMING
function DAI858() external view returns (IERC20); //inject NONSTANDARD NAMING
function DAIJOIN173() external view returns (IDaiJoin); //inject NONSTANDARD NAMING
function WETHJOIN654() external view returns (IGemJoin); //inject NONSTANDARD NAMING
function POT408() external view returns (IPot); //inject NONSTANDARD NAMING
function CHAI326() external view returns (IChai); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IERC2612.sol
// Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/
pragma solidity ^0.6.0;
interface IERC2612 {
function PERMIT233(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
function NONCES538(address owner) external view returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IFYDai.sol
pragma solidity ^0.6.10;
interface IFYDai is IERC20, IERC2612 {
function ISMATURE431() external view returns(bool); //inject NONSTANDARD NAMING
function MATURITY388() external view returns(uint); //inject NONSTANDARD NAMING
function CHI0242() external view returns(uint); //inject NONSTANDARD NAMING
function RATE0398() external view returns(uint); //inject NONSTANDARD NAMING
function CHIGROWTH747() external view returns(uint); //inject NONSTANDARD NAMING
function RATEGROWTH408() external view returns(uint); //inject NONSTANDARD NAMING
function MATURE589() external; //inject NONSTANDARD NAMING
function UNLOCKED182() external view returns (uint); //inject NONSTANDARD NAMING
function MINT176(address, uint) external; //inject NONSTANDARD NAMING
function BURN250(address, uint) external; //inject NONSTANDARD NAMING
function FLASHMINT22(uint, bytes calldata) external; //inject NONSTANDARD NAMING
function REDEEM906(address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING
// function transfer(address, uint) external returns (bool);
// function transferFrom(address, address, uint) external returns (bool);
// function approve(address, uint) external returns (bool);
}
// File: contracts/interfaces/IController.sol
pragma solidity ^0.6.10;
interface IController is IDelegable {
function TREASURY445() external view returns (ITreasury); //inject NONSTANDARD NAMING
function SERIES14(uint256) external view returns (IFYDai); //inject NONSTANDARD NAMING
function SERIESITERATOR268(uint256) external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALSERIES702() external view returns (uint256); //inject NONSTANDARD NAMING
function CONTAINSSERIES982(uint256) external view returns (bool); //inject NONSTANDARD NAMING
function POSTED950(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING
function DEBTFYDAI447(bytes32, uint256, address) external view returns (uint256); //inject NONSTANDARD NAMING
function DEBTDAI877(bytes32, uint256, address) external view returns (uint256); //inject NONSTANDARD NAMING
function TOTALDEBTDAI51(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING
function ISCOLLATERALIZED839(bytes32, address) external view returns (bool); //inject NONSTANDARD NAMING
function INDAI269(bytes32, uint256, uint256) external view returns (uint256); //inject NONSTANDARD NAMING
function INFYDAI474(bytes32, uint256, uint256) external view returns (uint256); //inject NONSTANDARD NAMING
function ERASE227(bytes32, address) external returns (uint256, uint256); //inject NONSTANDARD NAMING
function SHUTDOWN178() external; //inject NONSTANDARD NAMING
function POST95(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING
function WITHDRAW817(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING
function BORROW691(bytes32, uint256, address, address, uint256) external; //inject NONSTANDARD NAMING
function REPAYFYDAI426(bytes32, uint256, address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING
function REPAYDAI460(bytes32, uint256, address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING
}
// File: contracts/interfaces/IDai.sol
pragma solidity ^0.6.10;
interface IDai is IERC20 {
function NONCES538(address user) external view returns (uint256); //inject NONSTANDARD NAMING
function PERMIT233(address holder, address spender, uint256 nonce, uint256 expiry, //inject NONSTANDARD NAMING
bool allowed, uint8 v, bytes32 r, bytes32 s) external;
}
// File: contracts/interfaces/IPool.sol
pragma solidity ^0.6.10;
interface IPool is IDelegable, IERC20, IERC2612 {
function DAI858() external view returns(IERC20); //inject NONSTANDARD NAMING
function FYDAI600() external view returns(IFYDai); //inject NONSTANDARD NAMING
function GETDAIRESERVES173() external view returns(uint128); //inject NONSTANDARD NAMING
function GETFYDAIRESERVES833() external view returns(uint128); //inject NONSTANDARD NAMING
function SELLDAI400(address from, address to, uint128 daiIn) external returns(uint128); //inject NONSTANDARD NAMING
function BUYDAI253(address from, address to, uint128 daiOut) external returns(uint128); //inject NONSTANDARD NAMING
function SELLFYDAI226(address from, address to, uint128 fyDaiIn) external returns(uint128); //inject NONSTANDARD NAMING
function BUYFYDAI675(address from, address to, uint128 fyDaiOut) external returns(uint128); //inject NONSTANDARD NAMING
function SELLDAIPREVIEW300(uint128 daiIn) external view returns(uint128); //inject NONSTANDARD NAMING
function BUYDAIPREVIEW913(uint128 daiOut) external view returns(uint128); //inject NONSTANDARD NAMING
function SELLFYDAIPREVIEW69(uint128 fyDaiIn) external view returns(uint128); //inject NONSTANDARD NAMING
function BUYFYDAIPREVIEW685(uint128 fyDaiOut) external view returns(uint128); //inject NONSTANDARD NAMING
function MINT176(address from, address to, uint256 daiOffered) external returns (uint256); //inject NONSTANDARD NAMING
function BURN250(address from, address to, uint256 tokensBurned) external returns (uint256, uint256); //inject NONSTANDARD NAMING
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
library SafeMath {
function ADD958(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB494(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB494(a, b, "SafeMath: subtraction overflow");
}
function SUB494(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL434(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV16(a, b, "SafeMath: division by zero");
}
function DIV16(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD331(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD331(a, b, "SafeMath: modulo by zero");
}
function MOD331(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/helpers/DecimalMath.sol
pragma solidity ^0.6.10;
contract DecimalMath {
using SafeMath for uint256;
uint256 constant public unit17 = 1e27; //inject NONSTANDARD NAMING
function MULD379(uint256 x, uint256 y) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return x.MUL434(y).DIV16(unit17);
}
function DIVD836(uint256 x, uint256 y) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return x.MUL434(unit17).DIV16(y);
}
function MULDRUP300(uint256 x, uint256 y) internal pure returns (uint256) //inject NONSTANDARD NAMING
{
uint256 z = x.MUL434(y);
return z.MOD331(unit17) == 0 ? z.DIV16(unit17) : z.DIV16(unit17).ADD958(1);
}
function DIVDRUP370(uint256 x, uint256 y) internal pure returns (uint256) //inject NONSTANDARD NAMING
{
uint256 z = x.MUL434(unit17);
return z.MOD331(y) == 0 ? z.DIV16(y) : z.DIV16(y).ADD958(1);
}
}
// File: contracts/peripheral/YieldProxy.sol
pragma solidity ^0.6.10;
library SafeCast {
function TOUINT128897(uint256 x) internal pure returns(uint128) { //inject NONSTANDARD NAMING
require(
x <= type(uint128).max,
"YieldProxy: Cast overflow"
);
return uint128(x);
}
function TOINT256710(uint256 x) internal pure returns(int256) { //inject NONSTANDARD NAMING
require(
x <= uint256(type(int256).max),
"YieldProxy: Cast overflow"
);
return int256(x);
}
}
contract YieldProxy is DecimalMath {
using SafeCast for uint256;
IVat public vat;
IWeth public weth;
IDai public dai;
IGemJoin public wethJoin;
IDaiJoin public daiJoin;
IChai public chai;
IController public controller;
ITreasury public treasury;
IPool[] public pools;
mapping (address => bool) public poolsMap;
bytes32 public constant chai69 = "CHAI"; //inject NONSTANDARD NAMING
bytes32 public constant weth148 = "ETH-A"; //inject NONSTANDARD NAMING
bool constant public mty307 = true; //inject NONSTANDARD NAMING
bool constant public ytm282 = false; //inject NONSTANDARD NAMING
constructor(address controller_, IPool[] memory _pools) public {
controller = IController(controller_);
treasury = controller.TREASURY445();
weth = treasury.WETH278();
dai = IDai(address(treasury.DAI858()));
chai = treasury.CHAI326();
daiJoin = treasury.DAIJOIN173();
wethJoin = treasury.WETHJOIN654();
vat = treasury.VAT519();
// for repaying debt
dai.APPROVE147(address(treasury), uint(-1));
// for posting to the controller
chai.APPROVE147(address(treasury), uint(-1));
weth.APPROVE147(address(treasury), uint(-1));
// for converting DAI to CHAI
dai.APPROVE147(address(chai), uint(-1));
vat.HOPE952(address(daiJoin));
vat.HOPE952(address(wethJoin));
dai.APPROVE147(address(daiJoin), uint(-1));
weth.APPROVE147(address(wethJoin), uint(-1));
weth.APPROVE147(address(treasury), uint(-1));
// allow all the pools to pull FYDai/dai from us for LPing
for (uint i = 0 ; i < _pools.length; i++) {
dai.APPROVE147(address(_pools[i]), uint(-1));
_pools[i].FYDAI600().APPROVE147(address(_pools[i]), uint(-1));
poolsMap[address(_pools[i])]= true;
}
pools = _pools;
}
function UNPACK384(bytes memory signature) private pure returns (bytes32 r, bytes32 s, uint8 v) { //inject NONSTANDARD NAMING
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
}
function ONBOARD51(address from, bytes memory daiSignature, bytes memory controllerSig) external { //inject NONSTANDARD NAMING
bytes32 r;
bytes32 s;
uint8 v;
(r, s, v) = UNPACK384(daiSignature);
dai.PERMIT233(from, address(this), dai.NONCES538(from), uint(-1), true, v, r, s);
(r, s, v) = UNPACK384(controllerSig);
controller.ADDDELEGATEBYSIGNATURE882(from, address(this), uint(-1), v, r, s);
}
function AUTHORIZEPOOL621(IPool pool, address from, bytes memory daiSig, bytes memory fyDaiSig, bytes memory poolSig) public { //inject NONSTANDARD NAMING
ONLYKNOWNPOOL167(pool);
bytes32 r;
bytes32 s;
uint8 v;
(r, s, v) = UNPACK384(daiSig);
dai.PERMIT233(from, address(pool), dai.NONCES538(from), uint(-1), true, v, r, s);
(r, s, v) = UNPACK384(fyDaiSig);
pool.FYDAI600().PERMIT233(from, address(this), uint(-1), uint(-1), v, r, s);
(r, s, v) = UNPACK384(poolSig);
pool.ADDDELEGATEBYSIGNATURE882(from, address(this), uint(-1), v, r, s);
}
receive() external payable { }
function POST95(address to) //inject NONSTANDARD NAMING
public payable {
weth.DEPOSIT338{ value: msg.value }();
controller.POST95(weth148, address(this), to, msg.value);
}
function WITHDRAW817(address payable to, uint256 amount) //inject NONSTANDARD NAMING
public {
controller.WITHDRAW817(weth148, msg.sender, address(this), amount);
weth.WITHDRAW817(amount);
to.transfer(amount);
}
function ADDLIQUIDITY157(IPool pool, uint256 daiUsed, uint256 maxFYDai) external returns (uint256) { //inject NONSTANDARD NAMING
ONLYKNOWNPOOL167(pool);
IFYDai fyDai = pool.FYDAI600();
require(fyDai.ISMATURE431() != true, "YieldProxy: Only before maturity");
require(dai.TRANSFERFROM451(msg.sender, address(this), daiUsed), "YieldProxy: Transfer Failed");
// calculate needed fyDai
uint256 daiReserves = dai.BALANCEOF833(address(pool));
uint256 fyDaiReserves = fyDai.BALANCEOF833(address(pool));
uint256 daiToAdd = daiUsed.MUL434(daiReserves).DIV16(fyDaiReserves.ADD958(daiReserves));
uint256 daiToConvert = daiUsed.SUB494(daiToAdd);
require(
daiToConvert <= maxFYDai,
"YieldProxy: maxFYDai exceeded"
); // 1 Dai == 1 fyDai
// convert dai to chai and borrow needed fyDai
chai.JOIN369(address(this), daiToConvert);
// look at the balance of chai in dai to avoid rounding issues
uint256 toBorrow = chai.DAI858(address(this));
controller.POST95(chai69, address(this), msg.sender, chai.BALANCEOF833(address(this)));
controller.BORROW691(chai69, fyDai.MATURITY388(), msg.sender, address(this), toBorrow);
// mint liquidity tokens
return pool.MINT176(address(this), msg.sender, daiToAdd);
}
function REMOVELIQUIDITYEARLYDAIPOOL932(IPool pool, uint256 poolTokens, uint256 minimumDaiPrice, uint256 minimumFYDaiPrice) external { //inject NONSTANDARD NAMING
ONLYKNOWNPOOL167(pool);
IFYDai fyDai = pool.FYDAI600();
uint256 maturity = fyDai.MATURITY388();
(uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens);
// Exchange Dai for fyDai to pay as much debt as possible
uint256 fyDaiBought = pool.SELLDAI400(address(this), address(this), daiObtained.TOUINT128897());
require(
fyDaiBought >= MULD379(daiObtained, minimumDaiPrice),
"YieldProxy: minimumDaiPrice not reached"
);
fyDaiObtained = fyDaiObtained.ADD958(fyDaiBought);
uint256 fyDaiUsed;
if (fyDaiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) {
fyDaiUsed = controller.REPAYFYDAI426(chai69, maturity, address(this), msg.sender, fyDaiObtained);
}
uint256 fyDaiRemaining = fyDaiObtained.SUB494(fyDaiUsed);
if (fyDaiRemaining > 0) {// There is fyDai left, so exchange it for Dai to withdraw only Dai and Chai
require(
pool.SELLFYDAI226(address(this), address(this), uint128(fyDaiRemaining)) >= MULD379(fyDaiRemaining, minimumFYDaiPrice),
"YieldProxy: minimumFYDaiPrice not reached"
);
}
WITHDRAWASSETS926(fyDai);
}
function REMOVELIQUIDITYEARLYDAIFIXED8(IPool pool, uint256 poolTokens, uint256 minimumFYDaiPrice) external { //inject NONSTANDARD NAMING
ONLYKNOWNPOOL167(pool);
IFYDai fyDai = pool.FYDAI600();
uint256 maturity = fyDai.MATURITY388();
(uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens);
uint256 fyDaiUsed;
if (fyDaiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) {
fyDaiUsed = controller.REPAYFYDAI426(chai69, maturity, address(this), msg.sender, fyDaiObtained);
}
uint256 fyDaiRemaining = fyDaiObtained.SUB494(fyDaiUsed);
if (fyDaiRemaining == 0) { // We used all the fyDai, so probably there is debt left, so pay with Dai
if (daiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) {
controller.REPAYDAI460(chai69, maturity, address(this), msg.sender, daiObtained);
}
} else { // Exchange remaining fyDai for Dai to withdraw only Dai and Chai
require(
pool.SELLFYDAI226(address(this), address(this), uint128(fyDaiRemaining)) >= MULD379(fyDaiRemaining, minimumFYDaiPrice),
"YieldProxy: minimumFYDaiPrice not reached"
);
}
WITHDRAWASSETS926(fyDai);
}
function REMOVELIQUIDITYMATURE267(IPool pool, uint256 poolTokens) external { //inject NONSTANDARD NAMING
ONLYKNOWNPOOL167(pool);
IFYDai fyDai = pool.FYDAI600();
uint256 maturity = fyDai.MATURITY388();
(uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens);
if (fyDaiObtained > 0) {
daiObtained = daiObtained.ADD958(fyDai.REDEEM906(address(this), address(this), fyDaiObtained));
}
// Repay debt
if (daiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) {
controller.REPAYDAI460(chai69, maturity, address(this), msg.sender, daiObtained);
}
WITHDRAWASSETS926(fyDai);
}
function WITHDRAWASSETS926(IFYDai fyDai) internal { //inject NONSTANDARD NAMING
if (controller.DEBTFYDAI447(chai69, fyDai.MATURITY388(), msg.sender) == 0) {
controller.WITHDRAW817(chai69, msg.sender, address(this), controller.POSTED950(chai69, msg.sender));
chai.EXIT932(address(this), chai.BALANCEOF833(address(this)));
}
require(dai.TRANSFER582(msg.sender, dai.BALANCEOF833(address(this))), "YieldProxy: Dai Transfer Failed");
}
function BORROWDAIFORMAXIMUMFYDAI736( //inject NONSTANDARD NAMING
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 maximumFYDai,
uint256 daiToBorrow
)
public
returns (uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 fyDaiToBorrow = pool.BUYDAIPREVIEW913(daiToBorrow.TOUINT128897());
require (fyDaiToBorrow <= maximumFYDai, "YieldProxy: Too much fyDai required");
// The collateral for this borrow needs to have been posted beforehand
controller.BORROW691(collateral, maturity, msg.sender, address(this), fyDaiToBorrow);
pool.BUYDAI253(address(this), to, daiToBorrow.TOUINT128897());
return fyDaiToBorrow;
}
function BORROWMINIMUMDAIFORFYDAI776( //inject NONSTANDARD NAMING
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 fyDaiToBorrow,
uint256 minimumDaiToBorrow
)
public
returns (uint256)
{
ONLYKNOWNPOOL167(pool);
// The collateral for this borrow needs to have been posted beforehand
controller.BORROW691(collateral, maturity, msg.sender, address(this), fyDaiToBorrow);
uint256 boughtDai = pool.SELLFYDAI226(address(this), to, fyDaiToBorrow.TOUINT128897());
require (boughtDai >= minimumDaiToBorrow, "YieldProxy: Not enough Dai obtained");
return boughtDai;
}
function REPAYFYDAIDEBTFORMAXIMUMDAI955( //inject NONSTANDARD NAMING
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 fyDaiRepayment,
uint256 maximumRepaymentInDai
)
public
returns (uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 fyDaiDebt = controller.DEBTFYDAI447(collateral, maturity, to);
uint256 fyDaiToUse = fyDaiDebt < fyDaiRepayment ? fyDaiDebt : fyDaiRepayment; // Use no more fyDai than debt
uint256 repaymentInDai = pool.BUYFYDAI675(msg.sender, address(this), fyDaiToUse.TOUINT128897());
require (repaymentInDai <= maximumRepaymentInDai, "YieldProxy: Too much Dai required");
controller.REPAYFYDAI426(collateral, maturity, address(this), to, fyDaiToUse);
return repaymentInDai;
}
function REPAYMINIMUMFYDAIDEBTFORDAI862( //inject NONSTANDARD NAMING
IPool pool,
bytes32 collateral,
uint256 maturity,
address to,
uint256 minimumFYDaiRepayment,
uint256 repaymentInDai
)
public
returns (uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 fyDaiRepayment = pool.SELLDAIPREVIEW300(repaymentInDai.TOUINT128897());
uint256 fyDaiDebt = controller.DEBTFYDAI447(collateral, maturity, to);
if(fyDaiRepayment <= fyDaiDebt) { // Sell no more Dai than needed to cancel all the debt
pool.SELLDAI400(msg.sender, address(this), repaymentInDai.TOUINT128897());
} else { // If we have too much Dai, then don't sell it all and buy the exact amount of fyDai needed instead.
pool.BUYFYDAI675(msg.sender, address(this), fyDaiDebt.TOUINT128897());
fyDaiRepayment = fyDaiDebt;
}
require (fyDaiRepayment >= minimumFYDaiRepayment, "YieldProxy: Not enough fyDai debt repaid");
controller.REPAYFYDAI426(collateral, maturity, address(this), to, fyDaiRepayment);
return fyDaiRepayment;
}
function SELLDAI400(IPool pool, address to, uint128 daiIn, uint128 minFYDaiOut) //inject NONSTANDARD NAMING
external
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 fyDaiOut = pool.SELLDAI400(msg.sender, to, daiIn);
require(
fyDaiOut >= minFYDaiOut,
"YieldProxy: Limit not reached"
);
return fyDaiOut;
}
function BUYDAI253(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn) //inject NONSTANDARD NAMING
public
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 fyDaiIn = pool.BUYDAI253(msg.sender, to, daiOut);
require(
maxFYDaiIn >= fyDaiIn,
"YieldProxy: Limit exceeded"
);
return fyDaiIn;
}
function BUYDAIWITHSIGNATURE110(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn, bytes memory signature) //inject NONSTANDARD NAMING
external
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
(bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature);
pool.FYDAI600().PERMIT233(msg.sender, address(pool), uint(-1), uint(-1), v, r, s);
return BUYDAI253(pool, to, daiOut, maxFYDaiIn);
}
function SELLFYDAI226(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut) //inject NONSTANDARD NAMING
public
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 daiOut = pool.SELLFYDAI226(msg.sender, to, fyDaiIn);
require(
daiOut >= minDaiOut,
"YieldProxy: Limit not reached"
);
return daiOut;
}
function SELLFYDAIWITHSIGNATURE545(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut, bytes memory signature) //inject NONSTANDARD NAMING
external
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
(bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature);
pool.FYDAI600().PERMIT233(msg.sender, address(pool), uint(-1), uint(-1), v, r, s);
return SELLFYDAI226(pool, to, fyDaiIn, minDaiOut);
}
function BUYFYDAI675(IPool pool, address to, uint128 fyDaiOut, uint128 maxDaiIn) //inject NONSTANDARD NAMING
external
returns(uint256)
{
ONLYKNOWNPOOL167(pool);
uint256 daiIn = pool.BUYFYDAI675(msg.sender, to, fyDaiOut);
require(
maxDaiIn >= daiIn,
"YieldProxy: Limit exceeded"
);
return daiIn;
}
function REPAYDAIWITHSIGNATURE818(bytes32 collateral, uint256 maturity, address to, uint256 daiAmount, bytes memory signature) //inject NONSTANDARD NAMING
external
returns(uint256)
{
(bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature);
dai.PERMIT233(msg.sender, address(treasury), dai.NONCES538(msg.sender), uint(-1), true, v, r, s);
controller.REPAYDAI460(collateral, maturity, msg.sender, to, daiAmount);
}
function ONLYKNOWNPOOL167(IPool pool) private view { //inject NONSTANDARD NAMING
require(poolsMap[address(pool)], "YieldProxy: Unknown pool");
}
}
|
inject NONSTANDARD NAMING
|
function ERASE227(bytes32, address) external returns (uint256, uint256);
| 12,707,163 |
./partial_match/42/0x466206beB25B31547a5a9118bf1ed617aaC1784F/sources/WethWrapperForAMMExchange.sol
|
The graph mappings assume this event is emitted immediately after the corresponding amm event.
|
function removeLiquidity(IMarket _market, uint256 _fee, uint256 _poolTokensToSell, uint256 _minSetsSold) external returns (uint256 _shortShare, uint256 _longShare, uint256 _cashShare, uint256 _setsSold) {
IAMMExchange _amm = getAMM(_market, _fee);
_amm.transferFrom(msg.sender, address(this), _poolTokensToSell);
(_shortShare, _longShare, _cashShare, _setsSold) = _amm.removeLiquidity(_poolTokensToSell, _minSetsSold);
emit RemoveLiquidity(address(_amm), msg.sender);
shareTransfer(_market, address(this), msg.sender, _shortShare, _shortShare, _longShare);
if (_cashShare > 0) {
weth.withdraw(_cashShare);
msg.sender.transfer(_cashShare);
}
}
| 8,870,073 |
pragma solidity ^0.5.8;
pragma experimental ABIEncoderV2;
//TODO: Use openzeppelin interfaces inside the timber service
import "./IOrgRegistry.sol";
import "./Registrar.sol";
import "./ERC165Compatible.sol";
import "./Roles.sol";
import "./Ownable.sol";
/// @dev Contract for maintaining organization registry
/// Contract inherits from Ownable and ERC165Compatible
/// Ownable contains ownership criteria of the organization registry
/// ERC165Compatible contains interface compatibility checks
contract OrgRegistry is Ownable, ERC165Compatible, Registrar, IOrgRegistry {
/// @notice Leverages roles contract as imported above to assign different roles
using Roles for Roles.Role;
enum Role {Null, Buyer, Supplier, Carrier}
struct Org {
address orgAddress;
bytes32 name;
uint role;
bytes messagingKey;
bytes zkpPublicKey;
}
struct OrgInterfaces {
bytes32 groupName;
address tokenAddress;
address shieldAddress;
address verifierAddress;
}
mapping (address => Org) orgMap;
mapping (uint => OrgInterfaces) orgInterfaceMap;
uint orgInterfaceCount;
mapping (uint => Roles.Role) private roleMap;
// address[] public parties;
Org[] orgs;
mapping(address => address) managerMap;
event RegisterOrg(
bytes32 _name,
address _address,
uint _role,
bytes _messagingKey,
bytes _zkpPublicKey
);
/// @dev constructor function that takes the address of a pre-deployed ERC1820
/// registry. Ideally, this contract is a publicly known address:
/// 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24. Inherently, the constructor
/// sets the interfaces and registers the current contract with the global registry
constructor(address _erc1820) public Ownable() ERC165Compatible() Registrar(_erc1820) {
setInterfaces();
setInterfaceImplementation("IOrgRegistry", address(this));
}
/// @notice This is an implementation of setting interfaces for the organization
/// registry contract
/// @dev the character '^' corresponds to bit wise xor of individual interface id's
/// which are the parsed 4 bytes of the function signature of each of the functions
/// in the org registry contract
function setInterfaces() public onlyOwner returns (bool) {
/// 0x54ebc817 is equivalent to the bytes4 of the function selectors in IOrgRegistry
supportedInterfaces[this.registerOrg.selector ^
this.registerInterfaces.selector ^
this.getOrgs.selector ^
this.getOrgCount.selector ^
this.getInterfaceAddresses.selector] = true;
return true;
}
/// @notice This function is a helper function to be able to get the
/// set interface id by the setInterfaces()
function getInterfaces() external pure returns (bytes4) {
return this.registerOrg.selector ^
this.registerInterfaces.selector ^
this.getOrgs.selector ^
this.getOrgCount.selector ^
this.getInterfaceAddresses.selector;
}
/// @dev Since this is an inherited method from ERC165 Compatible, it returns the value of the interface id
/// set during the deployment of this contract
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return supportedInterfaces[interfaceId];
}
/// @notice Indicates whether the contract implements the interface 'interfaceHash' for the address 'addr' or not.
/// @dev Below implementation is necessary to be able to have the ability to register with ERC1820
/// @param interfaceHash keccak256 hash of the name of the interface
/// @param addr Address for which the contract will implement the interface
/// @return ERC1820_ACCEPT_MAGIC only if the contract implements 'interfaceHash' for the address 'addr'.
function canImplementInterfaceForAddress(bytes32 interfaceHash, address addr) external view returns(bytes32) {
return ERC1820_ACCEPT_MAGIC;
}
/// @dev Since this is an inherited method from Registrar, it allows for a new manager to be set
/// for this contract instance
function assignManager(address _oldManager, address _newManager) external {
assignManagement(_oldManager, _newManager);
}
/// @notice Function to register an organization
/// @param _address ethereum address of the registered organization
/// @param _name name of the registered organization
/// @param _role role of the registered organization
/// @param _messagingKey public key required for message communication
/// @param _zkpPublicKey public key required for commitments & to verify EdDSA signatures with
/// @dev Function to register an organization
/// @return `true` upon successful registration of the organization
function registerOrg(
address _address,
bytes32 _name,
uint _role,
bytes calldata _messagingKey,
bytes calldata _zkpPublicKey
) external returns (bool) {
Org memory org = Org(_address, _name, _role, _messagingKey, _zkpPublicKey);
roleMap[_role].add(_address);
orgMap[_address] = org;
orgs.push(org);
// parties.push(_address);
emit RegisterOrg(
_name,
_address,
_role,
_messagingKey,
_zkpPublicKey
);
return true;
}
/// @notice Function to register the names of the interfaces associated with the OrgRegistry
/// @param _groupName name of the working group registered by an organization
/// @param _tokenAddress name of the registered token interface
/// @param _shieldAddress name of the registered shield registry interface
/// @param _verifierAddress name of the verifier registry interface
/// @dev Function to register an organization's interfaces for easy lookup
/// @return `true` upon successful registration of the organization's interfaces
function registerInterfaces(
bytes32 _groupName,
address _tokenAddress,
address _shieldAddress,
address _verifierAddress
) external returns (bool) {
orgInterfaceMap[orgInterfaceCount] = OrgInterfaces(
_groupName,
_tokenAddress,
_shieldAddress,
_verifierAddress
);
orgInterfaceCount++;
return true;
}
/// @dev Function to get the count of number of organizations to help with extraction
/// @return length of the array containing organization addresses
function getOrgCount() external view returns (uint) {
return orgs.length;
}
/// @notice Function to get a single organization's details
function getOrg(address _address) external view returns (
address,
bytes32,
uint,
bytes memory,
bytes memory
) {
return (
orgMap[_address].orgAddress,
orgMap[_address].name,
orgMap[_address].role,
orgMap[_address].messagingKey,
orgMap[_address].zkpPublicKey
);
}
/// @notice Function to get a single organization's interface details
function getInterfaceAddresses() external view returns (
bytes32[] memory,
address[] memory,
address[] memory,
address[] memory
) {
bytes32[] memory gName = new bytes32[](orgInterfaceCount);
address[] memory tfAddress = new address[](orgInterfaceCount);
address[] memory sAddress = new address[](orgInterfaceCount);
address[] memory vrAddress = new address[](orgInterfaceCount);
for (uint i = 0; i < orgInterfaceCount; i++) {
OrgInterfaces storage orgInterfaces = orgInterfaceMap[i];
gName[i] = orgInterfaces.groupName;
tfAddress[i] = orgInterfaces.tokenAddress;
sAddress[i] = orgInterfaces.shieldAddress;
vrAddress[i] = orgInterfaces.verifierAddress;
}
return (
gName,
tfAddress,
sAddress,
vrAddress
);
}
// @notice Function to retrieve a page of registered organizations along with details
// @notice start and end indices here are a convenience for pagination
// @param start starting index of the array where organization addresses are stored
// @param count ending index of the array where organization addresses are stored
// @dev Getter to retrieve details of the organization enabled for pagination
// @return array form of the details of the organization as stored in the struct
function getOrgs() external view returns (
address[] memory,
bytes32[] memory,
uint[] memory,
bytes[] memory,
bytes[] memory
) {
address[] memory addresses = new address[](orgs.length);
bytes32[] memory names = new bytes32[](orgs.length);
uint[] memory roles = new uint[](orgs.length);
bytes[] memory messagingKeys = new bytes[](orgs.length);
bytes[] memory zkpPublicKeys = new bytes[](orgs.length);
for (uint i = 0; i < orgs.length; i++) {
addresses[i] = orgs[i].orgAddress;
names[i] = orgs[i].name;
roles[i] = orgs[i].role;
messagingKeys[i] = orgs[i].messagingKey;
zkpPublicKeys[i] = orgs[i].zkpPublicKey;
}
return (
addresses,
names,
roles,
messagingKeys,
zkpPublicKeys
);
}
}
|
Since this is an inherited method from ERC165 Compatible, it returns the value of the interface id set during the deployment of this contract
|
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return supportedInterfaces[interfaceId];
}
| 13,029,893 |
// CryptoTorch-Token Source code
// copyright 2018 CryptoTorch <https://cryptotorch.io>
pragma solidity 0.4.19;
/**
* @title SafeMath
* Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
*
* Owner rights:
* - change the name of the contract
* - change the name of the token
* - change the Proof of Stake difficulty
* - transfer ownership
*
* Owner CANNOT:
* - withdrawal funds
* - disable withdrawals
* - kill the contract
* - change the price of tokens
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20 interface (Good parts only)
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
}
/**
* @title CryptoTorchToken
*
* Token + Dividends System for the Cryptolympic-Torch
*
* Token: KMS - Kilometers (Distance of Torch Run)
*/
contract CryptoTorchToken is ERC20, Ownable {
using SafeMath for uint256;
//
// Events
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
event onWithdraw(
address indexed to,
uint256 amount
);
event onMint(
address indexed to,
uint256 pricePaid,
uint256 tokensMinted,
address indexed referredBy
);
event onBurn(
address indexed from,
uint256 tokensBurned,
uint256 amountEarned
);
//
// Token Configurations
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
string internal name_ = "Cryptolympic Torch-Run Kilometers";
string internal symbol_ = "KMS";
uint256 constant internal dividendFee_ = 5;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
uint256 public stakingRequirement = 50e18;
//
// Token Internals
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
address internal tokenController_;
address internal donationsReceiver_;
mapping (address => uint256) internal tokenBalanceLedger_; // scaled by 1e18
mapping (address => uint256) internal referralBalance_;
mapping (address => uint256) internal profitsReceived_;
mapping (address => int256) internal payoutsTo_;
//
// Modifiers
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// No buying tokens directly through this contract, only through the
// CryptoTorch Controller Contract via the CryptoTorch Dapp
//
modifier onlyTokenController() {
require(tokenController_ != address(0) && msg.sender == tokenController_);
_;
}
// Token Holders Only
modifier onlyTokenHolders() {
require(myTokens() > 0);
_;
}
// Dividend Holders Only
modifier onlyProfitHolders() {
require(myDividends(true) > 0);
_;
}
//
// Public Functions
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
/**
* Contract Constructor
*/
function CryptoTorchToken() public {}
/**
* Sets the Token Controller Contract (CryptoTorch)
*/
function setTokenController(address _controller) public onlyOwner {
tokenController_ = _controller;
}
/**
* Sets the Contract Donations Receiver address
*/
function setDonationsReceiver(address _receiver) public onlyOwner {
donationsReceiver_ = _receiver;
}
/**
* Do not make payments directly to this contract (unless it is a donation! :)
* - payments made directly to the contract do not receive tokens. Tokens
* are only available through the CryptoTorch Controller Contract, which
* is managed by the Dapp at https://cryptotorch.io
*/
function() payable public {
if (msg.value > 0 && donationsReceiver_ != 0x0) {
donationsReceiver_.transfer(msg.value); // donations? Thank you! :)
}
}
/**
* Liquifies tokens to ether.
*/
function sell(uint256 _amountOfTokens) public onlyTokenHolders {
sell_(msg.sender, _amountOfTokens);
}
/**
* Liquifies tokens to ether.
*/
function sellFor(address _for, uint256 _amountOfTokens) public onlyTokenController {
sell_(_for, _amountOfTokens);
}
/**
* Liquifies tokens to ether.
*/
function withdraw() public onlyProfitHolders {
withdraw_(msg.sender);
}
/**
* Liquifies tokens to ether.
*/
function withdrawFor(address _for) public onlyTokenController {
withdraw_(_for);
}
/**
* Liquifies tokens to ether.
*/
function mint(address _to, uint256 _amountPaid, address _referredBy) public onlyTokenController payable returns(uint256) {
require(_amountPaid == msg.value);
return mintTokens_(_to, _amountPaid, _referredBy);
}
/**
* Transfer tokens from the caller to a new holder.
* There's a small fee here that is redistributed to all token holders
*/
function transfer(address _to, uint256 _value) public onlyTokenHolders returns(bool) {
return transferFor_(msg.sender, _to, _value);
}
//
// Owner Functions
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
/**
* If we want to rebrand, we can.
*/
function setName(string _name) public onlyOwner {
name_ = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol) public onlyOwner {
symbol_ = _symbol;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens) public onlyOwner {
stakingRequirement = _amountOfTokens;
}
//
// Helper Functions
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
/**
* View the total balance of the contract
*/
function contractBalance() public view returns (uint256) {
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply() public view returns(uint256) {
return tokenSupply_;
}
/**
* ERC20 Token Name
*/
function name() public view returns (string) {
return name_;
}
/**
* ERC20 Token Symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* ERC20 Token Decimals
*/
function decimals() public pure returns (uint256) {
return 18;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens() public view returns(uint256) {
address _playerAddress = msg.sender;
return balanceOf(_playerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeBonus` is to to true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeBonus) public view returns(uint256) {
address _playerAddress = msg.sender;
return _includeBonus ? dividendsOf(_playerAddress) + referralBalance_[_playerAddress] : dividendsOf(_playerAddress);
}
/**
* Retreive the Total Profits previously paid out to the Caller
*/
function myProfitsReceived() public view returns (uint256) {
address _playerAddress = msg.sender;
return profitsOf(_playerAddress);
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _playerAddress) public view returns(uint256) {
return tokenBalanceLedger_[_playerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _playerAddress) public view returns(uint256) {
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_playerAddress]) - payoutsTo_[_playerAddress]) / magnitude;
}
/**
* Retrieve the paid-profits balance of any single address.
*/
function profitsOf(address _playerAddress) public view returns(uint256) {
return profitsReceived_[_playerAddress];
}
/**
* Retrieve the referral dividends balance of any single address.
*/
function referralBalanceOf(address _playerAddress) public view returns(uint256) {
return referralBalance_[_playerAddress];
}
/**
* Return the sell price of 1 individual token.
*/
function sellPrice() public view returns(uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ether = tokensToEther_(1e18);
uint256 _dividends = SafeMath.div(_ether, dividendFee_);
uint256 _taxedEther = SafeMath.sub(_ether, _dividends);
return _taxedEther;
}
}
/**
* Return the buy price of 1 individual token.
*/
function buyPrice() public view returns(uint256) {
// our calculation relies on the token supply, so we need supply. Doh.
if (tokenSupply_ == 0) {
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ether = tokensToEther_(1e18);
uint256 _dividends = SafeMath.div(_ether, dividendFee_);
uint256 _taxedEther = SafeMath.add(_ether, _dividends);
return _taxedEther;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _etherToSpend) public view returns(uint256) {
uint256 _dividends = _etherToSpend.div(dividendFee_);
uint256 _taxedEther = _etherToSpend.sub(_dividends);
uint256 _amountOfTokens = etherToTokens_(_taxedEther);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEtherReceived(uint256 _tokensToSell) public view returns(uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ether = tokensToEther_(_tokensToSell);
uint256 _dividends = _ether.div(dividendFee_);
uint256 _taxedEther = _ether.sub(_dividends);
return _taxedEther;
}
//
// Internal Functions
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
/**
* Liquifies tokens to ether.
*/
function sell_(address _recipient, uint256 _amountOfTokens) internal {
require(_amountOfTokens <= tokenBalanceLedger_[_recipient]);
uint256 _tokens = _amountOfTokens;
uint256 _ether = tokensToEther_(_tokens);
uint256 _dividends = SafeMath.div(_ether, dividendFee_);
uint256 _taxedEther = SafeMath.sub(_ether, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_recipient] = SafeMath.sub(tokenBalanceLedger_[_recipient], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEther * magnitude));
payoutsTo_[_recipient] -= _updatedPayouts;
// update the amount of dividends per token
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onBurn(_recipient, _tokens, _taxedEther);
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw_(address _recipient) internal {
require(_recipient != address(0));
// setup data
uint256 _dividends = getDividendsOf_(_recipient, false);
// update dividend tracker
payoutsTo_[_recipient] += (int256)(_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_recipient];
referralBalance_[_recipient] = 0;
// fire event
onWithdraw(_recipient, _dividends);
// transfer funds
profitsReceived_[_recipient] = profitsReceived_[_recipient].add(_dividends);
_recipient.transfer(_dividends);
// Keep contract clean
if (tokenSupply_ == 0 && this.balance > 0) {
owner.transfer(this.balance);
}
}
/**
* Assign tokens to player
*/
function mintTokens_(address _to, uint256 _amountPaid, address _referredBy) internal returns(uint256) {
require(_to != address(this) && _to != tokenController_);
uint256 _undividedDividends = SafeMath.div(_amountPaid, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 10);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEther = SafeMath.sub(_amountPaid, _undividedDividends);
uint256 _amountOfTokens = etherToTokens_(_taxedEther);
uint256 _fee = _dividends * magnitude;
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if (_referredBy != address(0) && _referredBy != _to && tokenBalanceLedger_[_referredBy] >= stakingRequirement) {
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if (tokenSupply_ > 0) {
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_to] = SafeMath.add(tokenBalanceLedger_[_to], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them
int256 _updatedPayouts = (int256)((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_to] += _updatedPayouts;
// fire event
onMint(_to, _amountPaid, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Transfer tokens from the caller to a new holder.
* There's a small fee here that is redistributed to all token holders
*/
function transferFor_(address _from, address _to, uint256 _amountOfTokens) internal returns(bool) {
require(_to != address(0));
require(tokenBalanceLedger_[_from] >= _amountOfTokens && tokenBalanceLedger_[_to] + _amountOfTokens >= tokenBalanceLedger_[_to]);
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_from]);
// withdraw all outstanding dividends first
if (getDividendsOf_(_from, true) > 0) {
withdraw_(_from);
}
// liquify 10% of the tokens that are transferred
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEther_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_from] = SafeMath.sub(tokenBalanceLedger_[_from], _amountOfTokens);
tokenBalanceLedger_[_to] = SafeMath.add(tokenBalanceLedger_[_to], _taxedTokens);
// update dividend trackers
payoutsTo_[_from] -= (int256)(profitPerShare_ * _amountOfTokens);
payoutsTo_[_to] += (int256)(profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_from, _to, _taxedTokens);
// ERC20
return true;
}
/**
* Retrieve the dividends of the owner.
*/
function getDividendsOf_(address _recipient, bool _includeBonus) internal view returns(uint256) {
return _includeBonus ? dividendsOf(_recipient) + referralBalance_[_recipient] : dividendsOf(_recipient);
}
/**
* Calculate Token price based on an amount of incoming ether;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function etherToTokens_(uint256 _ether) internal view returns(uint256) {
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ether * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_);
return _tokensReceived;
}
/**
* Calculate token sell value.
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEther_(uint256 _tokens) internal view returns(uint256) {
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
/**
* Squirts gas! ;)
*/
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
|
Liquifies tokens to ether./
|
function mint(address _to, uint256 _amountPaid, address _referredBy) public onlyTokenController payable returns(uint256) {
require(_amountPaid == msg.value);
return mintTokens_(_to, _amountPaid, _referredBy);
}
| 12,653,999 |
./partial_match/1/0x525CFF53983B090Ab8F5E4DA471d849eCD5e05ed/sources/QuantumCS.sol
|
function to buy a basket
|
function buyBasket(uint256 _basketNumber) public payable {
require(
_basketNumber > users[msg.sender].basketsPurchased && _basketNumber <= 13,
"basket already purchased"
);
require(
_basketNumber == users[msg.sender].basketsPurchased + 1,
"you need to purchase previous basket first"
);
require(
msg.value >= basketPrice[_basketNumber - 1],
"you should have enough balance"
);
users[msg.sender].basketsPurchased = users[msg.sender].basketsPurchased.add(1);
emit BuyBasketEvent(msg.sender,_basketNumber);
if(_basketNumber == 2){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle2 ++;
if(cycles[users[msg.sender].upline].cycle2%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
else if(_basketNumber == 3){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle3 ++;
if(cycles[users[msg.sender].upline].cycle3%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
else if(_basketNumber == 4){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle4 ++;
if(cycles[users[msg.sender].upline].cycle4%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
else if(_basketNumber == 5){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle5 ++;
if(cycles[users[msg.sender].upline].cycle5%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
else if(_basketNumber == 6){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle6 ++;
if(cycles[users[msg.sender].upline].cycle6%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
else if(_basketNumber == 7){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle7 ++;
if(cycles[users[msg.sender].upline].cycle7%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
else if(_basketNumber == 8){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle8 ++;
if(cycles[users[msg.sender].upline].cycle8%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
else if(_basketNumber == 9){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle9 ++;
if(cycles[users[msg.sender].upline].cycle9%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
else if(_basketNumber == 10){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle10 ++;
if(cycles[users[msg.sender].upline].cycle10%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
else if(_basketNumber == 11){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle11 ++;
if(cycles[users[msg.sender].upline].cycle11%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
else if(_basketNumber == 12){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle12 ++;
if(cycles[users[msg.sender].upline].cycle12%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
else if(_basketNumber == 13){
setDataLevel(msg.sender, _basketNumber);
cycles[users[msg.sender].upline].cycle13 ++;
if(cycles[users[msg.sender].upline].cycle13%4==0){
amountDistribute(_basketNumber,true);
}
else
amountDistribute(_basketNumber,false);
}
}
| 4,108,040 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.2;
interface ILendingPoolAddressesProviderV2 {
/**
* @notice Get the current address for Aave LendingPool
* @dev Lending pool is the core contract on which to call deposit
*/
function getLendingPool() external view returns (address);
}
interface IAaveATokenV2 {
/**
* @notice returns the current total aToken balance of _user all interest collected included.
* To obtain the user asset principal balance with interests excluded , ERC20 non-standard
* method principalBalanceOf() can be used.
*/
function balanceOf(address _user) external view returns(uint256);
}
interface IAaveLendingPoolV2 {
/**
* @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens)
* is minted.
* @param reserve the address of the reserve
* @param amount the amount to be deposited
* @param referralCode integrators are assigned a referral code and can potentially receive rewards.
**/
function deposit(
address reserve,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev withdraws the assets of user.
* @param reserve the address of the reserve
* @param amount the underlying amount to be redeemed
* @param to address that will receive the underlying
**/
function withdraw(
address reserve,
uint256 amount,
address to
) external;
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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);
}
}
}
}
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library MassetHelpers {
using SafeERC20 for IERC20;
function transferReturnBalance(
address _sender,
address _recipient,
address _bAsset,
uint256 _qty
) internal returns (uint256 receivedQty, uint256 recipientBalance) {
uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient);
IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty);
recipientBalance = IERC20(_bAsset).balanceOf(_recipient);
receivedQty = recipientBalance - balBefore;
}
function safeInfiniteApprove(address _asset, address _spender) internal {
IERC20(_asset).safeApprove(_spender, 0);
IERC20(_asset).safeApprove(_spender, 2**256 - 1);
}
}
interface IPlatformIntegration {
/**
* @dev Deposit the given bAsset to Lending platform
* @param _bAsset bAsset address
* @param _amount Amount to deposit
*/
function deposit(
address _bAsset,
uint256 _amount,
bool isTokenFeeCharged
) external returns (uint256 quantityDeposited);
/**
* @dev Withdraw given bAsset from Lending platform
*/
function withdraw(
address _receiver,
address _bAsset,
uint256 _amount,
bool _hasTxFee
) external;
/**
* @dev Withdraw given bAsset from Lending platform
*/
function withdraw(
address _receiver,
address _bAsset,
uint256 _amount,
uint256 _totalAmount,
bool _hasTxFee
) external;
/**
* @dev Withdraw given bAsset from the cache
*/
function withdrawRaw(
address _receiver,
address _bAsset,
uint256 _amount
) external;
/**
* @dev Returns the current balance of the given bAsset
*/
function checkBalance(address _bAsset) external returns (uint256 balance);
/**
* @dev Returns the pToken
*/
function bAssetToPToken(address _bAsset) external returns (address pToken);
}
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
contract ModuleKeys {
// Governance
// ===========
// keccak256("Governance");
bytes32 internal constant KEY_GOVERNANCE =
0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking");
bytes32 internal constant KEY_STAKING =
0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin");
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// mStable
// =======
// keccak256("OracleHub");
bytes32 internal constant KEY_ORACLE_HUB =
0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager");
bytes32 internal constant KEY_MANAGER =
0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER =
0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken");
bytes32 internal constant KEY_META_TOKEN =
0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager");
bytes32 internal constant KEY_SAVINGS_MANAGER =
0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
// keccak256("Liquidator");
bytes32 internal constant KEY_LIQUIDATOR =
0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4;
// keccak256("InterestValidator");
bytes32 internal constant KEY_INTEREST_VALIDATOR =
0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f;
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
abstract contract ImmutableModule is ModuleKeys {
INexus public immutable nexus;
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
constructor(address _nexus) {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
_onlyGovernor();
_;
}
function _onlyGovernor() internal view {
require(msg.sender == _governor(), "Only governor can execute");
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the ProxyAdmin.
*/
modifier onlyProxyAdmin() {
require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute");
_;
}
/**
* @dev Modifier to allow function calls only from the Manager.
*/
modifier onlyManager() {
require(msg.sender == _manager(), "Only manager can execute");
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return Staking Module address from the Nexus
* @return Address of the Staking Module contract
*/
function _staking() internal view returns (address) {
return nexus.getModule(KEY_STAKING);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
/**
* @dev Return MetaToken Module address from the Nexus
* @return Address of the MetaToken Module contract
*/
function _metaToken() internal view returns (address) {
return nexus.getModule(KEY_META_TOKEN);
}
/**
* @dev Return OracleHub Module address from the Nexus
* @return Address of the OracleHub Module contract
*/
function _oracleHub() internal view returns (address) {
return nexus.getModule(KEY_ORACLE_HUB);
}
/**
* @dev Return Manager Module address from the Nexus
* @return Address of the Manager Module contract
*/
function _manager() internal view returns (address) {
return nexus.getModule(KEY_MANAGER);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
}
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;
}
}
abstract contract AbstractIntegration is
IPlatformIntegration,
Initializable,
ImmutableModule,
ReentrancyGuard
{
event PTokenAdded(address indexed _bAsset, address _pToken);
event Deposit(address indexed _bAsset, address _pToken, uint256 _amount);
event Withdrawal(address indexed _bAsset, address _pToken, uint256 _amount);
event PlatformWithdrawal(address indexed bAsset, address pToken, uint256 totalAmount, uint256 userAmount);
// LP has write access
address public immutable lpAddress;
// bAsset => pToken (Platform Specific Token Address)
mapping(address => address) public override bAssetToPToken;
// Full list of all bAssets supported here
address[] internal bAssetsMapped;
/**
* @param _nexus Address of the Nexus
* @param _lp Address of LP
*/
constructor(
address _nexus,
address _lp
) ReentrancyGuard() ImmutableModule(_nexus) {
require(_lp != address(0), "Invalid LP address");
lpAddress = _lp;
}
/**
* @dev Simple initializer to set first bAsset/pTokens
*/
function initialize(
address[] calldata _bAssets,
address[] calldata _pTokens
) public initializer {
uint256 len = _bAssets.length;
require(len == _pTokens.length, "Invalid inputs");
for(uint256 i = 0; i < len; i++){
_setPTokenAddress(_bAssets[i], _pTokens[i]);
}
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyLP() {
require(msg.sender == lpAddress, "Only the LP can execute");
_;
}
/***************************************
CONFIG
****************************************/
/**
* @dev Provide support for bAsset by passing its pToken address.
* This method can only be called by the system Governor
* @param _bAsset Address for the bAsset
* @param _pToken Address for the corresponding platform token
*/
function setPTokenAddress(address _bAsset, address _pToken)
external
onlyGovernor
{
_setPTokenAddress(_bAsset, _pToken);
}
/**
* @dev Provide support for bAsset by passing its pToken address.
* Add to internal mappings and execute the platform specific,
* abstract method `_abstractSetPToken`
* @param _bAsset Address for the bAsset
* @param _pToken Address for the corresponding platform token
*/
function _setPTokenAddress(address _bAsset, address _pToken)
internal
{
require(bAssetToPToken[_bAsset] == address(0), "pToken already set");
require(_bAsset != address(0) && _pToken != address(0), "Invalid addresses");
bAssetToPToken[_bAsset] = _pToken;
bAssetsMapped.push(_bAsset);
emit PTokenAdded(_bAsset, _pToken);
_abstractSetPToken(_bAsset, _pToken);
}
function _abstractSetPToken(address _bAsset, address _pToken) internal virtual;
/**
* @dev Simple helper func to get the min of two values
*/
function _min(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
return x > y ? y : x;
}
}
// External
// Libs
/**
* @title AaveV2Integration
* @author Stability Labs Pty. Ltd.
* @notice A simple connection to deposit and withdraw bAssets from Aave
* @dev VERSION: 1.0
* DATE: 2020-16-11
*/
contract AaveV2Integration is AbstractIntegration {
using SafeERC20 for IERC20;
// Core address for the given platform */
address public immutable platformAddress;
event RewardTokenApproved(address rewardToken, address account);
/**
* @param _nexus Address of the Nexus
* @param _lp Address of LP
* @param _platformAddress Generic platform address
*/
constructor(
address _nexus,
address _lp,
address _platformAddress
) AbstractIntegration(_nexus, _lp) {
require(_platformAddress != address(0), "Invalid platform address");
platformAddress = _platformAddress;
}
/***************************************
ADMIN
****************************************/
/**
* @dev Approves Liquidator to spend reward tokens
*/
function approveRewardToken()
external
onlyGovernor
{
address liquidator = nexus.getModule(keccak256("Liquidator"));
require(liquidator != address(0), "Liquidator address cannot be zero");
// Official checksummed AAVE token address
// https://ethplorer.io/address/0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9
address aaveToken = address(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9);
MassetHelpers.safeInfiniteApprove(aaveToken, liquidator);
emit RewardTokenApproved(address(aaveToken), liquidator);
}
/***************************************
CORE
****************************************/
/**
* @dev Deposit a quantity of bAsset into the platform. Credited aTokens
* remain here in the vault. Can only be called by whitelisted addresses
* (mAsset and corresponding BasketManager)
* @param _bAsset Address for the bAsset
* @param _amount Units of bAsset to deposit
* @param _hasTxFee Is the bAsset known to have a tx fee?
* @return quantityDeposited Quantity of bAsset that entered the platform
*/
function deposit(
address _bAsset,
uint256 _amount,
bool _hasTxFee
)
external
override
onlyLP
nonReentrant
returns (uint256 quantityDeposited)
{
require(_amount > 0, "Must deposit something");
IAaveATokenV2 aToken = _getATokenFor(_bAsset);
quantityDeposited = _amount;
if(_hasTxFee) {
// If we charge a fee, account for it
uint256 prevBal = _checkBalance(aToken);
_getLendingPool().deposit(_bAsset, _amount, address(this), 36);
uint256 newBal = _checkBalance(aToken);
quantityDeposited = _min(quantityDeposited, newBal - prevBal);
} else {
_getLendingPool().deposit(_bAsset, _amount, address(this), 36);
}
emit Deposit(_bAsset, address(aToken), quantityDeposited);
}
/**
* @dev Withdraw a quantity of bAsset from the platform
* @param _receiver Address to which the bAsset should be sent
* @param _bAsset Address of the bAsset
* @param _amount Units of bAsset to withdraw
* @param _hasTxFee Is the bAsset known to have a tx fee?
*/
function withdraw(
address _receiver,
address _bAsset,
uint256 _amount,
bool _hasTxFee
)
external
override
onlyLP
nonReentrant
{
_withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee);
}
/**
* @dev Withdraw a quantity of bAsset from the platform
* @param _receiver Address to which the bAsset should be sent
* @param _bAsset Address of the bAsset
* @param _amount Units of bAsset to send to recipient
* @param _totalAmount Total units to pull from lending platform
* @param _hasTxFee Is the bAsset known to have a tx fee?
*/
function withdraw(
address _receiver,
address _bAsset,
uint256 _amount,
uint256 _totalAmount,
bool _hasTxFee
)
external
override
onlyLP
nonReentrant
{
_withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee);
}
/** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */
function _withdraw(
address _receiver,
address _bAsset,
uint256 _amount,
uint256 _totalAmount,
bool _hasTxFee
)
internal
{
require(_totalAmount > 0, "Must withdraw something");
IAaveATokenV2 aToken = _getATokenFor(_bAsset);
if(_hasTxFee) {
require(_amount == _totalAmount, "Cache inactive for assets with fee");
_getLendingPool().withdraw(_bAsset, _amount, _receiver);
} else {
_getLendingPool().withdraw(_bAsset, _totalAmount, address(this));
// Send redeemed bAsset to the receiver
IERC20(_bAsset).safeTransfer(_receiver, _amount);
}
emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount);
}
/**
* @dev Withdraw a quantity of bAsset from the cache.
* @param _receiver Address to which the bAsset should be sent
* @param _bAsset Address of the bAsset
* @param _amount Units of bAsset to withdraw
*/
function withdrawRaw(
address _receiver,
address _bAsset,
uint256 _amount
)
external
override
onlyLP
nonReentrant
{
require(_amount > 0, "Must withdraw something");
require(_receiver != address(0), "Must specify recipient");
IERC20(_bAsset).safeTransfer(_receiver, _amount);
emit Withdrawal(_bAsset, address(0), _amount);
}
/**
* @dev Get the total bAsset value held in the platform
* This includes any interest that was generated since depositing
* Aave gradually increases the balances of all aToken holders, as the interest grows
* @param _bAsset Address of the bAsset
* @return balance Total value of the bAsset in the platform
*/
function checkBalance(address _bAsset)
external
override
returns (uint256 balance)
{
// balance is always with token aToken decimals
IAaveATokenV2 aToken = _getATokenFor(_bAsset);
return _checkBalance(aToken);
}
/***************************************
APPROVALS
****************************************/
/**
* @dev Internal method to respond to the addition of new bAsset / pTokens
* We need to approve the Aave lending pool core conrtact and give it permission
* to spend the bAsset
* @param _bAsset Address of the bAsset to approve
*/
function _abstractSetPToken(address _bAsset, address /*_pToken*/)
internal
override
{
address lendingPool = address(_getLendingPool());
// approve the pool to spend the bAsset
MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool);
}
/***************************************
HELPERS
****************************************/
/**
* @dev Get the current address of the Aave lending pool, which is the gateway to
* depositing.
* @return Current lending pool implementation
*/
function _getLendingPool()
internal
view
returns (IAaveLendingPoolV2)
{
address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool();
require(lendingPool != address(0), "Lending pool does not exist");
return IAaveLendingPoolV2(lendingPool);
}
/**
* @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use
* for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings.
* @param _bAsset Address of the bAsset
* @return aToken Corresponding to this bAsset
*/
function _getATokenFor(address _bAsset)
internal
view
returns (IAaveATokenV2)
{
address aToken = bAssetToPToken[_bAsset];
require(aToken != address(0), "aToken does not exist");
return IAaveATokenV2(aToken);
}
/**
* @dev Get the total bAsset value held in the platform
* @param _aToken aToken for which to check balance
* @return balance Total value of the bAsset in the platform
*/
function _checkBalance(IAaveATokenV2 _aToken)
internal
view
returns (uint256 balance)
{
return _aToken.balanceOf(address(this));
}
}
|
Deposit a quantity of bAsset into the platform. Credited aTokens remain here in the vault. Can only be called by whitelisted addresses (mAsset and corresponding BasketManager) _bAsset Address for the bAsset _amount Units of bAsset to deposit _hasTxFee Is the bAsset known to have a tx fee? return quantityDeposited Quantity of bAsset that entered the platform/ If we charge a fee, account for it
|
function deposit(
address _bAsset,
uint256 _amount,
bool _hasTxFee
)
external
override
onlyLP
nonReentrant
returns (uint256 quantityDeposited)
{
require(_amount > 0, "Must deposit something");
IAaveATokenV2 aToken = _getATokenFor(_bAsset);
quantityDeposited = _amount;
if(_hasTxFee) {
uint256 prevBal = _checkBalance(aToken);
_getLendingPool().deposit(_bAsset, _amount, address(this), 36);
uint256 newBal = _checkBalance(aToken);
quantityDeposited = _min(quantityDeposited, newBal - prevBal);
_getLendingPool().deposit(_bAsset, _amount, address(this), 36);
}
emit Deposit(_bAsset, address(aToken), quantityDeposited);
}
| 6,975,991 |
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPool.sol";
import "../cover/Quotation.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "./MCR.sol";
contract Pool is IPool, MasterAware, ReentrancyGuard {
using Address for address;
using SafeMath for uint;
using SafeERC20 for IERC20;
struct AssetData {
uint112 minAmount;
uint112 maxAmount;
uint32 lastSwapTime;
// 18 decimals of precision. 0.01% -> 0.0001 -> 1e14
uint maxSlippageRatio;
}
/* storage */
address[] public assets;
mapping(address => AssetData) public assetData;
// contracts
Quotation public quotation;
NXMToken public nxmToken;
TokenController public tokenController;
MCR public mcr;
// parameters
address public swapController;
uint public minPoolEth;
PriceFeedOracle public priceFeedOracle;
address public swapOperator;
/* constants */
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant MCR_RATIO_DECIMALS = 4;
uint public constant MAX_MCR_RATIO = 40000; // 400%
uint public constant MAX_BUY_SELL_MCR_ETH_FRACTION = 500; // 5%. 4 decimal points
uint internal constant CONSTANT_C = 5800000;
uint internal constant CONSTANT_A = 1028 * 1e13;
uint internal constant TOKEN_EXPONENT = 4;
/* events */
event Payout(address indexed to, address indexed asset, uint amount);
event NXMSold (address indexed member, uint nxmIn, uint ethOut);
event NXMBought (address indexed member, uint ethIn, uint nxmOut);
event Swapped(address indexed fromAsset, address indexed toAsset, uint amountIn, uint amountOut);
/* logic */
modifier onlySwapOperator {
require(msg.sender == swapOperator, "Pool: not swapOperator");
_;
}
constructor (
address[] memory _assets,
uint112[] memory _minAmounts,
uint112[] memory _maxAmounts,
uint[] memory _maxSlippageRatios,
address _master,
address _priceOracle,
address _swapOperator
) public {
require(_assets.length == _minAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxSlippageRatios.length, "Pool: length mismatch");
for (uint i = 0; i < _assets.length; i++) {
address asset = _assets[i];
require(asset != address(0), "Pool: asset is zero address");
require(_maxAmounts[i] >= _minAmounts[i], "Pool: max < min");
require(_maxSlippageRatios[i] <= 1 ether, "Pool: max < min");
assets.push(asset);
assetData[asset].minAmount = _minAmounts[i];
assetData[asset].maxAmount = _maxAmounts[i];
assetData[asset].maxSlippageRatio = _maxSlippageRatios[i];
}
master = INXMMaster(_master);
priceFeedOracle = PriceFeedOracle(_priceOracle);
swapOperator = _swapOperator;
}
// fallback function
function() external payable {}
// for legacy Pool1 upgrade compatibility
function sendEther() external payable {}
/**
* @dev Calculates total value of all pool assets in ether
*/
function getPoolValueInEth() public view returns (uint) {
uint total = address(this).balance;
for (uint i = 0; i < assets.length; i++) {
address assetAddress = assets[i];
IERC20 token = IERC20(assetAddress);
uint rate = priceFeedOracle.getAssetToEthRate(assetAddress);
require(rate > 0, "Pool: zero rate");
uint assetBalance = token.balanceOf(address(this));
uint assetValue = assetBalance.mul(rate).div(1e18);
total = total.add(assetValue);
}
return total;
}
/* asset related functions */
function getAssets() external view returns (address[] memory) {
return assets;
}
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
) {
AssetData memory data = assetData[_asset];
return (data.minAmount, data.maxAmount, data.lastSwapTime, data.maxSlippageRatio);
}
function addAsset(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_asset != address(0), "Pool: asset is zero address");
require(_max >= _min, "Pool: max < min");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
require(_asset != assets[i], "Pool: asset exists");
}
assets.push(_asset);
assetData[_asset] = AssetData(_min, _max, 0, _maxSlippageRatio);
}
function removeAsset(address _asset) external onlyGovernance {
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
delete assetData[_asset];
assets[i] = assets[assets.length - 1];
assets.pop();
return;
}
revert("Pool: asset not found");
}
function setAssetDetails(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_min <= _max, "Pool: min > max");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
assetData[_asset].minAmount = _min;
assetData[_asset].maxAmount = _max;
assetData[_asset].maxSlippageRatio = _maxSlippageRatio;
return;
}
revert("Pool: asset not found");
}
/* claim related functions */
/**
* @dev Execute the payout in case a claim is accepted
* @param asset token address or 0xEee...EEeE for ether
* @param payoutAddress send funds to this address
* @param amount amount to send
*/
function sendClaimPayout (
address asset,
address payable payoutAddress,
uint amount
) external onlyInternal nonReentrant returns (bool success) {
bool ok;
if (asset == ETH) {
// solhint-disable-next-line avoid-low-level-calls
(ok, /* data */) = payoutAddress.call.value(amount)("");
} else {
ok = _safeTokenTransfer(asset, payoutAddress, amount);
}
if (ok) {
emit Payout(payoutAddress, asset, amount);
}
return ok;
}
/**
* @dev safeTransfer implementation that does not revert
* @param tokenAddress ERC20 address
* @param to destination
* @param value amount to send
* @return success true if the transfer was successfull
*/
function _safeTokenTransfer (
address tokenAddress,
address to,
uint256 value
) internal returns (bool) {
// token address is not a contract
if (!tokenAddress.isContract()) {
return false;
}
IERC20 token = IERC20(tokenAddress);
bytes memory data = abi.encodeWithSelector(token.transfer.selector, to, value);
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = tokenAddress.call(data);
// low-level call failed/reverted
if (!success) {
return false;
}
// tokens that don't have return data
if (returndata.length == 0) {
return true;
}
// tokens that have return data will return a bool
return abi.decode(returndata, (bool));
}
/* pool lifecycle functions */
function transferAsset(
address asset,
address payable destination,
uint amount
) external onlyGovernance nonReentrant {
require(assetData[asset].maxAmount == 0, "Pool: max not zero");
require(destination != address(0), "Pool: dest zero");
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferableAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferableAmount);
}
function upgradeCapitalPool(address payable newPoolAddress) external onlyMaster nonReentrant {
// transfer ether
uint ethBalance = address(this).balance;
(bool ok, /* data */) = newPoolAddress.call.value(ethBalance)("");
require(ok, "Pool: transfer failed");
// transfer assets
for (uint i = 0; i < assets.length; i++) {
IERC20 token = IERC20(assets[i]);
uint tokenBalance = token.balanceOf(address(this));
token.safeTransfer(newPoolAddress, tokenBalance);
}
}
/**
* @dev Update dependent contract address
* @dev Implements MasterAware interface function
*/
function changeDependentContractAddress() public {
nxmToken = NXMToken(master.tokenAddress());
tokenController = TokenController(master.getLatestAddress("TC"));
quotation = Quotation(master.getLatestAddress("QT"));
mcr = MCR(master.getLatestAddress("MC"));
}
/* cover purchase functions */
/// @dev Enables user to purchase cover with funding in ETH.
/// @param smartCAdd Smart Contract Address
function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public payable onlyMember whenNotPaused {
require(coverCurr == "ETH", "Pool: Unexpected asset type");
require(msg.value == coverDetails[1], "Pool: ETH amount does not match premium");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @dev Enables user to purchase cover via currency asset eg DAI
*/
function makeCoverUsingCA(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyMember whenNotPaused {
require(coverCurr != "ETH", "Pool: Unexpected asset type");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
function transferAssetFrom (address asset, address from, uint amount) public onlyInternal whenNotPaused {
IERC20 token = IERC20(asset);
token.safeTransferFrom(from, address(this), amount);
}
function transferAssetToSwapOperator (address asset, uint amount) public onlySwapOperator nonReentrant whenNotPaused {
if (asset == ETH) {
(bool ok, /* data */) = swapOperator.call.value(amount)("");
require(ok, "Pool: Eth transfer failed");
return;
}
IERC20 token = IERC20(asset);
token.safeTransfer(swapOperator, amount);
}
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) public onlySwapOperator whenNotPaused {
assetData[asset].lastSwapTime = lastSwapTime;
}
/* token sale functions */
/**
* @dev (DEPRECATED, use sellTokens function instead) Allows selling of NXM for ether.
* Seller first needs to give this contract allowance to
* transfer/burn tokens in the NXMToken contract
* @param _amount Amount of NXM to sell
* @return success returns true on successfull sale
*/
function sellNXMTokens(uint _amount) public onlyMember whenNotPaused returns (bool success) {
sellNXM(_amount, 0);
return true;
}
/**
* @dev (DEPRECATED, use calculateNXMForEth function instead) Returns the amount of wei a seller will get for selling NXM
* @param amount Amount of NXM to sell
* @return weiToPay Amount of wei the seller will get
*/
function getWei(uint amount) external view returns (uint weiToPay) {
return getEthForNXM(amount);
}
/**
* @dev Buys NXM tokens with ETH.
* @param minTokensOut Minimum amount of tokens to be bought. Revert if boughtTokens falls below this number.
* @return boughtTokens number of bought tokens.
*/
function buyNXM(uint minTokensOut) public payable onlyMember whenNotPaused {
uint ethIn = msg.value;
require(ethIn > 0, "Pool: ethIn > 0");
uint totalAssetValue = getPoolValueInEth().sub(ethIn);
uint mcrEth = mcr.getMCR();
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
require(mcrRatio <= MAX_MCR_RATIO, "Pool: Cannot purchase if MCR% > 400%");
uint tokensOut = calculateNXMForEth(ethIn, totalAssetValue, mcrEth);
require(tokensOut >= minTokensOut, "Pool: tokensOut is less than minTokensOut");
tokenController.mint(msg.sender, tokensOut);
// evaluate the new MCR for the current asset value including the ETH paid in
mcr.updateMCRInternal(totalAssetValue.add(ethIn), false);
emit NXMBought(msg.sender, ethIn, tokensOut);
}
/**
* @dev Sell NXM tokens and receive ETH.
* @param tokenAmount Amount of tokens to sell.
* @param minEthOut Minimum amount of ETH to be received. Revert if ethOut falls below this number.
* @return ethOut amount of ETH received in exchange for the tokens.
*/
function sellNXM(uint tokenAmount, uint minEthOut) public onlyMember nonReentrant whenNotPaused {
require(nxmToken.balanceOf(msg.sender) >= tokenAmount, "Pool: Not enough balance");
require(nxmToken.isLockedForMV(msg.sender) <= now, "Pool: NXM tokens are locked for voting");
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint ethOut = calculateEthForNXM(tokenAmount, currentTotalAssetValue, mcrEth);
require(currentTotalAssetValue.sub(ethOut) >= mcrEth, "Pool: MCR% cannot fall below 100%");
require(ethOut >= minEthOut, "Pool: ethOut < minEthOut");
tokenController.burnFrom(msg.sender, tokenAmount);
(bool ok, /* data */) = msg.sender.call.value(ethOut)("");
require(ok, "Pool: Sell transfer failed");
// evaluate the new MCR for the current asset value excluding the paid out ETH
mcr.updateMCRInternal(currentTotalAssetValue.sub(ethOut), false);
emit NXMSold(msg.sender, tokenAmount, ethOut);
}
/**
* @dev Get value in tokens for an ethAmount purchase.
* @param ethAmount amount of ETH used for buying.
* @return tokenValue tokens obtained by buying worth of ethAmount
*/
function getNXMForEth(
uint ethAmount
) public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateNXMForEth(ethAmount, totalAssetValue, mcrEth);
}
function calculateNXMForEth(
uint ethAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Purchases worth higher than 5% of MCReth are not allowed"
);
/*
The price formula is:
P(V) = A + MCReth / C * MCR% ^ 4
where MCR% = V / MCReth
P(V) = A + 1 / (C * MCReth ^ 3) * V ^ 4
To compute the number of tokens issued we can integrate with respect to V the following:
ΔT = ΔV / P(V)
which assumes that for an infinitesimally small change in locked value V price is constant and we
get an infinitesimally change in token supply ΔT.
This is not computable on-chain, below we use an approximation that works well assuming
* MCR% stays within [100%, 400%]
* ethAmount <= 5% * MCReth
Use a simplified formula excluding the constant A price offset to compute the amount of tokens to be minted.
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
For a very small variation in tokens ΔT, we have, ΔT = ΔV / P(V), to get total T we integrate with respect to V.
adjustedTokenAmount = ∫ (dV / AdjustedP(V)) from V0 (currentTotalAssetValue) to V1 (nextTotalAssetValue)
adjustedTokenAmount = ∫ ((C * MCReth ^ 3) / V ^ 4 * dV) from V0 to V1
Evaluating the above using the antiderivative of the function we get:
adjustedTokenAmount = - MCReth ^ 3 * C / (3 * V1 ^3) + MCReth * C /(3 * V0 ^ 3)
*/
if (currentTotalAssetValue == 0 || mcrEth.div(currentTotalAssetValue) > 1e12) {
/*
If the currentTotalAssetValue = 0, adjustedTokenPrice approaches 0. Therefore we can assume the price is A.
If currentTotalAssetValue is far smaller than mcrEth, MCR% approaches 0, let the price be A (baseline price).
This avoids overflow in the calculateIntegralAtPoint computation.
This approximation is safe from arbitrage since at MCR% < 100% no sells are possible.
*/
uint tokenPrice = CONSTANT_A;
return ethAmount.mul(1e18).div(tokenPrice);
}
// MCReth * C /(3 * V0 ^ 3)
uint point0 = calculateIntegralAtPoint(currentTotalAssetValue, mcrEth);
// MCReth * C / (3 * V1 ^3)
uint nextTotalAssetValue = currentTotalAssetValue.add(ethAmount);
uint point1 = calculateIntegralAtPoint(nextTotalAssetValue, mcrEth);
uint adjustedTokenAmount = point0.sub(point1);
/*
Compute a preliminary adjustedTokenPrice for the minted tokens based on the adjustedTokenAmount above,
and to that add the A constant (the price offset previously removed in the adjusted Price formula)
to obtain the finalPrice and ultimately the tokenValue based on the finalPrice.
adjustedPrice = ethAmount / adjustedTokenAmount
finalPrice = adjustedPrice + A
tokenValue = ethAmount / finalPrice
*/
// ethAmount is multiplied by 1e18 to cancel out the multiplication factor of 1e18 of the adjustedTokenAmount
uint adjustedTokenPrice = ethAmount.mul(1e18).div(adjustedTokenAmount);
uint tokenPrice = adjustedTokenPrice.add(CONSTANT_A);
return ethAmount.mul(1e18).div(tokenPrice);
}
/**
* @dev integral(V) = MCReth ^ 3 * C / (3 * V ^ 3) * 1e18
* computation result is multiplied by 1e18 to allow for a precision of 18 decimals.
* NOTE: omits the minus sign of the correct integral to use a uint result type for simplicity
* WARNING: this low-level function should be called from a contract which checks that
* mcrEth / assetValue < 1e17 (no overflow) and assetValue != 0
*/
function calculateIntegralAtPoint(
uint assetValue,
uint mcrEth
) internal pure returns (uint) {
return CONSTANT_C
.mul(1e18)
.div(3)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue);
}
function getEthForNXM(uint nxmAmount) public view returns (uint ethAmount) {
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateEthForNXM(nxmAmount, currentTotalAssetValue, mcrEth);
}
/**
* @dev Computes token sell value for a tokenAmount in ETH with a sell spread of 2.5%.
* for values in ETH of the sale <= 1% * MCReth the sell spread is very close to the exact value of 2.5%.
* for values higher than that sell spread may exceed 2.5%
* (The higher amount being sold at any given time the higher the spread)
*/
function calculateEthForNXM(
uint nxmAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
// Step 1. Calculate spot price at current values and amount of ETH if tokens are sold at that price
uint spotPrice0 = calculateTokenSpotPrice(currentTotalAssetValue, mcrEth);
uint spotEthAmount = nxmAmount.mul(spotPrice0).div(1e18);
// Step 2. Calculate spot price using V = currentTotalAssetValue - spotEthAmount from step 1
uint totalValuePostSpotPriceSell = currentTotalAssetValue.sub(spotEthAmount);
uint spotPrice1 = calculateTokenSpotPrice(totalValuePostSpotPriceSell, mcrEth);
// Step 3. Min [average[Price(0), Price(1)] x ( 1 - Sell Spread), Price(1) ]
// Sell Spread = 2.5%
uint averagePriceWithSpread = spotPrice0.add(spotPrice1).div(2).mul(975).div(1000);
uint finalPrice = averagePriceWithSpread < spotPrice1 ? averagePriceWithSpread : spotPrice1;
uint ethAmount = finalPrice.mul(nxmAmount).div(1e18);
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Sales worth more than 5% of MCReth are not allowed"
);
return ethAmount;
}
function calculateMCRRatio(uint totalAssetValue, uint mcrEth) public pure returns (uint) {
return totalAssetValue.mul(10 ** MCR_RATIO_DECIMALS).div(mcrEth);
}
/**
* @dev Calculates token price in ETH 1 NXM token. TokenPrice = A + (MCReth / C) * MCR%^4
*/
function calculateTokenSpotPrice(uint totalAssetValue, uint mcrEth) public pure returns (uint tokenPrice) {
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
uint precisionDecimals = 10 ** TOKEN_EXPONENT.mul(MCR_RATIO_DECIMALS);
return mcrEth
.mul(mcrRatio ** TOKEN_EXPONENT)
.div(CONSTANT_C)
.div(precisionDecimals)
.add(CONSTANT_A);
}
/**
* @dev Returns the NXM price in a given asset
* @param asset Asset name.
*/
function getTokenPrice(address asset) public view returns (uint tokenPrice) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint tokenSpotPriceEth = calculateTokenSpotPrice(totalAssetValue, mcrEth);
return priceFeedOracle.getAssetForEth(asset, tokenSpotPriceEth);
}
function getMCRRatio() public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateMCRRatio(totalAssetValue, mcrEth);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MIN_ETH") {
minPoolEth = value;
return;
}
revert("Pool: unknown parameter");
}
function updateAddressParameters(bytes8 code, address value) external onlyGovernance {
if (code == "SWP_OP") {
swapOperator = value;
return;
}
if (code == "PRC_FEED") {
priceFeedOracle = PriceFeedOracle(value);
return;
}
revert("Pool: unknown parameter");
}
}
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;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be 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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial 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 percetange 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.
_notEntered = true;
}
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/*
Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
*/
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract MasterAware {
INXMMaster public master;
modifier onlyMember {
require(master.isMember(msg.sender), "Caller is not a member");
_;
}
modifier onlyInternal {
require(master.isInternal(msg.sender), "Caller is not an internal contract");
_;
}
modifier onlyMaster {
if (address(master) != address(0)) {
require(address(master) == msg.sender, "Not master");
}
_;
}
modifier onlyGovernance {
require(
master.checkIsAuthToGoverned(msg.sender),
"Caller is not authorized to govern"
);
_;
}
modifier whenPaused {
require(master.isPause(), "System is not paused");
_;
}
modifier whenNotPaused {
require(!master.isPause(), "System is paused");
_;
}
function changeDependentContractAddress() external;
function changeMasterAddress(address masterAddress) public onlyMaster {
master = INXMMaster(masterAddress);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IPool {
function transferAssetToSwapOperator(address asset, uint amount) external;
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
);
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) external;
function minPoolEth() external returns (uint);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../claims/Incidents.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "./QuotationData.sol";
contract Quotation is MasterAware, ReentrancyGuard {
using SafeMath for uint;
ClaimsReward public cr;
Pool public pool;
IPooledStaking public pooledStaking;
QuotationData public qd;
TokenController public tc;
TokenData public td;
Incidents public incidents;
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
cr = ClaimsReward(master.getLatestAddress("CR"));
pool = Pool(master.getLatestAddress("P1"));
pooledStaking = IPooledStaking(master.getLatestAddress("PS"));
qd = QuotationData(master.getLatestAddress("QD"));
tc = TokenController(master.getLatestAddress("TC"));
td = TokenData(master.getLatestAddress("TD"));
incidents = Incidents(master.getLatestAddress("IC"));
}
// solhint-disable-next-line no-empty-blocks
function sendEther() public payable {}
/**
* @dev Expires a cover after a set period of time and changes the status of the cover
* @dev Reduces the total and contract sum assured
* @param coverId Cover Id.
*/
function expireCover(uint coverId) external {
uint expirationDate = qd.getValidityOfCover(coverId);
require(expirationDate < now, "Quotation: cover is not due to expire");
uint coverStatus = qd.getCoverStatusNo(coverId);
require(coverStatus != uint(QuotationData.CoverStatus.CoverExpired), "Quotation: cover already expired");
(/* claim count */, bool hasOpenClaim, /* accepted */) = tc.coverInfo(coverId);
require(!hasOpenClaim, "Quotation: cover has an open claim");
if (coverStatus != uint(QuotationData.CoverStatus.ClaimAccepted)) {
(,, address contractAddress, bytes4 currency, uint amount,) = qd.getCoverDetailsByCoverID1(coverId);
qd.subFromTotalSumAssured(currency, amount);
qd.subFromTotalSumAssuredSC(contractAddress, currency, amount);
}
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.CoverExpired));
}
function withdrawCoverNote(address coverOwner, uint[] calldata coverIds, uint[] calldata reasonIndexes) external {
uint gracePeriod = tc.claimSubmissionGracePeriod();
for (uint i = 0; i < coverIds.length; i++) {
uint expirationDate = qd.getValidityOfCover(coverIds[i]);
require(expirationDate.add(gracePeriod) < now, "Quotation: cannot withdraw before grace period expiration");
}
tc.withdrawCoverNote(coverOwner, coverIds, reasonIndexes);
}
function getWithdrawableCoverNoteCoverIds(
address coverOwner
) public view returns (
uint[] memory expiredCoverIds,
bytes32[] memory lockReasons
) {
uint[] memory coverIds = qd.getAllCoversOfUser(coverOwner);
uint[] memory expiredIdsQueue = new uint[](coverIds.length);
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint expiredQueueLength = 0;
for (uint i = 0; i < coverIds.length; i++) {
uint coverExpirationDate = qd.getValidityOfCover(coverIds[i]);
uint gracePeriodExpirationDate = coverExpirationDate.add(gracePeriod);
(/* claimCount */, bool hasOpenClaim, /* hasAcceptedClaim */) = tc.coverInfo(coverIds[i]);
if (!hasOpenClaim && gracePeriodExpirationDate < now) {
expiredIdsQueue[expiredQueueLength] = coverIds[i];
expiredQueueLength++;
}
}
expiredCoverIds = new uint[](expiredQueueLength);
lockReasons = new bytes32[](expiredQueueLength);
for (uint i = 0; i < expiredQueueLength; i++) {
expiredCoverIds[i] = expiredIdsQueue[i];
lockReasons[i] = keccak256(abi.encodePacked("CN", coverOwner, expiredIdsQueue[i]));
}
}
function getWithdrawableCoverNotesAmount(address coverOwner) external view returns (uint) {
uint withdrawableAmount;
bytes32[] memory lockReasons;
(/*expiredCoverIds*/, lockReasons) = getWithdrawableCoverNoteCoverIds(coverOwner);
for (uint i = 0; i < lockReasons.length; i++) {
uint coverNoteAmount = tc.tokensLocked(coverOwner, lockReasons[i]);
withdrawableAmount = withdrawableAmount.add(coverNoteAmount);
}
return withdrawableAmount;
}
/**
* @dev Makes Cover funded via NXM tokens.
* @param smartCAdd Smart Contract Address
*/
function makeCoverUsingNXMTokens(
uint[] calldata coverDetails,
uint16 coverPeriod,
bytes4 coverCurr,
address smartCAdd,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyMember whenNotPaused {
tc.burnFrom(msg.sender, coverDetails[2]); // needs allowance
_verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s, true);
}
/**
* @dev Verifies cover details signed off chain.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyInternal {
_verifyCoverDetails(
from,
scAddress,
coverCurr,
coverDetails,
coverPeriod,
_v,
_r,
_s,
false
);
}
/**
* @dev Verifies signature.
* @param coverDetails details related to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
* @param _v argument from vrs hash.
* @param _r argument from vrs hash.
* @param _s argument from vrs hash.
*/
function verifySignature(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress,
uint8 _v,
bytes32 _r,
bytes32 _s
) public view returns (bool) {
require(contractAddress != address(0));
bytes32 hash = getOrderHash(coverDetails, coverPeriod, currency, contractAddress);
return isValidSignature(hash, _v, _r, _s);
}
/**
* @dev Gets order hash for given cover details.
* @param coverDetails details realted to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
*/
function getOrderHash(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress
) public view returns (bytes32) {
return keccak256(
abi.encodePacked(
coverDetails[0],
currency,
coverPeriod,
contractAddress,
coverDetails[1],
coverDetails[2],
coverDetails[3],
coverDetails[4],
address(this)
)
);
}
/**
* @dev Verifies signature.
* @param hash order hash
* @param v argument from vrs hash.
* @param r argument from vrs hash.
* @param s argument from vrs hash.
*/
function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns (bool) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
address a = ecrecover(prefixedHash, v, r, s);
return (a == qd.getAuthQuoteEngine());
}
/**
* @dev Creates cover of the quotation, changes the status of the quotation ,
* updates the total sum assured and locks the tokens of the cover against a quote.
* @param from Quote member Ethereum address.
*/
function _makeCover(//solhint-disable-line
address payable from,
address contractAddress,
bytes4 coverCurrency,
uint[] memory coverDetails,
uint16 coverPeriod
) internal {
address underlyingToken = incidents.underlyingToken(contractAddress);
if (underlyingToken != address(0)) {
address coverAsset = cr.getCurrencyAssetAddress(coverCurrency);
require(coverAsset == underlyingToken, "Quotation: Unsupported cover asset for this product");
}
uint cid = qd.getCoverLength();
qd.addCover(
coverPeriod,
coverDetails[0],
from,
coverCurrency,
contractAddress,
coverDetails[1],
coverDetails[2]
);
uint coverNoteAmount = coverDetails[2].mul(qd.tokensRetained()).div(100);
if (underlyingToken == address(0)) {
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint claimSubmissionPeriod = uint(coverPeriod).mul(1 days).add(gracePeriod);
bytes32 reason = keccak256(abi.encodePacked("CN", from, cid));
// mint and lock cover note
td.setDepositCNAmount(cid, coverNoteAmount);
tc.mintCoverNote(from, reason, coverNoteAmount, claimSubmissionPeriod);
} else {
// minted directly to member's wallet
tc.mint(from, coverNoteAmount);
}
qd.addInTotalSumAssured(coverCurrency, coverDetails[0]);
qd.addInTotalSumAssuredSC(contractAddress, coverCurrency, coverDetails[0]);
uint coverPremiumInNXM = coverDetails[2];
uint stakersRewardPercentage = td.stakerCommissionPer();
uint rewardValue = coverPremiumInNXM.mul(stakersRewardPercentage).div(100);
pooledStaking.accumulateReward(contractAddress, rewardValue);
}
/**
* @dev Makes a cover.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function _verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool isNXM
) internal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
address asset = cr.getCurrencyAssetAddress(coverCurr);
if (coverCurr != "ETH" && !isNXM) {
pool.transferAssetFrom(asset, from, coverDetails[1]);
}
require(verifySignature(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod);
}
function createCover(
address payable from,
address scAddress,
bytes4 currency,
uint[] calldata coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyInternal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
require(verifySignature(coverDetails, coverPeriod, currency, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, currency, coverDetails, coverPeriod);
}
// referenced in master, keeping for now
// solhint-disable-next-line no-empty-blocks
function transferAssetsToNewContract(address) external pure {}
function freeUpHeldCovers() external nonReentrant {
IERC20 dai = IERC20(cr.getCurrencyAssetAddress("DAI"));
uint membershipFee = td.joiningFee();
uint lastCoverId = 106;
for (uint id = 1; id <= lastCoverId; id++) {
if (qd.holdedCoverIDStatus(id) != uint(QuotationData.HCIDStatus.kycPending)) {
continue;
}
(/*id*/, /*sc*/, bytes4 currency, /*period*/) = qd.getHoldedCoverDetailsByID1(id);
(/*id*/, address payable userAddress, uint[] memory coverDetails) = qd.getHoldedCoverDetailsByID2(id);
uint refundedETH = membershipFee;
uint coverPremium = coverDetails[1];
if (qd.refundEligible(userAddress)) {
qd.setRefundEligible(userAddress, false);
}
qd.setHoldedCoverIDStatus(id, uint(QuotationData.HCIDStatus.kycFailedOrRefunded));
if (currency == "ETH") {
refundedETH = refundedETH.add(coverPremium);
} else {
require(dai.transfer(userAddress, coverPremium), "Quotation: DAI refund transfer failed");
}
userAddress.transfer(refundedETH);
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface Aggregator {
function latestAnswer() external view returns (int);
}
contract PriceFeedOracle {
using SafeMath for uint;
mapping(address => address) public aggregators;
address public daiAddress;
address public stETH;
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor (
address _daiAggregator,
address _daiAddress,
address _stEthAddress
) public {
aggregators[_daiAddress] = _daiAggregator;
daiAddress = _daiAddress;
stETH = _stEthAddress;
}
/**
* @dev Returns the amount of ether in wei that are equivalent to 1 unit (10 ** decimals) of asset
* @param asset quoted currency
* @return price in ether
*/
function getAssetToEthRate(address asset) public view returns (uint) {
if (asset == ETH || asset == stETH) {
return 1 ether;
}
address aggregatorAddress = aggregators[asset];
if (aggregatorAddress == address(0)) {
revert("PriceFeedOracle: Oracle asset not found");
}
int rate = Aggregator(aggregatorAddress).latestAnswer();
require(rate > 0, "PriceFeedOracle: Rate must be > 0");
return uint(rate);
}
/**
* @dev Returns the amount of currency that is equivalent to ethIn amount of ether.
* @param asset quoted Supported values: ["DAI", "ETH"]
* @param ethIn amount of ether to be converted to the currency
* @return price in ether
*/
function getAssetForEth(address asset, uint ethIn) external view returns (uint) {
if (asset == daiAddress) {
return ethIn.mul(1e18).div(getAssetToEthRate(daiAddress));
}
if (asset == ETH || asset == stETH) {
return ethIn;
}
revert("PriceFeedOracle: Unknown asset");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "./external/OZIERC20.sol";
import "./external/OZSafeMath.sol";
contract NXMToken is OZIERC20 {
using OZSafeMath for uint256;
event WhiteListed(address indexed member);
event BlackListed(address indexed member);
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
mapping(address => bool) public whiteListed;
mapping(address => uint) public isLockedForMV;
uint256 private _totalSupply;
string public name = "NXM";
string public symbol = "NXM";
uint8 public decimals = 18;
address public operator;
modifier canTransfer(address _to) {
require(whiteListed[_to]);
_;
}
modifier onlyOperator() {
if (operator != address(0))
require(msg.sender == operator);
_;
}
constructor(address _founderAddress, uint _initialSupply) public {
_mint(_founderAddress, _initialSupply);
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev 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 increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Adds a user to whitelist
* @param _member address to add to whitelist
*/
function addToWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = true;
emit WhiteListed(_member);
return true;
}
/**
* @dev removes a user from whitelist
* @param _member address to remove from whitelist
*/
function removeFromWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = false;
emit BlackListed(_member);
return true;
}
/**
* @dev change operator address
* @param _newOperator address of new operator
*/
function changeOperator(address _newOperator) public onlyOperator returns (bool) {
operator = _newOperator;
return true;
}
/**
* @dev burns an amount of the tokens of the message sender
* account.
* @param amount The amount that will be burnt.
*/
function burn(uint256 amount) public returns (bool) {
_burn(msg.sender, amount);
return true;
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public returns (bool) {
_burnFrom(from, value);
return true;
}
/**
* @dev function that mints an amount of the token and assigns it to
* an account.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function mint(address account, uint256 amount) public onlyOperator {
_mint(account, 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 canTransfer(to) returns (bool) {
require(isLockedForMV[msg.sender] < now); // if not voted under governance
require(value <= _balances[msg.sender]);
_transfer(to, value);
return true;
}
/**
* @dev Transfer tokens to the operator from the specified address
* @param from The address to transfer from.
* @param value The amount to be transferred.
*/
function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) {
require(value <= _balances[from]);
_transferFrom(from, operator, 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
canTransfer(to)
returns (bool)
{
require(isLockedForMV[from] < now); // if not voted under governance
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
_transferFrom(from, to, value);
return true;
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyOperator {
if (_days.add(now) > isLockedForMV[_of])
isLockedForMV[_of] = _days.add(now);
}
/**
* @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) internal {
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
}
/**
* @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
)
internal
{
_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);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
import "../../interfaces/IPooledStaking.sol";
import "../claims/ClaimsData.sol";
import "./NXMToken.sol";
import "./external/LockHandler.sol";
contract TokenController is LockHandler, Iupgradable {
using SafeMath for uint256;
struct CoverInfo {
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// note: still 224 bits available here, can be used later
}
NXMToken public token;
IPooledStaking public pooledStaking;
uint public minCALockTime;
uint public claimSubmissionGracePeriod;
// coverId => CoverInfo
mapping(uint => CoverInfo) public coverInfo;
event Locked(address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity);
event Unlocked(address indexed _of, bytes32 indexed _reason, uint256 _amount);
event Burned(address indexed member, bytes32 lockedUnder, uint256 amount);
modifier onlyGovernance {
require(msg.sender == ms.getLatestAddress("GV"), "TokenController: Caller is not governance");
_;
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {
token = NXMToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
function markCoverClaimOpen(uint coverId) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// reads all of them using a single SLOAD
(claimCount, hasOpenClaim, hasAcceptedClaim) = (info.claimCount, info.hasOpenClaim, info.hasAcceptedClaim);
// no safemath for uint16 but should be safe from
// overflows as there're max 2 claims per cover
claimCount = claimCount + 1;
require(claimCount <= 2, "TokenController: Max claim count exceeded");
require(hasOpenClaim == false, "TokenController: Cover already has an open claim");
require(hasAcceptedClaim == false, "TokenController: Cover already has accepted claims");
// should use a single SSTORE for both
(info.claimCount, info.hasOpenClaim) = (claimCount, true);
}
/**
* @param coverId cover id (careful, not claim id!)
* @param isAccepted claim verdict
*/
function markCoverClaimClosed(uint coverId, bool isAccepted) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
require(info.hasOpenClaim == true, "TokenController: Cover claim is not marked as open");
// should use a single SSTORE for both
(info.hasOpenClaim, info.hasAcceptedClaim) = (false, isAccepted);
}
/**
* @dev to change the operator address
* @param _newOperator is the new address of operator
*/
function changeOperator(address _newOperator) public onlyInternal {
token.changeOperator(_newOperator);
}
/**
* @dev Proxies token transfer through this contract to allow staking when members are locked for voting
* @param _from Source address
* @param _to Destination address
* @param _value Amount to transfer
*/
function operatorTransfer(address _from, address _to, uint _value) external onlyInternal returns (bool) {
require(msg.sender == address(pooledStaking), "TokenController: Call is only allowed from PooledStaking address");
token.operatorTransfer(_from, _value);
token.transfer(_to, _value);
return true;
}
/**
* @dev Locks a specified amount of tokens,
* for CLA reason and for a specified time
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lockClaimAssessmentTokens(uint256 _amount, uint256 _time) external checkPause {
require(minCALockTime <= _time, "TokenController: Must lock for minimum time");
require(_time <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
// If tokens are already locked, then functions extendLock or
// increaseClaimAssessmentLock should be used to make any changes
_lock(msg.sender, "CLA", _amount, _time);
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
* @param _of address whose tokens are to be locked
*/
function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time)
public
onlyInternal
returns (bool)
{
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(_of, _reason, _amount, _time);
return true;
}
/**
* @dev Mints and locks a specified amount of tokens against an address,
* for a CN reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function mintCoverNote(
address _of,
bytes32 _reason,
uint256 _amount,
uint256 _time
) external onlyInternal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.mint(address(this), _amount);
uint256 lockedUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, lockedUntil, false);
emit Locked(_of, _reason, _amount, lockedUntil);
}
/**
* @dev Extends lock for reason CLA for a specified time
* @param _time Lock extension time in seconds
*/
function extendClaimAssessmentLock(uint256 _time) external checkPause {
uint256 validity = getLockedTokensValidity(msg.sender, "CLA");
require(validity.add(_time).sub(block.timestamp) <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
_extendLock(msg.sender, "CLA", _time);
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLockOf(address _of, bytes32 _reason, uint256 _time)
public
onlyInternal
returns (bool)
{
_extendLock(_of, _reason, _time);
return true;
}
/**
* @dev Increase number of tokens locked for a CLA reason
* @param _amount Number of tokens to be increased
*/
function increaseClaimAssessmentLock(uint256 _amount) external checkPause
{
require(_tokensLocked(msg.sender, "CLA") > 0, "TokenController: No tokens locked");
token.operatorTransfer(msg.sender, _amount);
locked[msg.sender]["CLA"].amount = locked[msg.sender]["CLA"].amount.add(_amount);
emit Locked(msg.sender, "CLA", _amount, locked[msg.sender]["CLA"].validity);
}
/**
* @dev burns tokens of an address
* @param _of is the address to burn tokens of
* @param amount is the amount to burn
* @return the boolean status of the burning process
*/
function burnFrom(address _of, uint amount) public onlyInternal returns (bool) {
return token.burnFrom(_of, amount);
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal {
_burnLockedTokens(_of, _reason, _amount);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal {
_reduceLock(_of, _reason, _time);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
{
_releaseLockedTokens(_of, _reason, _amount);
}
/**
* @dev Adds an address to whitelist maintained in the contract
* @param _member address to add to whitelist
*/
function addToWhitelist(address _member) public onlyInternal {
token.addToWhiteList(_member);
}
/**
* @dev Removes an address from the whitelist in the token
* @param _member address to remove
*/
function removeFromWhitelist(address _member) public onlyInternal {
token.removeFromWhiteList(_member);
}
/**
* @dev Mints new token for an address
* @param _member address to reward the minted tokens
* @param _amount number of tokens to mint
*/
function mint(address _member, uint _amount) public onlyInternal {
token.mint(_member, _amount);
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyInternal {
token.lockForMemberVote(_of, _days);
}
/**
* @dev Unlocks the withdrawable tokens against CLA of a specified address
* @param _of Address of user, claiming back withdrawable tokens against CLA
*/
function withdrawClaimAssessmentTokens(address _of) external checkPause {
uint256 withdrawableTokens = _tokensUnlockable(_of, "CLA");
if (withdrawableTokens > 0) {
locked[_of]["CLA"].claimed = true;
emit Unlocked(_of, "CLA", withdrawableTokens);
token.transfer(_of, withdrawableTokens);
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param value value to set
*/
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MNCLT") {
minCALockTime = value;
return;
}
if (code == "GRACEPER") {
claimSubmissionGracePeriod = value;
return;
}
revert("TokenController: invalid param code");
}
function getLockReasons(address _of) external view returns (bytes32[] memory reasons) {
return lockReason[_of];
}
/**
* @dev Gets the validity of locked tokens of a specified address
* @param _of The address to query the validity
* @param reason reason for which tokens were locked
*/
function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) {
validity = locked[_of][reason].validity;
}
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public
view
returns (uint256 unlockableTokens)
{
for (uint256 i = 0; i < lockReason[_of].length; i++) {
unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i]));
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensLocked(_of, _reason);
}
/**
* @dev Returns tokens locked and validity for a specified address and reason
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLockedWithValidity(address _of, bytes32 _reason)
public
view
returns (uint256 amount, uint256 validity)
{
bool claimed = locked[_of][_reason].claimed;
amount = locked[_of][_reason].amount;
validity = locked[_of][_reason].validity;
if (claimed) {
amount = 0;
}
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensUnlockable(_of, _reason);
}
function totalSupply() public view returns (uint256)
{
return token.totalSupply();
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public
view
returns (uint256 amount)
{
return _tokensLockedAtTime(_of, _reason, _time);
}
/**
* @dev Returns the total amount of tokens held by an address:
* transferable + locked + staked for pooled staking - pending burns.
* Used by Claims and Governance in member voting to calculate the user's vote weight.
*
* @param _of The address to query the total balance of
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of) public view returns (uint256 amount) {
amount = token.balanceOf(_of);
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
uint stakerReward = pooledStaking.stakerReward(_of);
uint stakerDeposit = pooledStaking.stakerDeposit(_of);
amount = amount.add(stakerDeposit).add(stakerReward);
}
/**
* @dev Returns the total amount of locked and staked tokens.
* Used by MemberRoles to check eligibility for withdraw / switch membership.
* Includes tokens locked for claim assessment, tokens staked for risk assessment, and locked cover notes
* Does not take into account pending burns.
* @param _of member whose locked tokens are to be calculate
*/
function totalLockedBalance(address _of) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.operatorTransfer(_of, _amount);
uint256 validUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, validUntil, false);
emit Locked(_of, _reason, _amount, validUntil);
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function _tokensLocked(address _of, bytes32 _reason)
internal
view
returns (uint256 amount)
{
if (!locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
internal
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Extends lock for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function _extendLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount)
{
if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal {
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.burn(_amount);
emit Burned(_of, _reason, _amount);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal
{
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.transfer(_of, _amount);
emit Unlocked(_of, _reason, _amount);
}
function withdrawCoverNote(
address _of,
uint[] calldata _coverIds,
uint[] calldata _indexes
) external onlyInternal {
uint reasonCount = lockReason[_of].length;
uint lastReasonIndex = reasonCount.sub(1, "TokenController: No locked cover notes found");
uint totalAmount = 0;
// The iteration is done from the last to first to prevent reason indexes from
// changing due to the way we delete the items (copy last to current and pop last).
// The provided indexes array must be ordered, otherwise reason index checks will fail.
for (uint i = _coverIds.length; i > 0; i--) {
bool hasOpenClaim = coverInfo[_coverIds[i - 1]].hasOpenClaim;
require(hasOpenClaim == false, "TokenController: Cannot withdraw for cover with an open claim");
// note: cover owner is implicitly checked using the reason hash
bytes32 _reason = keccak256(abi.encodePacked("CN", _of, _coverIds[i - 1]));
uint _reasonIndex = _indexes[i - 1];
require(lockReason[_of][_reasonIndex] == _reason, "TokenController: Bad reason index");
uint amount = locked[_of][_reason].amount;
totalAmount = totalAmount.add(amount);
delete locked[_of][_reason];
if (lastReasonIndex != _reasonIndex) {
lockReason[_of][_reasonIndex] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
emit Unlocked(_of, _reason, amount);
if (lastReasonIndex > 0) {
lastReasonIndex = lastReasonIndex.sub(1, "TokenController: Reason count mismatch");
}
}
token.transfer(_of, totalAmount);
}
function removeEmptyReason(address _of, bytes32 _reason, uint _index) external {
_removeEmptyReason(_of, _reason, _index);
}
function removeMultipleEmptyReasons(
address[] calldata _members,
bytes32[] calldata _reasons,
uint[] calldata _indexes
) external {
require(_members.length == _reasons.length, "TokenController: members and reasons array lengths differ");
require(_reasons.length == _indexes.length, "TokenController: reasons and indexes array lengths differ");
for (uint i = _members.length; i > 0; i--) {
uint idx = i - 1;
_removeEmptyReason(_members[idx], _reasons[idx], _indexes[idx]);
}
}
function _removeEmptyReason(address _of, bytes32 _reason, uint _index) internal {
uint lastReasonIndex = lockReason[_of].length.sub(1, "TokenController: lockReason is empty");
require(lockReason[_of][_index] == _reason, "TokenController: bad reason index");
require(locked[_of][_reason].amount == 0, "TokenController: reason amount is not zero");
if (lastReasonIndex != _index) {
lockReason[_of][_index] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
}
function initialize() external {
require(claimSubmissionGracePeriod == 0, "TokenController: Already initialized");
claimSubmissionGracePeriod = 120 days;
migrate();
}
function migrate() internal {
ClaimsData cd = ClaimsData(ms.getLatestAddress("CD"));
uint totalClaims = cd.actualClaimLength() - 1;
// fix stuck claims 21 & 22
cd.changeFinalVerdict(20, -1);
cd.setClaimStatus(20, 6);
cd.changeFinalVerdict(21, -1);
cd.setClaimStatus(21, 6);
// reduce claim assessment lock period for members locked for more than 180 days
// extracted using scripts/extract-ca-locked-more-than-180.js
address payable[3] memory members = [
0x4a9fA34da6d2378c8f3B9F6b83532B169beaEDFc,
0x6b5DCDA27b5c3d88e71867D6b10b35372208361F,
0x8B6D1e5b4db5B6f9aCcc659e2b9619B0Cd90D617
];
for (uint i = 0; i < members.length; i++) {
if (locked[members[i]]["CLA"].validity > now + 180 days) {
locked[members[i]]["CLA"].validity = now + 180 days;
}
}
for (uint i = 1; i <= totalClaims; i++) {
(/*id*/, uint status) = cd.getClaimStatusNumber(i);
(/*id*/, uint coverId) = cd.getClaimCoverId(i);
int8 verdict = cd.getFinalVerdict(i);
// SLOAD
CoverInfo memory info = coverInfo[coverId];
info.claimCount = info.claimCount + 1;
info.hasAcceptedClaim = (status == 14);
info.hasOpenClaim = (verdict == 0);
// SSTORE
coverInfo[coverId] = info;
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenData.sol";
import "./LegacyMCR.sol";
contract MCR is MasterAware {
using SafeMath for uint;
Pool public pool;
QuotationData public qd;
// sizeof(qd) + 96 = 160 + 96 = 256 (occupies entire slot)
uint96 _unused;
// the following values are expressed in basis points
uint24 public mcrFloorIncrementThreshold = 13000;
uint24 public maxMCRFloorIncrement = 100;
uint24 public maxMCRIncrement = 500;
uint24 public gearingFactor = 48000;
// min update between MCR updates in seconds
uint24 public minUpdateTime = 3600;
uint112 public mcrFloor;
uint112 public mcr;
uint112 public desiredMCR;
uint32 public lastUpdateTime;
LegacyMCR public previousMCR;
event MCRUpdated(
uint mcr,
uint desiredMCR,
uint mcrFloor,
uint mcrETHWithGear,
uint totalSumAssured
);
uint constant UINT24_MAX = ~uint24(0);
uint constant MAX_MCR_ADJUSTMENT = 100;
uint constant BASIS_PRECISION = 10000;
constructor (address masterAddress) public {
changeMasterAddress(masterAddress);
if (masterAddress != address(0)) {
previousMCR = LegacyMCR(master.getLatestAddress("MC"));
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
qd = QuotationData(master.getLatestAddress("QD"));
pool = Pool(master.getLatestAddress("P1"));
initialize();
}
function initialize() internal {
address currentMCR = master.getLatestAddress("MC");
if (address(previousMCR) == address(0) || currentMCR != address(this)) {
// already initialized or not ready for initialization
return;
}
// fetch MCR parameters from previous contract
uint112 minCap = 7000 * 1e18;
mcrFloor = uint112(previousMCR.variableMincap()) + minCap;
mcr = uint112(previousMCR.getLastMCREther());
desiredMCR = mcr;
mcrFloorIncrementThreshold = uint24(previousMCR.dynamicMincapThresholdx100());
maxMCRFloorIncrement = uint24(previousMCR.dynamicMincapIncrementx100());
// set last updated time to now
lastUpdateTime = uint32(block.timestamp);
previousMCR = LegacyMCR(address(0));
}
/**
* @dev Gets total sum assured (in ETH).
* @return amount of sum assured
*/
function getAllSumAssurance() public view returns (uint) {
PriceFeedOracle priceFeed = pool.priceFeedOracle();
address daiAddress = priceFeed.daiAddress();
uint ethAmount = qd.getTotalSumAssured("ETH").mul(1e18);
uint daiAmount = qd.getTotalSumAssured("DAI").mul(1e18);
uint daiRate = priceFeed.getAssetToEthRate(daiAddress);
uint daiAmountInEth = daiAmount.mul(daiRate).div(1e18);
return ethAmount.add(daiAmountInEth);
}
/*
* @dev trigger an MCR update. Current virtual MCR value is synced to storage, mcrFloor is potentially updated
* and a new desiredMCR value to move towards is set.
*
*/
function updateMCR() public {
_updateMCR(pool.getPoolValueInEth(), false);
}
function updateMCRInternal(uint poolValueInEth, bool forceUpdate) public onlyInternal {
_updateMCR(poolValueInEth, forceUpdate);
}
function _updateMCR(uint poolValueInEth, bool forceUpdate) internal {
// read with 1 SLOAD
uint _mcrFloorIncrementThreshold = mcrFloorIncrementThreshold;
uint _maxMCRFloorIncrement = maxMCRFloorIncrement;
uint _gearingFactor = gearingFactor;
uint _minUpdateTime = minUpdateTime;
uint _mcrFloor = mcrFloor;
// read with 1 SLOAD
uint112 _mcr = mcr;
uint112 _desiredMCR = desiredMCR;
uint32 _lastUpdateTime = lastUpdateTime;
if (!forceUpdate && _lastUpdateTime + _minUpdateTime > block.timestamp) {
return;
}
if (block.timestamp > _lastUpdateTime && pool.calculateMCRRatio(poolValueInEth, _mcr) >= _mcrFloorIncrementThreshold) {
// MCR floor updates by up to maxMCRFloorIncrement percentage per day whenever the MCR ratio exceeds 1.3
// MCR floor is monotonically increasing.
uint basisPointsAdjustment = min(
_maxMCRFloorIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days),
_maxMCRFloorIncrement
);
uint newMCRFloor = _mcrFloor.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION);
require(newMCRFloor <= uint112(~0), 'MCR: newMCRFloor overflow');
mcrFloor = uint112(newMCRFloor);
}
// sync the current virtual MCR value to storage
uint112 newMCR = uint112(getMCR());
if (newMCR != _mcr) {
mcr = newMCR;
}
// the desiredMCR cannot fall below the mcrFloor but may have a higher or lower target value based
// on the changes in the totalSumAssured in the system.
uint totalSumAssured = getAllSumAssurance();
uint gearedMCR = totalSumAssured.mul(BASIS_PRECISION).div(_gearingFactor);
uint112 newDesiredMCR = uint112(max(gearedMCR, mcrFloor));
if (newDesiredMCR != _desiredMCR) {
desiredMCR = newDesiredMCR;
}
lastUpdateTime = uint32(block.timestamp);
emit MCRUpdated(mcr, desiredMCR, mcrFloor, gearedMCR, totalSumAssured);
}
/**
* @dev Calculates the current virtual MCR value. The virtual MCR value moves towards the desiredMCR value away
* from the stored mcr value at constant velocity based on how much time passed from the lastUpdateTime.
* The total change in virtual MCR cannot exceed 1% of stored mcr.
*
* This approach allows for the MCR to change smoothly across time without sudden jumps between values, while
* always progressing towards the desiredMCR goal. The desiredMCR can change subject to the call of _updateMCR
* so the virtual MCR value may change direction and start decreasing instead of increasing or vice-versa.
*
* @return mcr
*/
function getMCR() public view returns (uint) {
// read with 1 SLOAD
uint _mcr = mcr;
uint _desiredMCR = desiredMCR;
uint _lastUpdateTime = lastUpdateTime;
if (block.timestamp == _lastUpdateTime) {
return _mcr;
}
uint _maxMCRIncrement = maxMCRIncrement;
uint basisPointsAdjustment = _maxMCRIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days);
basisPointsAdjustment = min(basisPointsAdjustment, MAX_MCR_ADJUSTMENT);
if (_desiredMCR > _mcr) {
return min(_mcr.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION), _desiredMCR);
}
// in case desiredMCR <= mcr
return max(_mcr.mul(BASIS_PRECISION - basisPointsAdjustment).div(BASIS_PRECISION), _desiredMCR);
}
function getGearedMCR() external view returns (uint) {
return getAllSumAssurance().mul(BASIS_PRECISION).div(gearingFactor);
}
function min(uint x, uint y) pure internal returns (uint) {
return x < y ? x : y;
}
function max(uint x, uint y) pure internal returns (uint) {
return x > y ? x : y;
}
/**
* @dev Updates Uint Parameters
* @param code parameter code
* @param val new value
*/
function updateUintParameters(bytes8 code, uint val) public {
require(master.checkIsAuthToGoverned(msg.sender));
if (code == "DMCT") {
require(val <= UINT24_MAX, "MCR: value too large");
mcrFloorIncrementThreshold = uint24(val);
} else if (code == "DMCI") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRFloorIncrement = uint24(val);
} else if (code == "MMIC") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRIncrement = uint24(val);
} else if (code == "GEAR") {
require(val <= UINT24_MAX, "MCR: value too large");
gearingFactor = uint24(val);
} else if (code == "MUTI") {
require(val <= UINT24_MAX, "MCR: value too large");
minUpdateTime = uint24(val);
} else {
revert("Invalid param code");
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract INXMMaster {
address public tokenAddress;
address public owner;
uint public pauseTime;
function delegateCallBack(bytes32 myid) external;
function masterInitialized() public view returns (bool);
function isInternal(address _add) public view returns (bool);
function isPause() public view returns (bool check);
function isOwner(address _add) public view returns (bool);
function isMember(address _add) public view returns (bool);
function checkIsAuthToGoverned(address _add) public view returns (bool);
function updatePauseTime(uint _time) public;
function dAppLocker() public view returns (address _add);
function dAppToken() public view returns (address _add);
function getLatestAddress(bytes2 _contractName) public view returns (address payable contractAddress);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
//Claims Reward Contract contains the functions for calculating number of tokens
// that will get rewarded, unlocked or burned depending upon the status of claim.
pragma solidity ^0.5.0;
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../governance/Governance.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Claims.sol";
import "./ClaimsData.sol";
import "../capital/MCR.sol";
contract ClaimsReward is Iupgradable {
using SafeMath for uint;
NXMToken internal tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
Claims internal c1;
ClaimsData internal cd;
Pool internal pool;
Governance internal gv;
IPooledStaking internal pooledStaking;
MemberRoles internal memberRoles;
MCR public mcr;
// assigned in constructor
address public DAI;
// constants
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint private constant DECIMAL1E18 = uint(10) ** 18;
constructor (address masterAddress, address _daiAddress) public {
changeMasterAddress(masterAddress);
DAI = _daiAddress;
}
function changeDependentContractAddress() public onlyInternal {
c1 = Claims(ms.getLatestAddress("CL"));
cd = ClaimsData(ms.getLatestAddress("CD"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
memberRoles = MemberRoles(ms.getLatestAddress("MR"));
pool = Pool(ms.getLatestAddress("P1"));
mcr = MCR(ms.getLatestAddress("MC"));
}
/// @dev Decides the next course of action for a given claim.
function changeClaimStatus(uint claimid) public checkPause onlyInternal {
(, uint coverid) = cd.getClaimCoverId(claimid);
(, uint status) = cd.getClaimStatusNumber(claimid);
// when current status is "Pending-Claim Assessor Vote"
if (status == 0) {
_changeClaimStatusCA(claimid, coverid, status);
} else if (status >= 1 && status <= 5) {
_changeClaimStatusMV(claimid, coverid, status);
} else if (status == 12) {// when current status is "Claim Accepted Payout Pending"
bool payoutSucceeded = attemptClaimPayout(coverid);
if (payoutSucceeded) {
c1.setClaimStatus(claimid, 14);
} else {
c1.setClaimStatus(claimid, 12);
}
}
}
function getCurrencyAssetAddress(bytes4 currency) public view returns (address) {
if (currency == "ETH") {
return ETH;
}
if (currency == "DAI") {
return DAI;
}
revert("ClaimsReward: unknown asset");
}
function attemptClaimPayout(uint coverId) internal returns (bool success) {
uint sumAssured = qd.getCoverSumAssured(coverId);
// TODO: when adding new cover currencies, fetch the correct decimals for this multiplication
uint sumAssuredWei = sumAssured.mul(1e18);
// get asset address
bytes4 coverCurrency = qd.getCurrencyOfCover(coverId);
address asset = getCurrencyAssetAddress(coverCurrency);
// get payout address
address payable coverHolder = qd.getCoverMemberAddress(coverId);
address payable payoutAddress = memberRoles.getClaimPayoutAddress(coverHolder);
// execute the payout
bool payoutSucceeded = pool.sendClaimPayout(asset, payoutAddress, sumAssuredWei);
if (payoutSucceeded) {
// burn staked tokens
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = pool.getTokenPrice(asset);
// note: for new assets "18" needs to be replaced with target asset decimals
uint burnNXMAmount = sumAssuredWei.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnNXMAmount);
// adjust total sum assured
(, address coverContract) = qd.getscAddressOfCover(coverId);
qd.subFromTotalSumAssured(coverCurrency, sumAssured);
qd.subFromTotalSumAssuredSC(coverContract, coverCurrency, sumAssured);
// update MCR since total sum assured and MCR% change
mcr.updateMCRInternal(pool.getPoolValueInEth(), true);
return true;
}
return false;
}
/// @dev Amount of tokens to be rewarded to a user for a particular vote id.
/// @param check 1 -> CA vote, else member vote
/// @param voteid vote id for which reward has to be Calculated
/// @param flag if 1 calculate even if claimed,else don't calculate if already claimed
/// @return tokenCalculated reward to be given for vote id
/// @return lastClaimedCheck true if final verdict is still pending for that voteid
/// @return tokens number of tokens locked under that voteid
/// @return perc percentage of reward to be given.
function getRewardToBeGiven(
uint check,
uint voteid,
uint flag
)
public
view
returns (
uint tokenCalculated,
bool lastClaimedCheck,
uint tokens,
uint perc
)
{
uint claimId;
int8 verdict;
bool claimed;
uint tokensToBeDist;
uint totalTokens;
(tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid);
lastClaimedCheck = false;
int8 claimVerdict = cd.getFinalVerdict(claimId);
if (claimVerdict == 0) {
lastClaimedCheck = true;
}
if (claimVerdict == verdict && (claimed == false || flag == 1)) {
if (check == 1) {
(perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId);
} else {
(, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId);
}
if (perc > 0) {
if (check == 1) {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenCA(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenCA(claimId);
}
} else {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenMV(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenMV(claimId);
}
}
tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100));
}
}
}
/// @dev Transfers all tokens held by contract to a new contract in case of upgrade.
function upgrade(address _newAdd) public onlyInternal {
uint amount = tk.balanceOf(address(this));
if (amount > 0) {
require(tk.transfer(_newAdd, amount));
}
}
/// @dev Total reward in token due for claim by a user.
/// @return total total number of tokens
function getRewardToBeDistributedByUser(address _add) public view returns (uint total) {
uint lengthVote = cd.getVoteAddressCALength(_add);
uint lastIndexCA;
uint lastIndexMV;
uint tokenForVoteId;
uint voteId;
(lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add);
for (uint i = lastIndexCA; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(_add, i);
(tokenForVoteId,,,) = getRewardToBeGiven(1, voteId, 0);
total = total.add(tokenForVoteId);
}
lengthVote = cd.getVoteAddressMemberLength(_add);
for (uint j = lastIndexMV; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(_add, j);
(tokenForVoteId,,,) = getRewardToBeGiven(0, voteId, 0);
total = total.add(tokenForVoteId);
}
return (total);
}
/// @dev Gets reward amount and claiming status for a given claim id.
/// @return reward amount of tokens to user.
/// @return claimed true if already claimed false if yet to be claimed.
function getRewardAndClaimedStatus(uint check, uint claimId) public view returns (uint reward, bool claimed) {
uint voteId;
uint claimid;
uint lengthVote;
if (check == 1) {
lengthVote = cd.getVoteAddressCALength(msg.sender);
for (uint i = 0; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(msg.sender, i);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
} else {
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
for (uint j = 0; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(msg.sender, j);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
}
(reward,,,) = getRewardToBeGiven(check, voteId, 1);
}
/**
* @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance
* Claim assesment, Risk assesment, Governance rewards
*/
function claimAllPendingReward(uint records) public isMemberAndcheckPause {
_claimRewardToBeDistributed(records);
pooledStaking.withdrawReward(msg.sender);
uint governanceRewards = gv.claimReward(msg.sender, records);
if (governanceRewards > 0) {
require(tk.transfer(msg.sender, governanceRewards));
}
}
/**
* @dev Function used to get pending rewards of a particular user address.
* @param _add user address.
* @return total reward amount of the user
*/
function getAllPendingRewardOfUser(address _add) public view returns (uint) {
uint caReward = getRewardToBeDistributedByUser(_add);
uint pooledStakingReward = pooledStaking.stakerReward(_add);
uint governanceReward = gv.getPendingReward(_add);
return caReward.add(pooledStakingReward).add(governanceReward);
}
/// @dev Rewards/Punishes users who participated in Claims assessment.
// Unlocking and burning of the tokens will also depend upon the status of claim.
/// @param claimid Claim Id.
function _rewardAgainstClaim(uint claimid, uint coverid, uint status) internal {
uint premiumNXM = qd.getCoverPremiumNXM(coverid);
uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100); // 20% of premium
uint percCA;
uint percMV;
(percCA, percMV) = cd.getRewardStatus(status);
cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens);
if (percCA > 0 || percMV > 0) {
tc.mint(address(this), distributableTokens);
}
// denied
if (status == 6 || status == 9 || status == 11) {
cd.changeFinalVerdict(claimid, -1);
tc.markCoverClaimClosed(coverid, false);
_burnCoverNoteDeposit(coverid);
// accepted
} else if (status == 7 || status == 8 || status == 10) {
cd.changeFinalVerdict(claimid, 1);
tc.markCoverClaimClosed(coverid, true);
_unlockCoverNote(coverid);
bool payoutSucceeded = attemptClaimPayout(coverid);
// 12 = payout pending, 14 = payout succeeded
uint nextStatus = payoutSucceeded ? 14 : 12;
c1.setClaimStatus(claimid, nextStatus);
}
}
function _burnCoverNoteDeposit(uint coverId) internal {
address _of = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
uint lockedAmount = tc.tokensLocked(_of, reason);
(uint amount,) = td.depositedCN(coverId);
amount = amount.div(2);
// limit burn amount to actual amount locked
uint burnAmount = lockedAmount < amount ? lockedAmount : amount;
if (burnAmount != 0) {
tc.burnLockedTokens(_of, reason, amount);
}
}
function _unlockCoverNote(uint coverId) internal {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
uint lockedCN = tc.tokensLocked(coverHolder, reason);
if (lockedCN != 0) {
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/// @dev Computes the result of Claim Assessors Voting for a given claim id.
function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency.
uint accept;
uint deny;
uint acceptAndDeny;
bool rewardOrPunish;
uint sumAssured;
(, accept) = cd.getClaimVote(claimid, 1);
(, deny) = cd.getClaimVote(claimid, - 1);
acceptAndDeny = accept.add(deny);
accept = accept.mul(100);
deny = deny.mul(100);
if (caTokens == 0) {
status = 3;
} else {
sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
// Min threshold reached tokens used for voting > 5* sum assured
if (caTokens > sumAssured.mul(5)) {
if (accept.div(acceptAndDeny) > 70) {
status = 7;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted));
rewardOrPunish = true;
} else if (deny.div(acceptAndDeny) > 70) {
status = 6;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied));
rewardOrPunish = true;
} else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 4;
} else {
status = 5;
}
} else {
if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 2;
} else {
status = 3;
}
}
}
c1.setClaimStatus(claimid, status);
if (rewardOrPunish) {
_rewardAgainstClaim(claimid, coverid, status);
}
}
}
/// @dev Computes the result of Member Voting for a given claim id.
function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint8 coverStatus;
uint statusOrig = status;
uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency.
// If tokens used for acceptance >50%, claim is accepted
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
uint thresholdUnreached = 0;
// Minimum threshold for member voting is reached only when
// value of tokens used for voting > 5* sum assured of claim id
if (mvTokens < sumAssured.mul(5)) {
thresholdUnreached = 1;
}
uint accept;
(, accept) = cd.getClaimMVote(claimid, 1);
uint deny;
(, deny) = cd.getClaimMVote(claimid, - 1);
if (accept.add(deny) > 0) {
if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 8;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 9;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
}
if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) {
status = 10;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) {
status = 11;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
c1.setClaimStatus(claimid, status);
qd.changeCoverStatusNo(coverid, uint8(coverStatus));
// Reward/Punish Claim Assessors and Members who participated in Claims assessment
_rewardAgainstClaim(claimid, coverid, status);
}
}
/// @dev Allows a user to claim all pending Claims assessment rewards.
function _claimRewardToBeDistributed(uint _records) internal {
uint lengthVote = cd.getVoteAddressCALength(msg.sender);
uint voteid;
uint lastIndex;
(lastIndex,) = cd.getRewardDistributedIndex(msg.sender);
uint total = 0;
uint tokenForVoteId = 0;
bool lastClaimedCheck;
uint _days = td.lockCADays();
bool claimed;
uint counter = 0;
uint claimId;
uint perc;
uint i;
uint lastClaimed = lengthVote;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressCA(msg.sender, i);
(tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (perc > 0 && !claimed) {
counter++;
cd.setRewardClaimed(voteid, true);
} else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) {
(perc,,) = cd.getClaimRewardDetail(claimId);
if (perc == 0) {
counter++;
}
cd.setRewardClaimed(voteid, true);
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexCA(msg.sender, i);
}
else {
cd.setRewardDistributedIndexCA(msg.sender, lastClaimed);
}
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
lastClaimed = lengthVote;
_days = _days.mul(counter);
if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) {
tc.reduceLock(msg.sender, "CLA", _days);
}
(, lastIndex) = cd.getRewardDistributedIndex(msg.sender);
lastClaimed = lengthVote;
counter = 0;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressMember(msg.sender, i);
(tokenForVoteId, lastClaimedCheck,,) = getRewardToBeGiven(0, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (claimed == false && cd.getFinalVerdict(claimId) != 0) {
cd.setRewardClaimed(voteid, true);
counter++;
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (total > 0) {
require(tk.transfer(msg.sender, total));
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexMV(msg.sender, i);
}
else {
cd.setRewardDistributedIndexMV(msg.sender, lastClaimed);
}
}
/**
* @dev Function used to claim the commission earned by the staker.
*/
function _claimStakeCommission(uint _records, address _user) external onlyInternal {
uint total = 0;
uint len = td.getStakerStakedContractLength(_user);
uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user);
uint commissionEarned;
uint commissionRedeemed;
uint maxCommission;
uint lastCommisionRedeemed = len;
uint counter;
uint i;
for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) {
commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i);
commissionEarned = td.getStakerEarnedStakeCommission(_user, i);
maxCommission = td.getStakerInitialStakedAmountOnContract(
_user, i).mul(td.stakerMaxCommissionPer()).div(100);
if (lastCommisionRedeemed == len && maxCommission != commissionEarned)
lastCommisionRedeemed = i;
td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed));
total = total.add(commissionEarned.sub(commissionRedeemed));
counter++;
}
if (lastCommisionRedeemed == len) {
td.setLastCompletedStakeCommissionIndex(_user, i);
} else {
td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed);
}
if (total > 0)
require(tk.transfer(_user, total)); // solhint-disable-line
}
}
/* Copyright (C) 2021 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsData.sol";
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../governance/MemberRoles.sol";
import "../token/TokenController.sol";
import "../capital/MCR.sol";
contract Incidents is MasterAware {
using SafeERC20 for IERC20;
using SafeMath for uint;
struct Incident {
address productId;
uint32 date;
uint priceBefore;
}
// contract identifiers
enum ID {CD, CR, QD, TC, MR, P1, PS, MC}
mapping(uint => address payable) public internalContracts;
Incident[] public incidents;
// product id => underlying token (ex. yDAI -> DAI)
mapping(address => address) public underlyingToken;
// product id => covered token (ex. 0xc7ed.....1 -> yDAI)
mapping(address => address) public coveredToken;
// claim id => payout amount
mapping(uint => uint) public claimPayout;
// product id => accumulated burn amount
mapping(address => uint) public accumulatedBurn;
// burn ratio in bps, ex 2000 for 20%
uint public BURN_RATIO;
// burn ratio in bps
uint public DEDUCTIBLE_RATIO;
uint constant BASIS_PRECISION = 10000;
event ProductAdded(
address indexed productId,
address indexed coveredToken,
address indexed underlyingToken
);
event IncidentAdded(
address indexed productId,
uint incidentDate,
uint priceBefore
);
modifier onlyAdvisoryBoard {
uint abRole = uint(MemberRoles.Role.AdvisoryBoard);
require(
memberRoles().checkRole(msg.sender, abRole),
"Incidents: Caller is not an advisory board member"
);
_;
}
function initialize() external {
require(BURN_RATIO == 0, "Already initialized");
BURN_RATIO = 2000;
DEDUCTIBLE_RATIO = 9000;
}
function addProducts(
address[] calldata _productIds,
address[] calldata _coveredTokens,
address[] calldata _underlyingTokens
) external onlyAdvisoryBoard {
require(
_productIds.length == _coveredTokens.length,
"Incidents: Protocols and covered tokens lengths differ"
);
require(
_productIds.length == _underlyingTokens.length,
"Incidents: Protocols and underyling tokens lengths differ"
);
for (uint i = 0; i < _productIds.length; i++) {
address id = _productIds[i];
require(coveredToken[id] == address(0), "Incidents: covered token is already set");
require(underlyingToken[id] == address(0), "Incidents: underlying token is already set");
coveredToken[id] = _coveredTokens[i];
underlyingToken[id] = _underlyingTokens[i];
emit ProductAdded(id, _coveredTokens[i], _underlyingTokens[i]);
}
}
function incidentCount() external view returns (uint) {
return incidents.length;
}
function addIncident(
address productId,
uint incidentDate,
uint priceBefore
) external onlyGovernance {
address underlying = underlyingToken[productId];
require(underlying != address(0), "Incidents: Unsupported product");
Incident memory incident = Incident(productId, uint32(incidentDate), priceBefore);
incidents.push(incident);
emit IncidentAdded(productId, incidentDate, priceBefore);
}
function redeemPayoutForMember(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address member
) external onlyInternal returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, member);
}
function redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount
) external returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, msg.sender);
}
function _redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address coverOwner
) internal returns (uint claimId, uint payoutAmount, address coverAsset) {
QuotationData qd = quotationData();
Incident memory incident = incidents[incidentId];
uint sumAssured;
bytes4 currency;
{
address productId;
address _coverOwner;
(/* id */, _coverOwner, productId,
currency, sumAssured, /* premiumNXM */
) = qd.getCoverDetailsByCoverID1(coverId);
// check ownership and covered protocol
require(coverOwner == _coverOwner, "Incidents: Not cover owner");
require(productId == incident.productId, "Incidents: Bad incident id");
}
{
uint coverPeriod = uint(qd.getCoverPeriod(coverId)).mul(1 days);
uint coverExpirationDate = qd.getValidityOfCover(coverId);
uint coverStartDate = coverExpirationDate.sub(coverPeriod);
// check cover validity
require(coverStartDate <= incident.date, "Incidents: Cover start date is after the incident");
require(coverExpirationDate >= incident.date, "Incidents: Cover end date is before the incident");
// check grace period
uint gracePeriod = tokenController().claimSubmissionGracePeriod();
require(coverExpirationDate.add(gracePeriod) >= block.timestamp, "Incidents: Grace period has expired");
}
{
// assumes 18 decimals (eth & dai)
uint decimalPrecision = 1e18;
uint maxAmount;
// sumAssured is currently stored without decimals
uint coverAmount = sumAssured.mul(decimalPrecision);
{
// max amount check
uint deductiblePriceBefore = incident.priceBefore.mul(DEDUCTIBLE_RATIO).div(BASIS_PRECISION);
maxAmount = coverAmount.mul(decimalPrecision).div(deductiblePriceBefore);
require(coveredTokenAmount <= maxAmount, "Incidents: Amount exceeds sum assured");
}
// payoutAmount = coveredTokenAmount / maxAmount * coverAmount
// = coveredTokenAmount * coverAmount / maxAmount
payoutAmount = coveredTokenAmount.mul(coverAmount).div(maxAmount);
}
{
TokenController tc = tokenController();
// mark cover as having a successful claim
tc.markCoverClaimOpen(coverId);
tc.markCoverClaimClosed(coverId, true);
// create the claim
ClaimsData cd = claimsData();
claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
cd.setClaimStatus(claimId, 14);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimAccepted));
claimPayout[claimId] = payoutAmount;
}
coverAsset = claimsReward().getCurrencyAssetAddress(currency);
_sendPayoutAndPushBurn(
incident.productId,
address(uint160(coverOwner)),
coveredTokenAmount,
coverAsset,
payoutAmount
);
qd.subFromTotalSumAssured(currency, sumAssured);
qd.subFromTotalSumAssuredSC(incident.productId, currency, sumAssured);
mcr().updateMCRInternal(pool().getPoolValueInEth(), true);
}
function pushBurns(address productId, uint maxIterations) external {
uint burnAmount = accumulatedBurn[productId];
delete accumulatedBurn[productId];
require(burnAmount > 0, "Incidents: No burns to push");
require(maxIterations >= 30, "Incidents: Pass at least 30 iterations");
IPooledStaking ps = pooledStaking();
ps.pushBurn(productId, burnAmount);
ps.processPendingActions(maxIterations);
}
function withdrawAsset(address asset, address destination, uint amount) external onlyGovernance {
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferAmount);
}
function _sendPayoutAndPushBurn(
address productId,
address payable coverOwner,
uint coveredTokenAmount,
address coverAsset,
uint payoutAmount
) internal {
address _coveredToken = coveredToken[productId];
// pull depegged tokens
IERC20(_coveredToken).safeTransferFrom(msg.sender, address(this), coveredTokenAmount);
Pool p1 = pool();
// send the payoutAmount
{
address payable payoutAddress = memberRoles().getClaimPayoutAddress(coverOwner);
bool success = p1.sendClaimPayout(coverAsset, payoutAddress, payoutAmount);
require(success, "Incidents: Payout failed");
}
{
// burn
uint decimalPrecision = 1e18;
uint assetPerNxm = p1.getTokenPrice(coverAsset);
uint maxBurnAmount = payoutAmount.mul(decimalPrecision).div(assetPerNxm);
uint burnAmount = maxBurnAmount.mul(BURN_RATIO).div(BASIS_PRECISION);
accumulatedBurn[productId] = accumulatedBurn[productId].add(burnAmount);
}
}
function claimsData() internal view returns (ClaimsData) {
return ClaimsData(internalContracts[uint(ID.CD)]);
}
function claimsReward() internal view returns (ClaimsReward) {
return ClaimsReward(internalContracts[uint(ID.CR)]);
}
function quotationData() internal view returns (QuotationData) {
return QuotationData(internalContracts[uint(ID.QD)]);
}
function tokenController() internal view returns (TokenController) {
return TokenController(internalContracts[uint(ID.TC)]);
}
function memberRoles() internal view returns (MemberRoles) {
return MemberRoles(internalContracts[uint(ID.MR)]);
}
function pool() internal view returns (Pool) {
return Pool(internalContracts[uint(ID.P1)]);
}
function pooledStaking() internal view returns (IPooledStaking) {
return IPooledStaking(internalContracts[uint(ID.PS)]);
}
function mcr() internal view returns (MCR) {
return MCR(internalContracts[uint(ID.MC)]);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "BURNRATE") {
require(value <= BASIS_PRECISION, "Incidents: Burn ratio cannot exceed 10000");
BURN_RATIO = value;
return;
}
if (code == "DEDUCTIB") {
require(value <= BASIS_PRECISION, "Incidents: Deductible ratio cannot exceed 10000");
DEDUCTIBLE_RATIO = value;
return;
}
revert("Incidents: Invalid parameter");
}
function changeDependentContractAddress() external {
INXMMaster master = INXMMaster(master);
internalContracts[uint(ID.CD)] = master.getLatestAddress("CD");
internalContracts[uint(ID.CR)] = master.getLatestAddress("CR");
internalContracts[uint(ID.QD)] = master.getLatestAddress("QD");
internalContracts[uint(ID.TC)] = master.getLatestAddress("TC");
internalContracts[uint(ID.MR)] = master.getLatestAddress("MR");
internalContracts[uint(ID.P1)] = master.getLatestAddress("P1");
internalContracts[uint(ID.PS)] = master.getLatestAddress("PS");
internalContracts[uint(ID.MC)] = master.getLatestAddress("MC");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract TokenData is Iupgradable {
using SafeMath for uint;
address payable public walletAddress;
uint public lockTokenTimeAfterCoverExp;
uint public bookTime;
uint public lockCADays;
uint public lockMVDays;
uint public scValidDays;
uint public joiningFee;
uint public stakerCommissionPer;
uint public stakerMaxCommissionPer;
uint public tokenExponent;
uint public priceStep;
struct StakeCommission {
uint commissionEarned;
uint commissionRedeemed;
}
struct Stake {
address stakedContractAddress;
uint stakedContractIndex;
uint dateAdd;
uint stakeAmount;
uint unlockedAmount;
uint burnedAmount;
uint unLockableBeforeLastBurn;
}
struct Staker {
address stakerAddress;
uint stakerIndex;
}
struct CoverNote {
uint amount;
bool isDeposited;
}
/**
* @dev mapping of uw address to array of sc address to fetch
* all staked contract address of underwriter, pushing
* data into this array of Stake returns stakerIndex
*/
mapping(address => Stake[]) public stakerStakedContracts;
/**
* @dev mapping of sc address to array of UW address to fetch
* all underwritters of the staked smart contract
* pushing data into this mapped array returns scIndex
*/
mapping(address => Staker[]) public stakedContractStakers;
/**
* @dev mapping of staked contract Address to the array of StakeCommission
* here index of this array is stakedContractIndex
*/
mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission;
mapping(address => uint) public lastCompletedStakeCommission;
/**
* @dev mapping of the staked contract address to the current
* staker index who will receive commission.
*/
mapping(address => uint) public stakedContractCurrentCommissionIndex;
/**
* @dev mapping of the staked contract address to the
* current staker index to burn token from.
*/
mapping(address => uint) public stakedContractCurrentBurnIndex;
/**
* @dev mapping to return true if Cover Note deposited against coverId
*/
mapping(uint => CoverNote) public depositedCN;
mapping(address => uint) internal isBookedTokens;
event Commission(
address indexed stakedContractAddress,
address indexed stakerAddress,
uint indexed scIndex,
uint commissionAmount
);
constructor(address payable _walletAdd) public {
walletAddress = _walletAdd;
bookTime = 12 hours;
joiningFee = 2000000000000000; // 0.002 Ether
lockTokenTimeAfterCoverExp = 35 days;
scValidDays = 250;
lockCADays = 7 days;
lockMVDays = 2 days;
stakerCommissionPer = 20;
stakerMaxCommissionPer = 50;
tokenExponent = 4;
priceStep = 1000;
}
/**
* @dev Change the wallet address which receive Joining Fee
*/
function changeWalletAddress(address payable _address) external onlyInternal {
walletAddress = _address;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "TOKEXP") {
val = tokenExponent;
} else if (code == "TOKSTEP") {
val = priceStep;
} else if (code == "RALOCKT") {
val = scValidDays;
} else if (code == "RACOMM") {
val = stakerCommissionPer;
} else if (code == "RAMAXC") {
val = stakerMaxCommissionPer;
} else if (code == "CABOOKT") {
val = bookTime / (1 hours);
} else if (code == "CALOCKT") {
val = lockCADays / (1 days);
} else if (code == "MVLOCKT") {
val = lockMVDays / (1 days);
} else if (code == "QUOLOCKT") {
val = lockTokenTimeAfterCoverExp / (1 days);
} else if (code == "JOINFEE") {
val = joiningFee;
}
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {//solhint-disable-line
}
/**
* @dev to get the contract staked by a staker
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return the address of staked contract
*/
function getStakerStakedContractByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (address stakedContractAddress)
{
stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
}
/**
* @dev to get the staker's staked burned
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount burned
*/
function getStakerStakedBurnedByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint burnedAmount)
{
burnedAmount = stakerStakedContracts[
_stakerAddress][_stakerIndex].burnedAmount;
}
/**
* @dev to get the staker's staked unlockable before the last burn
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return unlockable staked tokens
*/
function getStakerStakedUnlockableBeforeLastBurnByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint unlockable)
{
unlockable = stakerStakedContracts[
_stakerAddress][_stakerIndex].unLockableBeforeLastBurn;
}
/**
* @dev to get the staker's staked contract index
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return is the index of the smart contract address
*/
function getStakerStakedContractIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint scIndex)
{
scIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
}
/**
* @dev to get the staker index of the staked contract
* @param _stakedContractAddress is the address of the staked contract
* @param _stakedContractIndex is the index of staked contract
* @return is the index of the staker
*/
function getStakedContractStakerIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (uint sIndex)
{
sIndex = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerIndex;
}
/**
* @dev to get the staker's initial staked amount on the contract
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return staked amount
*/
function getStakerInitialStakedAmountOnContract(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakeAmount;
}
/**
* @dev to get the staker's staked contract length
* @param _stakerAddress is the address of the staker
* @return length of staked contract
*/
function getStakerStakedContractLength(
address _stakerAddress
)
public
view
returns (uint length)
{
length = stakerStakedContracts[_stakerAddress].length;
}
/**
* @dev to get the staker's unlocked tokens which were staked
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount
*/
function getStakerUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].unlockedAmount;
}
/**
* @dev pushes the unlocked staked tokens by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount.add(_amount);
}
/**
* @dev pushes the Burned tokens for a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be burned.
*/
function pushBurnedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount.add(_amount);
}
/**
* @dev pushes the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function pushUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn.add(_amount);
}
/**
* @dev sets the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function setUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = _amount;
}
/**
* @dev pushes the earned commission earned by a staker.
* @param _stakerAddress address of staker.
* @param _stakedContractAddress address of smart contract.
* @param _stakedContractIndex index of the staker to distribute commission.
* @param _commissionAmount amount to be given as commission.
*/
function pushEarnedStakeCommissions(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _commissionAmount
)
public
onlyInternal
{
stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex].
commissionEarned = stakedContractStakeCommission[_stakedContractAddress][
_stakedContractIndex].commissionEarned.add(_commissionAmount);
emit Commission(
_stakerAddress,
_stakedContractAddress,
_stakedContractIndex,
_commissionAmount
);
}
/**
* @dev pushes the redeemed commission redeemed by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushRedeemedStakeCommissions(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
uint stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
address stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
stakedContractStakeCommission[stakedContractAddress][stakedContractIndex].
commissionRedeemed = stakedContractStakeCommission[
stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount);
}
/**
* @dev Gets stake commission given to an underwriter
* for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets stake commission redeemed by an underwriter
* for particular staked contract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
* @return commissionEarned total amount given to staker.
*/
function getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalEarnedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionEarned)
{
totalCommissionEarned = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionEarned = totalCommissionEarned.
add(_getStakerEarnedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalReedmedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionRedeemed)
{
totalCommissionRedeemed = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionRedeemed = totalCommissionRedeemed.add(
_getStakerRedeemedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev set flag to deposit/ undeposit cover note
* against a cover Id
* @param coverId coverId of Cover
* @param flag true/false for deposit/undeposit
*/
function setDepositCN(uint coverId, bool flag) public onlyInternal {
if (flag == true) {
require(!depositedCN[coverId].isDeposited, "Cover note already deposited");
}
depositedCN[coverId].isDeposited = flag;
}
/**
* @dev set locked cover note amount
* against a cover Id
* @param coverId coverId of Cover
* @param amount amount of nxm to be locked
*/
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal {
depositedCN[coverId].amount = amount;
}
/**
* @dev to get the staker address on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @param _stakedContractIndex is the index of staked contract's index
* @return address of staker
*/
function getStakedContractStakerByIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (address stakerAddress)
{
stakerAddress = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerAddress;
}
/**
* @dev to get the length of stakers on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @return length in concern
*/
function getStakedContractStakersLength(
address _stakedContractAddress
)
public
view
returns (uint length)
{
length = stakedContractStakers[_stakedContractAddress].length;
}
/**
* @dev Adds a new stake record.
* @param _stakerAddress staker address.
* @param _stakedContractAddress smart contract address.
* @param _amount amountof NXM to be staked.
*/
function addStake(
address _stakerAddress,
address _stakedContractAddress,
uint _amount
)
public
onlyInternal
returns (uint scIndex)
{
scIndex = (stakedContractStakers[_stakedContractAddress].push(
Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1);
stakerStakedContracts[_stakerAddress].push(
Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0));
}
/**
* @dev books the user's tokens for maintaining Assessor Velocity,
* i.e. once a token is used to cast a vote as a Claims assessor,
* @param _of user's address.
*/
function bookCATokens(address _of) public onlyInternal {
require(!isCATokensBooked(_of), "Tokens already booked");
isBookedTokens[_of] = now.add(bookTime);
}
/**
* @dev to know if claim assessor's tokens are booked or not
* @param _of is the claim assessor's address in concern
* @return boolean representing the status of tokens booked
*/
function isCATokensBooked(address _of) public view returns (bool res) {
if (now < isBookedTokens[_of])
res = true;
}
/**
* @dev Sets the index which will receive commission.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentCommissionIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index;
}
/**
* @dev Sets the last complete commission index
* @param _stakerAddress smart contract address.
* @param _index current index.
*/
function setLastCompletedStakeCommissionIndex(
address _stakerAddress,
uint _index
)
public
onlyInternal
{
lastCompletedStakeCommission[_stakerAddress] = _index;
}
/**
* @dev Sets the index till which commission is distrubuted.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentBurnIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentBurnIndex[_stakedContractAddress] = _index;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "TOKEXP") {
_setTokenExponent(val);
} else if (code == "TOKSTEP") {
_setPriceStep(val);
} else if (code == "RALOCKT") {
_changeSCValidDays(val);
} else if (code == "RACOMM") {
_setStakerCommissionPer(val);
} else if (code == "RAMAXC") {
_setStakerMaxCommissionPer(val);
} else if (code == "CABOOKT") {
_changeBookTime(val * 1 hours);
} else if (code == "CALOCKT") {
_changelockCADays(val * 1 days);
} else if (code == "MVLOCKT") {
_changelockMVDays(val * 1 days);
} else if (code == "QUOLOCKT") {
_setLockTokenTimeAfterCoverExp(val * 1 days);
} else if (code == "JOINFEE") {
_setJoiningFee(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev Internal function to get stake commission given to an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionEarned;
}
/**
* @dev Internal function to get stake commission redeemed by an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionRedeemed;
}
/**
* @dev to set the percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerCommissionPer(uint _val) internal {
stakerCommissionPer = _val;
}
/**
* @dev to set the max percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerMaxCommissionPer(uint _val) internal {
stakerMaxCommissionPer = _val;
}
/**
* @dev to set the token exponent value
* @param _val is new value
*/
function _setTokenExponent(uint _val) internal {
tokenExponent = _val;
}
/**
* @dev to set the price step
* @param _val is new value
*/
function _setPriceStep(uint _val) internal {
priceStep = _val;
}
/**
* @dev Changes number of days for which NXM needs to staked in case of underwriting
*/
function _changeSCValidDays(uint _days) internal {
scValidDays = _days;
}
/**
* @dev Changes the time period up to which tokens will be locked.
* Used to generate the validity period of tokens booked by
* a user for participating in claim's assessment/claim's voting.
*/
function _changeBookTime(uint _time) internal {
bookTime = _time;
}
/**
* @dev Changes lock CA days - number of days for which tokens
* are locked while submitting a vote.
*/
function _changelockCADays(uint _val) internal {
lockCADays = _val;
}
/**
* @dev Changes lock MV days - number of days for which tokens are locked
* while submitting a vote.
*/
function _changelockMVDays(uint _val) internal {
lockMVDays = _val;
}
/**
* @dev Changes extra lock period for a cover, post its expiry.
*/
function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
/**
* @dev Set the joining fee for membership
*/
function _setJoiningFee(uint _amount) internal {
joiningFee = _amount;
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract QuotationData is Iupgradable {
using SafeMath for uint;
enum HCIDStatus {NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover}
enum CoverStatus {Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested}
struct Cover {
address payable memberAddress;
bytes4 currencyCode;
uint sumAssured;
uint16 coverPeriod;
uint validUntil;
address scAddress;
uint premiumNXM;
}
struct HoldCover {
uint holdCoverId;
address payable userAddress;
address scAddress;
bytes4 coverCurr;
uint[] coverDetails;
uint16 coverPeriod;
}
address public authQuoteEngine;
mapping(bytes4 => uint) internal currencyCSA;
mapping(address => uint[]) internal userCover;
mapping(address => uint[]) public userHoldedCover;
mapping(address => bool) public refundEligible;
mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd;
mapping(uint => uint8) public coverStatus;
mapping(uint => uint) public holdedCoverIDStatus;
mapping(uint => bool) public timestampRepeated;
Cover[] internal allCovers;
HoldCover[] internal allCoverHolded;
uint public stlp;
uint public stl;
uint public pm;
uint public minDays;
uint public tokensRetained;
address public kycAuthAddress;
event CoverDetailsEvent(
uint indexed cid,
address scAdd,
uint sumAssured,
uint expiry,
uint premium,
uint premiumNXM,
bytes4 curr
);
event CoverStatusEvent(uint indexed cid, uint8 statusNum);
constructor(address _authQuoteAdd, address _kycAuthAdd) public {
authQuoteEngine = _authQuoteAdd;
kycAuthAddress = _kycAuthAdd;
stlp = 90;
stl = 100;
pm = 30;
minDays = 30;
tokensRetained = 10;
allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0));
uint[] memory arr = new uint[](1);
allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0));
}
/// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be added.
function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].sub(_amount);
}
/// @dev Adds the amount in Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be added.
function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].add(_amount);
}
/// @dev sets bit for timestamp to avoid replay attacks.
function setTimestampRepeated(uint _timestamp) external onlyInternal {
timestampRepeated[_timestamp] = true;
}
/// @dev Creates a blank new cover.
function addCover(
uint16 _coverPeriod,
uint _sumAssured,
address payable _userAddress,
bytes4 _currencyCode,
address _scAddress,
uint premium,
uint premiumNXM
)
external
onlyInternal
{
uint expiryDate = now.add(uint(_coverPeriod).mul(1 days));
allCovers.push(Cover(_userAddress, _currencyCode,
_sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM));
uint cid = allCovers.length.sub(1);
userCover[_userAddress].push(cid);
emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode);
}
/// @dev create holded cover which will process after verdict of KYC.
function addHoldCover(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] calldata coverDetails,
uint16 coverPeriod
)
external
onlyInternal
{
uint holdedCoverLen = allCoverHolded.length;
holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending);
allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress,
coverCurr, coverDetails, coverPeriod));
userHoldedCover[from].push(allCoverHolded.length.sub(1));
}
///@dev sets refund eligible bit.
///@param _add user address.
///@param status indicates if user have pending kyc.
function setRefundEligible(address _add, bool status) external onlyInternal {
refundEligible[_add] = status;
}
/// @dev to set current status of particular holded coverID (1 for not completed KYC,
/// 2 for KYC passed, 3 for failed KYC or full refunded,
/// 4 for KYC completed but cover not processed)
function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal {
holdedCoverIDStatus[holdedCoverID] = status;
}
/**
* @dev to set address of kyc authentication
* @param _add is the new address
*/
function setKycAuthAddress(address _add) external onlyInternal {
kycAuthAddress = _add;
}
/// @dev Changes authorised address for generating quote off chain.
function changeAuthQuoteEngine(address _add) external onlyInternal {
authQuoteEngine = _add;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "STLP") {
val = stlp;
} else if (code == "STL") {
val = stl;
} else if (code == "PM") {
val = pm;
} else if (code == "QUOMIND") {
val = minDays;
} else if (code == "QUOTOK") {
val = tokensRetained;
}
}
/// @dev Gets Product details.
/// @return _minDays minimum cover period.
/// @return _PM Profit margin.
/// @return _STL short term Load.
/// @return _STLP short term load period.
function getProductDetails()
external
view
returns (
uint _minDays,
uint _pm,
uint _stl,
uint _stlp
)
{
_minDays = minDays;
_pm = pm;
_stl = stl;
_stlp = stlp;
}
/// @dev Gets total number covers created till date.
function getCoverLength() external view returns (uint len) {
return (allCovers.length);
}
/// @dev Gets Authorised Engine address.
function getAuthQuoteEngine() external view returns (address _add) {
_add = authQuoteEngine;
}
/// @dev Gets the Total Sum Assured amount of a given currency.
function getTotalSumAssured(bytes4 _curr) external view returns (uint amount) {
amount = currencyCSA[_curr];
}
/// @dev Gets all the Cover ids generated by a given address.
/// @param _add User's address.
/// @return allCover array of covers.
function getAllCoversOfUser(address _add) external view returns (uint[] memory allCover) {
return (userCover[_add]);
}
/// @dev Gets total number of covers generated by a given address
function getUserCoverLength(address _add) external view returns (uint len) {
len = userCover[_add].length;
}
/// @dev Gets the status of a given cover.
function getCoverStatusNo(uint _cid) external view returns (uint8) {
return coverStatus[_cid];
}
/// @dev Gets the Cover Period (in days) of a given cover.
function getCoverPeriod(uint _cid) external view returns (uint32 cp) {
cp = allCovers[_cid].coverPeriod;
}
/// @dev Gets the Sum Assured Amount of a given cover.
function getCoverSumAssured(uint _cid) external view returns (uint sa) {
sa = allCovers[_cid].sumAssured;
}
/// @dev Gets the Currency Name in which a given cover is assured.
function getCurrencyOfCover(uint _cid) external view returns (bytes4 curr) {
curr = allCovers[_cid].currencyCode;
}
/// @dev Gets the validity date (timestamp) of a given cover.
function getValidityOfCover(uint _cid) external view returns (uint date) {
date = allCovers[_cid].validUntil;
}
/// @dev Gets Smart contract address of cover.
function getscAddressOfCover(uint _cid) external view returns (uint, address) {
return (_cid, allCovers[_cid].scAddress);
}
/// @dev Gets the owner address of a given cover.
function getCoverMemberAddress(uint _cid) external view returns (address payable _add) {
_add = allCovers[_cid].memberAddress;
}
/// @dev Gets the premium amount of a given cover in NXM.
function getCoverPremiumNXM(uint _cid) external view returns (uint _premiumNXM) {
_premiumNXM = allCovers[_cid].premiumNXM;
}
/// @dev Provides the details of a cover Id
/// @param _cid cover Id
/// @return memberAddress cover user address.
/// @return scAddress smart contract Address
/// @return currencyCode currency of cover
/// @return sumAssured sum assured of cover
/// @return premiumNXM premium in NXM
function getCoverDetailsByCoverID1(
uint _cid
)
external
view
returns (
uint cid,
address _memberAddress,
address _scAddress,
bytes4 _currencyCode,
uint _sumAssured,
uint premiumNXM
)
{
return (
_cid,
allCovers[_cid].memberAddress,
allCovers[_cid].scAddress,
allCovers[_cid].currencyCode,
allCovers[_cid].sumAssured,
allCovers[_cid].premiumNXM
);
}
/// @dev Provides details of a cover Id
/// @param _cid cover Id
/// @return status status of cover.
/// @return sumAssured Sum assurance of cover.
/// @return coverPeriod Cover Period of cover (in days).
/// @return validUntil is validity of cover.
function getCoverDetailsByCoverID2(
uint _cid
)
external
view
returns (
uint cid,
uint8 status,
uint sumAssured,
uint16 coverPeriod,
uint validUntil
)
{
return (
_cid,
coverStatus[_cid],
allCovers[_cid].sumAssured,
allCovers[_cid].coverPeriod,
allCovers[_cid].validUntil
);
}
/// @dev Provides details of a holded cover Id
/// @param _hcid holded cover Id
/// @return scAddress SmartCover address of cover.
/// @return coverCurr currency of cover.
/// @return coverPeriod Cover Period of cover (in days).
function getHoldedCoverDetailsByID1(
uint _hcid
)
external
view
returns (
uint hcid,
address scAddress,
bytes4 coverCurr,
uint16 coverPeriod
)
{
return (
_hcid,
allCoverHolded[_hcid].scAddress,
allCoverHolded[_hcid].coverCurr,
allCoverHolded[_hcid].coverPeriod
);
}
/// @dev Gets total number holded covers created till date.
function getUserHoldedCoverLength(address _add) external view returns (uint) {
return userHoldedCover[_add].length;
}
/// @dev Gets holded cover index by index of user holded covers.
function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) {
return userHoldedCover[_add][index];
}
/// @dev Provides the details of a holded cover Id
/// @param _hcid holded cover Id
/// @return memberAddress holded cover user address.
/// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute.
function getHoldedCoverDetailsByID2(
uint _hcid
)
external
view
returns (
uint hcid,
address payable memberAddress,
uint[] memory coverDetails
)
{
return (
_hcid,
allCoverHolded[_hcid].userAddress,
allCoverHolded[_hcid].coverDetails
);
}
/// @dev Gets the Total Sum Assured amount of a given currency and smart contract address.
function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount) {
amount = currencyCSAOfSCAdd[_add][_curr];
}
//solhint-disable-next-line
function changeDependentContractAddress() public {}
/// @dev Changes the status of a given cover.
/// @param _cid cover Id.
/// @param _stat New status.
function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal {
coverStatus[_cid] = _stat;
emit CoverStatusEvent(_cid, _stat);
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "STLP") {
_changeSTLP(val);
} else if (code == "STL") {
_changeSTL(val);
} else if (code == "PM") {
_changePM(val);
} else if (code == "QUOMIND") {
_changeMinDays(val);
} else if (code == "QUOTOK") {
_setTokensRetained(val);
} else {
revert("Invalid param code");
}
}
/// @dev Changes the existing Profit Margin value
function _changePM(uint _pm) internal {
pm = _pm;
}
/// @dev Changes the existing Short Term Load Period (STLP) value.
function _changeSTLP(uint _stlp) internal {
stlp = _stlp;
}
/// @dev Changes the existing Short Term Load (STL) value.
function _changeSTL(uint _stl) internal {
stl = _stl;
}
/// @dev Changes the existing Minimum cover period (in days)
function _changeMinDays(uint _days) internal {
minDays = _days;
}
/**
* @dev to set the the amount of tokens retained
* @param val is the amount retained
*/
function _setTokensRetained(uint val) internal {
tokensRetained = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface OZIERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library OZSafeMath {
/**
* @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) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract Iupgradable {
INXMMaster public ms;
address public nxMasterAddress;
modifier onlyInternal {
require(ms.isInternal(msg.sender));
_;
}
modifier isMemberAndcheckPause {
require(ms.isPause() == false && ms.isMember(msg.sender) == true);
_;
}
modifier onlyOwner {
require(ms.isOwner(msg.sender));
_;
}
modifier checkPause {
require(ms.isPause() == false);
_;
}
modifier isMember {
require(ms.isMember(msg.sender), "Not member");
_;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public;
/**
* @dev change master address
* @param _masterAddress is the new address
*/
function changeMasterAddress(address _masterAddress) public {
if (address(ms) != address(0)) {
require(address(ms) == msg.sender, "Not master");
}
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
}
pragma solidity ^0.5.0;
interface IPooledStaking {
function accumulateReward(address contractAddress, uint amount) external;
function pushBurn(address contractAddress, uint amount) external;
function hasPendingActions() external view returns (bool);
function processPendingActions(uint maxIterations) external returns (bool finished);
function contractStake(address contractAddress) external view returns (uint);
function stakerReward(address staker) external view returns (uint);
function stakerDeposit(address staker) external view returns (uint);
function stakerContractStake(address staker, address contractAddress) external view returns (uint);
function withdraw(uint amount) external;
function stakerMaxWithdrawable(address stakerAddress) external view returns (uint);
function withdrawReward(address stakerAddress) external;
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract ClaimsData is Iupgradable {
using SafeMath for uint;
struct Claim {
uint coverId;
uint dateUpd;
}
struct Vote {
address voter;
uint tokens;
uint claimId;
int8 verdict;
bool rewardClaimed;
}
struct ClaimsPause {
uint coverid;
uint dateUpd;
bool submit;
}
struct ClaimPauseVoting {
uint claimid;
uint pendingTime;
bool voting;
}
struct RewardDistributed {
uint lastCAvoteIndex;
uint lastMVvoteIndex;
}
struct ClaimRewardDetails {
uint percCA;
uint percMV;
uint tokenToBeDist;
}
struct ClaimTotalTokens {
uint accept;
uint deny;
}
struct ClaimRewardStatus {
uint percCA;
uint percMV;
}
ClaimRewardStatus[] internal rewardStatus;
Claim[] internal allClaims;
Vote[] internal allvotes;
ClaimsPause[] internal claimPause;
ClaimPauseVoting[] internal claimPauseVotingEP;
mapping(address => RewardDistributed) internal voterVoteRewardReceived;
mapping(uint => ClaimRewardDetails) internal claimRewardDetail;
mapping(uint => ClaimTotalTokens) internal claimTokensCA;
mapping(uint => ClaimTotalTokens) internal claimTokensMV;
mapping(uint => int8) internal claimVote;
mapping(uint => uint) internal claimsStatus;
mapping(uint => uint) internal claimState12Count;
mapping(uint => uint[]) internal claimVoteCA;
mapping(uint => uint[]) internal claimVoteMember;
mapping(address => uint[]) internal voteAddressCA;
mapping(address => uint[]) internal voteAddressMember;
mapping(address => uint[]) internal allClaimsByAddress;
mapping(address => mapping(uint => uint)) internal userClaimVoteCA;
mapping(address => mapping(uint => uint)) internal userClaimVoteMember;
mapping(address => uint) public userClaimVotePausedOn;
uint internal claimPauseLastsubmit;
uint internal claimStartVotingFirstIndex;
uint public pendingClaimStart;
uint public claimDepositTime;
uint public maxVotingTime;
uint public minVotingTime;
uint public payoutRetryTime;
uint public claimRewardPerc;
uint public minVoteThreshold;
uint public maxVoteThreshold;
uint public majorityConsensus;
uint public pauseDaysCA;
event ClaimRaise(
uint indexed coverId,
address indexed userAddress,
uint claimId,
uint dateSubmit
);
event VoteCast(
address indexed userAddress,
uint indexed claimId,
bytes4 indexed typeOf,
uint tokens,
uint submitDate,
int8 verdict
);
constructor() public {
pendingClaimStart = 1;
maxVotingTime = 48 * 1 hours;
minVotingTime = 12 * 1 hours;
payoutRetryTime = 24 * 1 hours;
allvotes.push(Vote(address(0), 0, 0, 0, false));
allClaims.push(Claim(0, 0));
claimDepositTime = 7 days;
claimRewardPerc = 20;
minVoteThreshold = 5;
maxVoteThreshold = 10;
majorityConsensus = 70;
pauseDaysCA = 3 days;
_addRewardIncentive();
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function setpendingClaimStart(uint _start) external onlyInternal {
require(pendingClaimStart <= _start);
pendingClaimStart = _start;
}
/**
* @dev Updates the max vote index for which claim assessor has received reward
* @param _voter address of the voter.
* @param caIndex last index till which reward was distributed for CA
*/
function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex;
}
/**
* @dev Used to pause claim assessor activity for 3 days
* @param user Member address whose claim voting ability needs to be paused
*/
function setUserClaimVotePausedOn(address user) external {
require(ms.checkIsAuthToGoverned(msg.sender));
userClaimVotePausedOn[user] = now;
}
/**
* @dev Updates the max vote index for which member has received reward
* @param _voter address of the voter.
* @param mvIndex last index till which reward was distributed for member
*/
function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex;
}
/**
* @param claimid claim id.
* @param percCA reward Percentage reward for claim assessor
* @param percMV reward Percentage reward for members
* @param tokens total tokens to be rewarded
*/
function setClaimRewardDetail(
uint claimid,
uint percCA,
uint percMV,
uint tokens
)
external
onlyInternal
{
claimRewardDetail[claimid].percCA = percCA;
claimRewardDetail[claimid].percMV = percMV;
claimRewardDetail[claimid].tokenToBeDist = tokens;
}
/**
* @dev Sets the reward claim status against a vote id.
* @param _voteid vote Id.
* @param claimed true if reward for vote is claimed, else false.
*/
function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal {
allvotes[_voteid].rewardClaimed = claimed;
}
/**
* @dev Sets the final vote's result(either accepted or declined)of a claim.
* @param _claimId Claim Id.
* @param _verdict 1 if claim is accepted,-1 if declined.
*/
function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal {
claimVote[_claimId] = _verdict;
}
/**
* @dev Creates a new claim.
*/
function addClaim(
uint _claimId,
uint _coverId,
address _from,
uint _nowtime
)
external
onlyInternal
{
allClaims.push(Claim(_coverId, _nowtime));
allClaimsByAddress[_from].push(_claimId);
}
/**
* @dev Add Vote's details of a given claim.
*/
function addVote(
address _voter,
uint _tokens,
uint claimId,
int8 _verdict
)
external
onlyInternal
{
allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false));
}
/**
* @dev Stores the id of the claim assessor vote given to a claim.
* Maintains record of all votes given by all the CA to a claim.
* @param _claimId Claim Id to which vote has given by the CA.
* @param _voteid Vote Id.
*/
function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal {
claimVoteCA[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Claim assessor's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the CA.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteCA(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteCA[_from][_claimId] = _voteid;
voteAddressCA[_from].push(_voteid);
}
/**
* @dev Stores the tokens locked by the Claim Assessors during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the tokens locked by the Members during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the id of the member vote given to a claim.
* Maintains record of all votes given by all the Members to a claim.
* @param _claimId Claim Id to which vote has been given by the Member.
* @param _voteid Vote Id.
*/
function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal {
claimVoteMember[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Member's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the Member.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteMember(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteMember[_from][_claimId] = _voteid;
voteAddressMember[_from].push(_voteid);
}
/**
* @dev Increases the count of failure until payout of a claim is successful.
*/
function updateState12Count(uint _claimId, uint _cnt) external onlyInternal {
claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt);
}
/**
* @dev Sets status of a claim.
* @param _claimId Claim Id.
* @param _stat Status number.
*/
function setClaimStatus(uint _claimId, uint _stat) external onlyInternal {
claimsStatus[_claimId] = _stat;
}
/**
* @dev Sets the timestamp of a given claim at which the Claim's details has been updated.
* @param _claimId Claim Id of claim which has been changed.
* @param _dateUpd timestamp at which claim is updated.
*/
function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal {
allClaims[_claimId].dateUpd = _dateUpd;
}
/**
@dev Queues Claims during Emergency Pause.
*/
function setClaimAtEmergencyPause(
uint _coverId,
uint _dateUpd,
bool _submit
)
external
onlyInternal
{
claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit));
}
/**
* @dev Set submission flag for Claims queued during emergency pause.
* Set to true after EP is turned off and the claim is submitted .
*/
function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal {
claimPause[_index].submit = _submit;
}
/**
* @dev Sets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function setFirstClaimIndexToSubmitAfterEP(
uint _firstClaimIndexToSubmit
)
external
onlyInternal
{
claimPauseLastsubmit = _firstClaimIndexToSubmit;
}
/**
* @dev Sets the pending vote duration for a claim in case of emergency pause.
*/
function setPendingClaimDetails(
uint _claimId,
uint _pendingTime,
bool _voting
)
external
onlyInternal
{
claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting));
}
/**
* @dev Sets voting flag true after claim is reopened for voting after emergency pause.
*/
function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal {
claimPauseVotingEP[_claimId].voting = _vote;
}
/**
* @dev Sets the index from which claim needs to be
* reopened when emergency pause is swithched off.
*/
function setFirstClaimIndexToStartVotingAfterEP(
uint _claimStartVotingFirstIndex
)
external
onlyInternal
{
claimStartVotingFirstIndex = _claimStartVotingFirstIndex;
}
/**
* @dev Calls Vote Event.
*/
function callVoteEvent(
address _userAddress,
uint _claimId,
bytes4 _typeOf,
uint _tokens,
uint _submitDate,
int8 _verdict
)
external
onlyInternal
{
emit VoteCast(
_userAddress,
_claimId,
_typeOf,
_tokens,
_submitDate,
_verdict
);
}
/**
* @dev Calls Claim Event.
*/
function callClaimEvent(
uint _coverId,
address _userAddress,
uint _claimId,
uint _datesubmit
)
external
onlyInternal
{
emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit);
}
/**
* @dev Gets Uint Parameters by parameter code
* @param code whose details we want
* @return string value of the parameter
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "CAMAXVT") {
val = maxVotingTime / (1 hours);
} else if (code == "CAMINVT") {
val = minVotingTime / (1 hours);
} else if (code == "CAPRETRY") {
val = payoutRetryTime / (1 hours);
} else if (code == "CADEPT") {
val = claimDepositTime / (1 days);
} else if (code == "CAREWPER") {
val = claimRewardPerc;
} else if (code == "CAMINTH") {
val = minVoteThreshold;
} else if (code == "CAMAXTH") {
val = maxVoteThreshold;
} else if (code == "CACONPER") {
val = majorityConsensus;
} else if (code == "CAPAUSET") {
val = pauseDaysCA / (1 days);
}
}
/**
* @dev Get claim queued during emergency pause by index.
*/
function getClaimOfEmergencyPauseByIndex(
uint _index
)
external
view
returns (
uint coverId,
uint dateUpd,
bool submit
)
{
coverId = claimPause[_index].coverid;
dateUpd = claimPause[_index].dateUpd;
submit = claimPause[_index].submit;
}
/**
* @dev Gets the Claim's details of given claimid.
*/
function getAllClaimsByIndex(
uint _claimId
)
external
view
returns (
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the vote id of a given claim of a given Claim Assessor.
*/
function getUserClaimVoteCA(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteCA[_add][_claimId];
}
/**
* @dev Gets the vote id of a given claim of a given member.
*/
function getUserClaimVoteMember(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteMember[_add][_claimId];
}
/**
* @dev Gets the count of all votes.
*/
function getAllVoteLength() external view returns (uint voteCount) {
return allvotes.length.sub(1); // Start Index always from 1.
}
/**
* @dev Gets the status number of a given claim.
* @param _claimId Claim id.
* @return statno Status Number.
*/
function getClaimStatusNumber(uint _claimId) external view returns (uint claimId, uint statno) {
return (_claimId, claimsStatus[_claimId]);
}
/**
* @dev Gets the reward percentage to be distributed for a given status id
* @param statusNumber the number of type of status
* @return percCA reward Percentage for claim assessor
* @return percMV reward Percentage for members
*/
function getRewardStatus(uint statusNumber) external view returns (uint percCA, uint percMV) {
return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV);
}
/**
* @dev Gets the number of tries that have been made for a successful payout of a Claim.
*/
function getClaimState12Count(uint _claimId) external view returns (uint num) {
num = claimState12Count[_claimId];
}
/**
* @dev Gets the last update date of a claim.
*/
function getClaimDateUpd(uint _claimId) external view returns (uint dateupd) {
dateupd = allClaims[_claimId].dateUpd;
}
/**
* @dev Gets all Claims created by a user till date.
* @param _member user's address.
* @return claimarr List of Claims id.
*/
function getAllClaimsByAddress(address _member) external view returns (uint[] memory claimarr) {
return allClaimsByAddress[_member];
}
/**
* @dev Gets the number of tokens that has been locked
* while giving vote to a claim by Claim Assessors.
* @param _claimId Claim Id.
* @return accept Total number of tokens when CA accepts the claim.
* @return deny Total number of tokens when CA declines the claim.
*/
function getClaimsTokenCA(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensCA[_claimId].accept,
claimTokensCA[_claimId].deny
);
}
/**
* @dev Gets the number of tokens that have been
* locked while assessing a claim as a member.
* @param _claimId Claim Id.
* @return accept Total number of tokens in acceptance of the claim.
* @return deny Total number of tokens against the claim.
*/
function getClaimsTokenMV(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensMV[_claimId].accept,
claimTokensMV[_claimId].deny
);
}
/**
* @dev Gets the total number of votes cast as Claims assessor for/against a given claim
*/
function getCaClaimVotesToken(uint _claimId) external view returns (uint claimId, uint cnt) {
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets the total number of tokens cast as a member for/against a given claim
*/
function getMemberClaimVotesToken(
uint _claimId
)
external
view
returns (uint claimId, uint cnt)
{
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @dev Provides information of a vote when given its vote id.
* @param _voteid Vote Id.
*/
function getVoteDetails(uint _voteid)
external view
returns (
uint tokens,
uint claimId,
int8 verdict,
bool rewardClaimed
)
{
return (
allvotes[_voteid].tokens,
allvotes[_voteid].claimId,
allvotes[_voteid].verdict,
allvotes[_voteid].rewardClaimed
);
}
/**
* @dev Gets the voter's address of a given vote id.
*/
function getVoterVote(uint _voteid) external view returns (address voter) {
return allvotes[_voteid].voter;
}
/**
* @dev Provides information of a Claim when given its claim id.
* @param _claimId Claim Id.
*/
function getClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
_claimId,
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the total number of votes of a given claim.
* @param _claimId Claim Id.
* @param _ca if 1: votes given by Claim Assessors to a claim,
* else returns the number of votes of given by Members to a claim.
* @return len total number of votes for/against a given claim.
*/
function getClaimVoteLength(
uint _claimId,
uint8 _ca
)
external
view
returns (uint claimId, uint len)
{
claimId = _claimId;
if (_ca == 1)
len = claimVoteCA[_claimId].length;
else
len = claimVoteMember[_claimId].length;
}
/**
* @dev Gets the verdict of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return ver 1 if vote was given in favour,-1 if given in against.
*/
function getVoteVerdict(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (int8 ver)
{
if (_ca == 1)
ver = allvotes[claimVoteCA[_claimId][_index]].verdict;
else
ver = allvotes[claimVoteMember[_claimId][_index]].verdict;
}
/**
* @dev Gets the Number of tokens of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return tok Number of tokens.
*/
function getVoteToken(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (uint tok)
{
if (_ca == 1)
tok = allvotes[claimVoteCA[_claimId][_index]].tokens;
else
tok = allvotes[claimVoteMember[_claimId][_index]].tokens;
}
/**
* @dev Gets the Voter's address of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return voter Voter's address.
*/
function getVoteVoter(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (address voter)
{
if (_ca == 1)
voter = allvotes[claimVoteCA[_claimId][_index]].voter;
else
voter = allvotes[claimVoteMember[_claimId][_index]].voter;
}
/**
* @dev Gets total number of Claims created by a user till date.
* @param _add User's address.
*/
function getUserClaimCount(address _add) external view returns (uint len) {
len = allClaimsByAddress[_add].length;
}
/**
* @dev Calculates number of Claims that are in pending state.
*/
function getClaimLength() external view returns (uint len) {
len = allClaims.length.sub(pendingClaimStart);
}
/**
* @dev Gets the Number of all the Claims created till date.
*/
function actualClaimLength() external view returns (uint len) {
len = allClaims.length;
}
/**
* @dev Gets details of a claim.
* @param _index claim id = pending claim start + given index
* @param _add User's address.
* @return coverid cover against which claim has been submitted.
* @return claimId Claim Id.
* @return voteCA verdict of vote given as a Claim Assessor.
* @return voteMV verdict of vote given as a Member.
* @return statusnumber Status of claim.
*/
function getClaimFromNewStart(
uint _index,
address _add
)
external
view
returns (
uint coverid,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
uint i = pendingClaimStart.add(_index);
coverid = allClaims[i].coverId;
claimId = i;
if (userClaimVoteCA[_add][i] > 0)
voteCA = allvotes[userClaimVoteCA[_add][i]].verdict;
else
voteCA = 0;
if (userClaimVoteMember[_add][i] > 0)
voteMV = allvotes[userClaimVoteMember[_add][i]].verdict;
else
voteMV = 0;
statusnumber = claimsStatus[i];
}
/**
* @dev Gets details of a claim of a user at a given index.
*/
function getUserClaimByIndex(
uint _index,
address _add
)
external
view
returns (
uint status,
uint coverid,
uint claimId
)
{
claimId = allClaimsByAddress[_add][_index];
status = claimsStatus[claimId];
coverid = allClaims[claimId].coverId;
}
/**
* @dev Gets Id of all the votes given to a claim.
* @param _claimId Claim Id.
* @return ca id of all the votes given by Claim assessors to a claim.
* @return mv id of all the votes given by members to a claim.
*/
function getAllVotesForClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint[] memory ca,
uint[] memory mv
)
{
return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]);
}
/**
* @dev Gets Number of tokens deposit in a vote using
* Claim assessor's address and claim id.
* @return tokens Number of deposited tokens.
*/
function getTokensClaim(
address _of,
uint _claimId
)
external
view
returns (
uint claimId,
uint tokens
)
{
return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens);
}
/**
* @param _voter address of the voter.
* @return lastCAvoteIndex last index till which reward was distributed for CA
* @return lastMVvoteIndex last index till which reward was distributed for member
*/
function getRewardDistributedIndex(
address _voter
)
external
view
returns (
uint lastCAvoteIndex,
uint lastMVvoteIndex
)
{
return (
voterVoteRewardReceived[_voter].lastCAvoteIndex,
voterVoteRewardReceived[_voter].lastMVvoteIndex
);
}
/**
* @param claimid claim id.
* @return perc_CA reward Percentage for claim assessor
* @return perc_MV reward Percentage for members
* @return tokens total tokens to be rewarded
*/
function getClaimRewardDetail(
uint claimid
)
external
view
returns (
uint percCA,
uint percMV,
uint tokens
)
{
return (
claimRewardDetail[claimid].percCA,
claimRewardDetail[claimid].percMV,
claimRewardDetail[claimid].tokenToBeDist
);
}
/**
* @dev Gets cover id of a claim.
*/
function getClaimCoverId(uint _claimId) external view returns (uint claimId, uint coverid) {
return (_claimId, allClaims[_claimId].coverId);
}
/**
* @dev Gets total number of tokens staked during voting by Claim Assessors.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter).
*/
function getClaimVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets total number of tokens staked during voting by Members.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens,
* -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or
* deny on the basis of verdict given as parameter).
*/
function getClaimMVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @param _voter address of voteid
* @param index index to get voteid in CA
*/
function getVoteAddressCA(address _voter, uint index) external view returns (uint) {
return voteAddressCA[_voter][index];
}
/**
* @param _voter address of voter
* @param index index to get voteid in member vote
*/
function getVoteAddressMember(address _voter, uint index) external view returns (uint) {
return voteAddressMember[_voter][index];
}
/**
* @param _voter address of voter
*/
function getVoteAddressCALength(address _voter) external view returns (uint) {
return voteAddressCA[_voter].length;
}
/**
* @param _voter address of voter
*/
function getVoteAddressMemberLength(address _voter) external view returns (uint) {
return voteAddressMember[_voter].length;
}
/**
* @dev Gets the Final result of voting of a claim.
* @param _claimId Claim id.
* @return verdict 1 if claim is accepted, -1 if declined.
*/
function getFinalVerdict(uint _claimId) external view returns (int8 verdict) {
return claimVote[_claimId];
}
/**
* @dev Get number of Claims queued for submission during emergency pause.
*/
function getLengthOfClaimSubmittedAtEP() external view returns (uint len) {
len = claimPause.length;
}
/**
* @dev Gets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function getFirstClaimIndexToSubmitAfterEP() external view returns (uint indexToSubmit) {
indexToSubmit = claimPauseLastsubmit;
}
/**
* @dev Gets number of Claims to be reopened for voting post emergency pause period.
*/
function getLengthOfClaimVotingPause() external view returns (uint len) {
len = claimPauseVotingEP.length;
}
/**
* @dev Gets claim details to be reopened for voting after emergency pause.
*/
function getPendingClaimDetailsByIndex(
uint _index
)
external
view
returns (
uint claimId,
uint pendingTime,
bool voting
)
{
claimId = claimPauseVotingEP[_index].claimid;
pendingTime = claimPauseVotingEP[_index].pendingTime;
voting = claimPauseVotingEP[_index].voting;
}
/**
* @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off.
*/
function getFirstClaimIndexToStartVotingAfterEP() external view returns (uint firstindex) {
firstindex = claimStartVotingFirstIndex;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "CAMAXVT") {
_setMaxVotingTime(val * 1 hours);
} else if (code == "CAMINVT") {
_setMinVotingTime(val * 1 hours);
} else if (code == "CAPRETRY") {
_setPayoutRetryTime(val * 1 hours);
} else if (code == "CADEPT") {
_setClaimDepositTime(val * 1 days);
} else if (code == "CAREWPER") {
_setClaimRewardPerc(val);
} else if (code == "CAMINTH") {
_setMinVoteThreshold(val);
} else if (code == "CAMAXTH") {
_setMaxVoteThreshold(val);
} else if (code == "CACONPER") {
_setMajorityConsensus(val);
} else if (code == "CAPAUSET") {
_setPauseDaysCA(val * 1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {}
/**
* @dev Adds status under which a claim can lie.
* @param percCA reward percentage for claim assessor
* @param percMV reward percentage for members
*/
function _pushStatus(uint percCA, uint percMV) internal {
rewardStatus.push(ClaimRewardStatus(percCA, percMV));
}
/**
* @dev adds reward incentive for all possible claim status for Claim assessors and members
*/
function _addRewardIncentive() internal {
_pushStatus(0, 0); // 0 Pending-Claim Assessor Vote
_pushStatus(0, 0); // 1 Pending-Claim Assessor Vote Denied, Pending Member Vote
_pushStatus(0, 0); // 2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote
_pushStatus(0, 0); // 3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote
_pushStatus(0, 0); // 4 Pending-CA Consensus not reached Accept, Pending Member Vote
_pushStatus(0, 0); // 5 Pending-CA Consensus not reached Deny, Pending Member Vote
_pushStatus(100, 0); // 6 Final-Claim Assessor Vote Denied
_pushStatus(100, 0); // 7 Final-Claim Assessor Vote Accepted
_pushStatus(0, 100); // 8 Final-Claim Assessor Vote Denied, MV Accepted
_pushStatus(0, 100); // 9 Final-Claim Assessor Vote Denied, MV Denied
_pushStatus(0, 0); // 10 Final-Claim Assessor Vote Accept, MV Nodecision
_pushStatus(0, 0); // 11 Final-Claim Assessor Vote Denied, MV Nodecision
_pushStatus(0, 0); // 12 Claim Accepted Payout Pending
_pushStatus(0, 0); // 13 Claim Accepted No Payout
_pushStatus(0, 0); // 14 Claim Accepted Payout Done
}
/**
* @dev Sets Maximum time(in seconds) for which claim assessment voting is open
*/
function _setMaxVotingTime(uint _time) internal {
maxVotingTime = _time;
}
/**
* @dev Sets Minimum time(in seconds) for which claim assessment voting is open
*/
function _setMinVotingTime(uint _time) internal {
minVotingTime = _time;
}
/**
* @dev Sets Minimum vote threshold required
*/
function _setMinVoteThreshold(uint val) internal {
minVoteThreshold = val;
}
/**
* @dev Sets Maximum vote threshold required
*/
function _setMaxVoteThreshold(uint val) internal {
maxVoteThreshold = val;
}
/**
* @dev Sets the value considered as Majority Consenus in voting
*/
function _setMajorityConsensus(uint val) internal {
majorityConsensus = val;
}
/**
* @dev Sets the payout retry time
*/
function _setPayoutRetryTime(uint _time) internal {
payoutRetryTime = _time;
}
/**
* @dev Sets percentage of reward given for claim assessment
*/
function _setClaimRewardPerc(uint _val) internal {
claimRewardPerc = _val;
}
/**
* @dev Sets the time for which claim is deposited.
*/
function _setClaimDepositTime(uint _time) internal {
claimDepositTime = _time;
}
/**
* @dev Sets number of days claim assessment will be paused
*/
function _setPauseDaysCA(uint val) internal {
pauseDaysCA = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC1132 interface
* @dev see https://github.com/ethereum/EIPs/issues/1132
*/
contract LockHandler {
/**
* @dev Reasons why a user's tokens have been locked
*/
mapping(address => bytes32[]) public lockReason;
/**
* @dev locked token structure
*/
struct LockToken {
uint256 amount;
uint256 validity;
bool claimed;
}
/**
* @dev Holds number & validity of tokens locked for a given reason for
* a specified address
*/
mapping(address => mapping(bytes32 => LockToken)) public locked;
}
pragma solidity ^0.5.0;
interface LegacyMCR {
function addMCRData(uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate) external;
function addLastMCRData(uint64 date) external;
function changeDependentContractAddress() external;
function getAllSumAssurance() external view returns (uint amount);
function _calVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function calculateStepTokenPrice(bytes4 curr, uint mcrtp) external view returns (uint tokenPrice);
function calculateTokenPrice(bytes4 curr) external view returns (uint tokenPrice);
function calVtpAndMCRtp() external view returns (uint vtp, uint mcrtp);
function calculateVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) external view returns (uint lowerThreshold, uint upperThreshold);
function getMaxSellTokens() external view returns (uint maxTokens);
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val);
function updateUintParameters(bytes8 code, uint val) external;
function variableMincap() external view returns (uint);
function dynamicMincapThresholdx100() external view returns (uint);
function dynamicMincapIncrementx100() external view returns (uint);
function getLastMCREther() external view returns (uint);
}
// /* Copyright (C) 2017 GovBlocks.io
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../token/TokenController.sol";
import "./MemberRoles.sol";
import "./ProposalCategory.sol";
import "./external/IGovernance.sol";
contract Governance is IGovernance, Iupgradable {
using SafeMath for uint;
enum ProposalStatus {
Draft,
AwaitingSolution,
VotingStarted,
Accepted,
Rejected,
Majority_Not_Reached_But_Accepted,
Denied
}
struct ProposalData {
uint propStatus;
uint finalVerdict;
uint category;
uint commonIncentive;
uint dateUpd;
address owner;
}
struct ProposalVote {
address voter;
uint proposalId;
uint dateAdd;
}
struct VoteTally {
mapping(uint => uint) memberVoteValue;
mapping(uint => uint) abVoteValue;
uint voters;
}
struct DelegateVote {
address follower;
address leader;
uint lastUpd;
}
ProposalVote[] internal allVotes;
DelegateVote[] public allDelegation;
mapping(uint => ProposalData) internal allProposalData;
mapping(uint => bytes[]) internal allProposalSolutions;
mapping(address => uint[]) internal allVotesByMember;
mapping(uint => mapping(address => bool)) public rewardClaimed;
mapping(address => mapping(uint => uint)) public memberProposalVote;
mapping(address => uint) public followerDelegation;
mapping(address => uint) internal followerCount;
mapping(address => uint[]) internal leaderDelegation;
mapping(uint => VoteTally) public proposalVoteTally;
mapping(address => bool) public isOpenForDelegation;
mapping(address => uint) public lastRewardClaimed;
bool internal constructorCheck;
uint public tokenHoldingTime;
uint internal roleIdAllowedToCatgorize;
uint internal maxVoteWeigthPer;
uint internal specialResolutionMajPerc;
uint internal maxFollowers;
uint internal totalProposals;
uint internal maxDraftTime;
MemberRoles internal memberRole;
ProposalCategory internal proposalCategory;
TokenController internal tokenInstance;
mapping(uint => uint) public proposalActionStatus;
mapping(uint => uint) internal proposalExecutionTime;
mapping(uint => mapping(address => bool)) public proposalRejectedByAB;
mapping(uint => uint) internal actionRejectedCount;
bool internal actionParamsInitialised;
uint internal actionWaitingTime;
uint constant internal AB_MAJ_TO_REJECT_ACTION = 3;
enum ActionStatus {
Pending,
Accepted,
Rejected,
Executed,
NoAction
}
/**
* @dev Called whenever an action execution is failed.
*/
event ActionFailed (
uint256 proposalId
);
/**
* @dev Called whenever an AB member rejects the action execution.
*/
event ActionRejected (
uint256 indexed proposalId,
address rejectedBy
);
/**
* @dev Checks if msg.sender is proposal owner
*/
modifier onlyProposalOwner(uint _proposalId) {
require(msg.sender == allProposalData[_proposalId].owner, "Not allowed");
_;
}
/**
* @dev Checks if proposal is opened for voting
*/
modifier voteNotStarted(uint _proposalId) {
require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted));
_;
}
/**
* @dev Checks if msg.sender is allowed to create proposal under given category
*/
modifier isAllowed(uint _categoryId) {
require(allowedToCreateProposal(_categoryId), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender is allowed categorize proposal under given category
*/
modifier isAllowedToCategorize() {
require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender had any pending rewards to be claimed
*/
modifier checkPendingRewards {
require(getPendingReward(msg.sender) == 0, "Claim reward");
_;
}
/**
* @dev Event emitted whenever a proposal is categorized
*/
event ProposalCategorized(
uint indexed proposalId,
address indexed categorizedBy,
uint categoryId
);
/**
* @dev Removes delegation of an address.
* @param _add address to undelegate.
*/
function removeDelegation(address _add) external onlyInternal {
_unDelegate(_add);
}
/**
* @dev Creates a new proposal
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
*/
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external isAllowed(_categoryId)
{
require(ms.isMember(msg.sender), "Not Member");
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
}
/**
* @dev Edits the details of an existing proposal
* @param _proposalId Proposal id that details needs to be updated
* @param _proposalDescHash Proposal description hash having long and short description of proposal.
*/
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external onlyProposalOwner(_proposalId)
{
require(
allProposalSolutions[_proposalId].length < 2,
"Not allowed"
);
allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft);
allProposalData[_proposalId].category = 0;
allProposalData[_proposalId].commonIncentive = 0;
emit Proposal(
allProposalData[_proposalId].owner,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
}
/**
* @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
*/
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
external
voteNotStarted(_proposalId) isAllowedToCategorize
{
_categorizeProposal(_proposalId, _categoryId, _incentive);
}
/**
* @dev Submit proposal with solution
* @param _proposalId Proposal id
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external
onlyProposalOwner(_proposalId)
{
require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution));
_proposalSubmission(_proposalId, _solutionHash, _action);
}
/**
* @dev Creates a new proposal with solution
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external isAllowed(_categoryId)
{
uint proposalId = totalProposals;
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
require(_categoryId > 0);
_proposalSubmission(
proposalId,
_solutionHash,
_action
);
}
/**
* @dev Submit a vote on the proposal.
* @param _proposalId to vote upon.
* @param _solutionChosen is the chosen vote.
*/
function submitVote(uint _proposalId, uint _solutionChosen) external {
require(allProposalData[_proposalId].propStatus ==
uint(Governance.ProposalStatus.VotingStarted), "Not allowed");
require(_solutionChosen < allProposalSolutions[_proposalId].length);
_submitVote(_proposalId, _solutionChosen);
}
/**
* @dev Closes the proposal.
* @param _proposalId of proposal to be closed.
*/
function closeProposal(uint _proposalId) external {
uint category = allProposalData[_proposalId].category;
uint _memberRole;
if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now &&
allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
} else {
require(canCloseProposal(_proposalId) == 1);
(, _memberRole,,,,,) = proposalCategory.category(allProposalData[_proposalId].category);
if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) {
_closeAdvisoryBoardVote(_proposalId, category);
} else {
_closeMemberVote(_proposalId, category);
}
}
}
/**
* @dev Claims reward for member.
* @param _memberAddress to claim reward of.
* @param _maxRecords maximum number of records to claim reward for.
_proposals list of proposals of which reward will be claimed.
* @return amount of pending reward.
*/
function claimReward(address _memberAddress, uint _maxRecords)
external returns (uint pendingDAppReward)
{
uint voteId;
address leader;
uint lastUpd;
require(msg.sender == ms.getLatestAddress("CR"));
uint delegationId = followerDelegation[_memberAddress];
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
uint totalVotes = allVotesByMember[leader].length;
uint lastClaimed = totalVotes;
uint j;
uint i;
for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) {
voteId = allVotesByMember[leader][i];
proposalId = allVotes[voteId].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) {
if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) {
if (!rewardClaimed[voteId][_memberAddress]) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
rewardClaimed[voteId][_memberAddress] = true;
j++;
}
} else {
if (lastClaimed == totalVotes) {
lastClaimed = i;
}
}
}
}
if (lastClaimed == totalVotes) {
lastRewardClaimed[_memberAddress] = i;
} else {
lastRewardClaimed[_memberAddress] = lastClaimed;
}
if (j > 0) {
emit RewardClaimed(
_memberAddress,
pendingDAppReward
);
}
}
/**
* @dev Sets delegation acceptance status of individual user
* @param _status delegation acceptance status
*/
function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards {
isOpenForDelegation[msg.sender] = _status;
}
/**
* @dev Delegates vote to an address.
* @param _add is the address to delegate vote to.
*/
function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards {
require(ms.masterInitialized());
require(allDelegation[followerDelegation[_add]].leader == address(0));
if (followerDelegation[msg.sender] > 0) {
require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now);
}
require(!alreadyDelegated(msg.sender));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner)));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)));
require(followerCount[_add] < maxFollowers);
if (allVotesByMember[msg.sender].length > 0) {
require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime)
< now);
}
require(ms.isMember(_add));
require(isOpenForDelegation[_add]);
allDelegation.push(DelegateVote(msg.sender, _add, now));
followerDelegation[msg.sender] = allDelegation.length - 1;
leaderDelegation[_add].push(allDelegation.length - 1);
followerCount[_add]++;
lastRewardClaimed[msg.sender] = allVotesByMember[_add].length;
}
/**
* @dev Undelegates the sender
*/
function unDelegate() external isMemberAndcheckPause checkPendingRewards {
_unDelegate(msg.sender);
}
/**
* @dev Triggers action of accepted proposal after waiting time is finished
*/
function triggerAction(uint _proposalId) external {
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger");
_triggerAction(_proposalId, allProposalData[_proposalId].category);
}
/**
* @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious
*/
function rejectAction(uint _proposalId) external {
require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now);
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted));
require(!proposalRejectedByAB[_proposalId][msg.sender]);
require(
keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category))
!= keccak256(abi.encodeWithSignature("swapABMember(address,address)"))
);
proposalRejectedByAB[_proposalId][msg.sender] = true;
actionRejectedCount[_proposalId]++;
emit ActionRejected(_proposalId, msg.sender);
if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) {
proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected);
}
}
/**
* @dev Sets intial actionWaitingTime value
* To be called after governance implementation has been updated
*/
function setInitialActionParameters() external onlyOwner {
require(!actionParamsInitialised);
actionParamsInitialised = true;
actionWaitingTime = 24 * 1 hours;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "GOVHOLD") {
val = tokenHoldingTime / (1 days);
} else if (code == "MAXFOL") {
val = maxFollowers;
} else if (code == "MAXDRFT") {
val = maxDraftTime / (1 days);
} else if (code == "EPTIME") {
val = ms.pauseTime() / (1 days);
} else if (code == "ACWT") {
val = actionWaitingTime / (1 hours);
}
}
/**
* @dev Gets all details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return category
* @return status
* @return finalVerdict
* @return totalReward
*/
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalRewar
)
{
return (
_proposalId,
allProposalData[_proposalId].category,
allProposalData[_proposalId].propStatus,
allProposalData[_proposalId].finalVerdict,
allProposalData[_proposalId].commonIncentive
);
}
/**
* @dev Gets some details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return number of all proposal solutions
* @return amount of votes
*/
function proposalDetails(uint _proposalId) external view returns (uint, uint, uint) {
return (
_proposalId,
allProposalSolutions[_proposalId].length,
proposalVoteTally[_proposalId].voters
);
}
/**
* @dev Gets solution action on a proposal
* @param _proposalId whose details we want
* @param _solution whose details we want
* @return action of a solution on a proposal
*/
function getSolutionAction(uint _proposalId, uint _solution) external view returns (uint, bytes memory) {
return (
_solution,
allProposalSolutions[_proposalId][_solution]
);
}
/**
* @dev Gets length of propsal
* @return length of propsal
*/
function getProposalLength() external view returns (uint) {
return totalProposals;
}
/**
* @dev Get followers of an address
* @return get followers of an address
*/
function getFollowers(address _add) external view returns (uint[] memory) {
return leaderDelegation[_add];
}
/**
* @dev Gets pending rewards of a member
* @param _memberAddress in concern
* @return amount of pending reward
*/
function getPendingReward(address _memberAddress)
public view returns (uint pendingDAppReward)
{
uint delegationId = followerDelegation[_memberAddress];
address leader;
uint lastUpd;
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) {
if (allVotes[allVotesByMember[leader][i]].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) {
if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) {
proposalId = allVotes[allVotesByMember[leader][i]].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus
> uint(ProposalStatus.VotingStarted)) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
}
}
}
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "GOVHOLD") {
tokenHoldingTime = val * 1 days;
} else if (code == "MAXFOL") {
maxFollowers = val;
} else if (code == "MAXDRFT") {
maxDraftTime = val * 1 days;
} else if (code == "EPTIME") {
ms.updatePauseTime(val * 1 days);
} else if (code == "ACWT") {
actionWaitingTime = val * 1 hours;
} else {
revert("Invalid code");
}
}
/**
* @dev Updates all dependency addresses to latest ones from Master
*/
function changeDependentContractAddress() public {
tokenInstance = TokenController(ms.dAppLocker());
memberRole = MemberRoles(ms.getLatestAddress("MR"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Checks if msg.sender is allowed to create a proposal under given category
*/
function allowedToCreateProposal(uint category) public view returns (bool check) {
if (category == 0)
return true;
uint[] memory mrAllowed;
(,,,, mrAllowed,,) = proposalCategory.category(category);
for (uint i = 0; i < mrAllowed.length; i++) {
if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i]))
return true;
}
}
/**
* @dev Checks if an address is already delegated
* @param _add in concern
* @return bool value if the address is delegated or not
*/
function alreadyDelegated(address _add) public view returns (bool delegated) {
for (uint i = 0; i < leaderDelegation[_add].length; i++) {
if (allDelegation[leaderDelegation[_add][i]].leader == _add) {
return true;
}
}
}
/**
* @dev Checks If the proposal voting time is up and it's ready to close
* i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise!
* @param _proposalId Proposal id to which closing value is being checked
*/
function canCloseProposal(uint _proposalId)
public
view
returns (uint)
{
uint dateUpdate;
uint pStatus;
uint _closingTime;
uint _roleId;
uint majority;
pStatus = allProposalData[_proposalId].propStatus;
dateUpdate = allProposalData[_proposalId].dateUpd;
(, _roleId, majority, , , _closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
if (
pStatus == uint(ProposalStatus.VotingStarted)
) {
uint numberOfMembers = memberRole.numberOfMembers(_roleId);
if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority
|| proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers
|| dateUpdate.add(_closingTime) <= now) {
return 1;
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters
|| dateUpdate.add(_closingTime) <= now)
return 1;
}
} else if (pStatus > uint(ProposalStatus.VotingStarted)) {
return 2;
} else {
return 0;
}
}
/**
* @dev Gets Id of member role allowed to categorize the proposal
* @return roleId allowed to categorize the proposal
*/
function allowedToCatgorize() public view returns (uint roleId) {
return roleIdAllowedToCatgorize;
}
/**
* @dev Gets vote tally data
* @param _proposalId in concern
* @param _solution of a proposal id
* @return member vote value
* @return advisory board vote value
* @return amount of votes
*/
function voteTallyData(uint _proposalId, uint _solution) public view returns (uint, uint, uint) {
return (proposalVoteTally[_proposalId].memberVoteValue[_solution],
proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters);
}
/**
* @dev Internal call to create proposal
* @param _proposalTitle of proposal
* @param _proposalSD is short description of proposal
* @param _proposalDescHash IPFS hash value of propsal
* @param _categoryId of proposal
*/
function _createProposal(
string memory _proposalTitle,
string memory _proposalSD,
string memory _proposalDescHash,
uint _categoryId
)
internal
{
require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0);
uint _proposalId = totalProposals;
allProposalData[_proposalId].owner = msg.sender;
allProposalData[_proposalId].dateUpd = now;
allProposalSolutions[_proposalId].push("");
totalProposals++;
emit Proposal(
msg.sender,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
if (_categoryId > 0)
_categorizeProposal(_proposalId, _categoryId, 0);
}
/**
* @dev Internal call to categorize a proposal
* @param _proposalId of proposal
* @param _categoryId of proposal
* @param _incentive is commonIncentive
*/
function _categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
internal
{
require(
_categoryId > 0 && _categoryId < proposalCategory.totalCategories(),
"Invalid category"
);
allProposalData[_proposalId].category = _categoryId;
allProposalData[_proposalId].commonIncentive = _incentive;
allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution);
emit ProposalCategorized(_proposalId, msg.sender, _categoryId);
}
/**
* @dev Internal call to add solution to a proposal
* @param _proposalId in concern
* @param _action on that solution
* @param _solutionHash string value
*/
function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash)
internal
{
allProposalSolutions[_proposalId].push(_action);
emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now);
}
/**
* @dev Internal call to add solution and open proposal for voting
*/
function _proposalSubmission(
uint _proposalId,
string memory _solutionHash,
bytes memory _action
)
internal
{
uint _categoryId = allProposalData[_proposalId].category;
if (proposalCategory.categoryActionHashes(_categoryId).length == 0) {
require(keccak256(_action) == keccak256(""));
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
_addSolution(
_proposalId,
_action,
_solutionHash
);
_updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted));
(, , , , , uint closingTime,) = proposalCategory.category(_categoryId);
emit CloseProposalOnTime(_proposalId, closingTime.add(now));
}
/**
* @dev Internal call to submit vote
* @param _proposalId of proposal in concern
* @param _solution for that proposal
*/
function _submitVote(uint _proposalId, uint _solution) internal {
uint delegationId = followerDelegation[msg.sender];
uint mrSequence;
uint majority;
uint closingTime;
(, mrSequence, majority, , , closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed");
require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed");
require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) &&
_checkLastUpd(allDelegation[delegationId].lastUpd)));
require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized");
uint totalVotes = allVotes.length;
allVotesByMember[msg.sender].push(totalVotes);
memberProposalVote[msg.sender][_proposalId] = totalVotes;
allVotes.push(ProposalVote(msg.sender, _proposalId, now));
emit Vote(msg.sender, _proposalId, totalVotes, now, _solution);
if (mrSequence == uint(MemberRoles.Role.Owner)) {
if (_solution == 1)
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner);
else
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
} else {
uint numberOfMembers = memberRole.numberOfMembers(mrSequence);
_setVoteTally(_proposalId, _solution, mrSequence);
if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers)
>= majority
|| (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) {
emit VoteCast(_proposalId);
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters)
emit VoteCast(_proposalId);
}
}
}
/**
* @dev Internal call to set vote tally of a proposal
* @param _proposalId of proposal in concern
* @param _solution of proposal in concern
* @param mrSequence number of members for a role
*/
function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal
{
uint categoryABReq;
uint isSpecialResolution;
(, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category);
if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) ||
mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
proposalVoteTally[_proposalId].abVoteValue[_solution]++;
}
tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime);
if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) {
uint voteWeight;
uint voters = 1;
uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender);
uint totalSupply = tokenInstance.totalSupply();
if (isSpecialResolution == 1) {
voteWeight = tokenBalance.add(10 ** 18);
} else {
voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18);
}
DelegateVote memory delegationData;
for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) {
delegationData = allDelegation[leaderDelegation[msg.sender][i]];
if (delegationData.leader == msg.sender &&
_checkLastUpd(delegationData.lastUpd)) {
if (memberRole.checkRole(delegationData.follower, mrSequence)) {
tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower);
tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime);
voters++;
if (isSpecialResolution == 1) {
voteWeight = voteWeight.add(tokenBalance.add(10 ** 18));
} else {
voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18));
}
}
}
}
proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight);
proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters;
}
}
/**
* @dev Gets minimum of two numbers
* @param a one of the two numbers
* @param b one of the two numbers
* @return minimum number out of the two
*/
function _minOf(uint a, uint b) internal pure returns (uint res) {
res = a;
if (res > b)
res = b;
}
/**
* @dev Check the time since last update has exceeded token holding time or not
* @param _lastUpd is last update time
* @return the bool which tells if the time since last update has exceeded token holding time or not
*/
function _checkLastUpd(uint _lastUpd) internal view returns (bool) {
return (now - _lastUpd) > tokenHoldingTime;
}
/**
* @dev Checks if the vote count against any solution passes the threshold value or not.
*/
function _checkForThreshold(uint _proposalId, uint _category) internal view returns (bool check) {
uint categoryQuorumPerc;
uint roleAuthorized;
(, roleAuthorized, , categoryQuorumPerc, , ,) = proposalCategory.category(_category);
check = ((proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1]))
.mul(100))
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18)
)
) >= categoryQuorumPerc;
}
/**
* @dev Called when vote majority is reached
* @param _proposalId of proposal in concern
* @param _status of proposal in concern
* @param category of proposal in concern
* @param max vote value of proposal in concern
*/
function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal {
allProposalData[_proposalId].finalVerdict = max;
_updateProposalStatus(_proposalId, _status);
emit ProposalAccepted(_proposalId);
if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) {
if (role == MemberRoles.Role.AdvisoryBoard) {
_triggerAction(_proposalId, category);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
proposalExecutionTime[_proposalId] = actionWaitingTime.add(now);
}
}
}
/**
* @dev Internal function to trigger action of accepted proposal
*/
function _triggerAction(uint _proposalId, uint _categoryId) internal {
proposalActionStatus[_proposalId] = uint(ActionStatus.Executed);
bytes2 contractName;
address actionAddress;
bytes memory _functionHash;
(, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId);
if (contractName == "MS") {
actionAddress = address(ms);
} else if (contractName != "EX") {
actionAddress = ms.getLatestAddress(contractName);
}
// solhint-disable-next-line avoid-low-level-calls
(bool actionStatus,) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1]));
if (actionStatus) {
emit ActionSuccess(_proposalId);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
emit ActionFailed(_proposalId);
}
}
/**
* @dev Internal call to update proposal status
* @param _proposalId of proposal in concern
* @param _status of proposal to set
*/
function _updateProposalStatus(uint _proposalId, uint _status) internal {
if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) {
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
allProposalData[_proposalId].dateUpd = now;
allProposalData[_proposalId].propStatus = _status;
}
/**
* @dev Internal call to undelegate a follower
* @param _follower is address of follower to undelegate
*/
function _unDelegate(address _follower) internal {
uint followerId = followerDelegation[_follower];
if (followerId > 0) {
followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1);
allDelegation[followerId].leader = address(0);
allDelegation[followerId].lastUpd = now;
lastRewardClaimed[_follower] = allVotesByMember[_follower].length;
}
}
/**
* @dev Internal call to close member voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
} else {
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(,, majorityVote,,,,) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
} else {
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
/**
* @dev Internal call to close advisory board voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal {
uint _majorityVote;
MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard;
(,, _majorityVote,,,,) = proposalCategory.category(category);
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/MasterAware.sol";
import "../cover/QuotationData.sol";
import "./NXMToken.sol";
import "./TokenController.sol";
import "./TokenData.sol";
contract TokenFunctions is MasterAware {
using SafeMath for uint;
TokenController public tc;
NXMToken public tk;
QuotationData public qd;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev to get the all the cover locked tokens of a user
* @param _of is the user address in concern
* @return amount locked
*/
function getUserAllLockedCNTokens(address _of) external view returns (uint) {
uint[] memory coverIds = qd.getAllCoversOfUser(_of);
uint total;
for (uint i = 0; i < coverIds.length; i++) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverIds[i]));
uint coverNote = tc.tokensLocked(_of, reason);
total = total.add(coverNote);
}
return total;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tc = TokenController(master.getLatestAddress("TC"));
tk = NXMToken(master.tokenAddress());
qd = QuotationData(master.getLatestAddress("QD"));
}
/**
* @dev Burns tokens used for fraudulent voting against a claim
* @param claimid Claim Id.
* @param _value number of tokens to be burned
* @param _of Claim Assessor's address.
*/
function burnCAToken(uint claimid, uint _value, address _of) external onlyGovernance {
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to check if a member is locked for member vote
* @param _of is the member address in concern
* @return the boolean status
*/
function isLockedForMemberVote(address _of) public view returns (bool) {
return now < tk.isLockedForMV(_of);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "../token/TokenFunctions.sol";
import "./ClaimsData.sol";
import "./Incidents.sol";
contract Claims is Iupgradable {
using SafeMath for uint;
TokenController internal tc;
ClaimsReward internal cr;
Pool internal p1;
ClaimsData internal cd;
TokenData internal td;
QuotationData internal qd;
Incidents internal incidents;
uint private constant DECIMAL1E18 = uint(10) ** 18;
/**
* @dev Sets the status of claim using claim id.
* @param claimId claim id.
* @param stat status to be set.
*/
function setClaimStatus(uint claimId, uint stat) external onlyInternal {
_setClaimStatus(claimId, stat);
}
/**
* @dev Calculates total amount that has been used to assess a claim.
* Computaion:Adds acceptCA(tokens used for voting in favor of a claim)
* denyCA(tokens used for voting against a claim) * current token price.
* @param claimId Claim Id.
* @param member Member type 0 -> Claim Assessors, else members.
* @return tokens Total Amount used in Claims assessment.
*/
function getCATokens(uint claimId, uint member) external view returns (uint tokens) {
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
if (member == 0) {
(, accept, deny) = cd.getClaimsTokenCA(claimId);
} else {
(, accept, deny) = cd.getClaimsTokenMV(claimId);
}
tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens)
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
p1 = Pool(ms.getLatestAddress("P1"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
cd = ClaimsData(ms.getLatestAddress("CD"));
qd = QuotationData(ms.getLatestAddress("QD"));
incidents = Incidents(ms.getLatestAddress("IC"));
}
/**
* @dev Submits a claim for a given cover note.
* Adds claim to queue incase of emergency pause else directly submits the claim.
* @param coverId Cover Id.
*/
function submitClaim(uint coverId) external {
_submitClaim(coverId, msg.sender);
}
function submitClaimForMember(uint coverId, address member) external onlyInternal {
_submitClaim(coverId, member);
}
function _submitClaim(uint coverId, address member) internal {
require(!ms.isPause(), "Claims: System is paused");
(/* id */, address contractAddress) = qd.getscAddressOfCover(coverId);
address token = incidents.coveredToken(contractAddress);
require(token == address(0), "Claims: Product type does not allow claims");
address coverOwner = qd.getCoverMemberAddress(coverId);
require(coverOwner == member, "Claims: Not cover owner");
uint expirationDate = qd.getValidityOfCover(coverId);
uint gracePeriod = tc.claimSubmissionGracePeriod();
require(expirationDate.add(gracePeriod) > now, "Claims: Grace period has expired");
tc.markCoverClaimOpen(coverId);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted));
uint claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
}
// solhint-disable-next-line no-empty-blocks
function submitClaimAfterEPOff() external pure {}
/**
* @dev Castes vote for members who have tokens locked under Claims Assessment
* @param claimId claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now);
uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime()));
require(tokens > 0);
uint stat;
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat == 0);
require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0);
td.bookCATokens(msg.sender);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict);
uint voteLength = cd.getAllVoteLength();
cd.addClaimVoteCA(claimId, voteLength);
cd.setUserClaimVoteCA(msg.sender, claimId, voteLength);
cd.setClaimTokensCA(claimId, verdict, tokens);
tc.extendLockOf(msg.sender, "CLA", td.lockCADays());
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Submits a member vote for assessing a claim.
* Tokens other than those locked under Claims
* Assessment can be used to cast a vote for a given claim id.
* @param claimId Selected claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
uint stat;
uint tokens = tc.totalBalanceOf(msg.sender);
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat >= 1 && stat <= 5);
require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict);
tc.lockForMemberVote(msg.sender, td.lockMVDays());
uint voteLength = cd.getAllVoteLength();
cd.addClaimVotemember(claimId, voteLength);
cd.setUserClaimVoteMember(msg.sender, claimId, voteLength);
cd.setClaimTokensMV(claimId, verdict, tokens);
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
// solhint-disable-next-line no-empty-blocks
function pauseAllPendingClaimsVoting() external pure {}
// solhint-disable-next-line no-empty-blocks
function startAllPendingClaimsVoting() external pure {}
/**
* @dev Checks if voting of a claim should be closed or not.
* @param claimId Claim Id.
* @return close 1 -> voting should be closed, 0 -> if voting should not be closed,
* -1 -> voting has already been closed.
*/
function checkVoteClosing(uint claimId) public view returns (int8 close) {
close = 0;
uint status;
(, status) = cd.getClaimStatusNumber(claimId);
uint dateUpd = cd.getClaimDateUpd(claimId);
if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) {
if (cd.getClaimState12Count(claimId) < 60)
close = 1;
}
if (status > 5 && status != 12) {
close = - 1;
} else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) {
close = 1;
} else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) {
close = 0;
} else if (status == 0 || (status >= 1 && status <= 5)) {
close = _checkVoteClosingFinal(claimId, status);
}
}
/**
* @dev Checks if voting of a claim should be closed or not.
* Internally called by checkVoteClosing method
* for Claims whose status number is 0 or status number lie between 2 and 6.
* @param claimId Claim Id.
* @param status Current status of claim.
* @return close 1 if voting should be closed,0 in case voting should not be closed,
* -1 if voting has already been closed.
*/
function _checkVoteClosingFinal(uint claimId, uint status) internal view returns (int8 close) {
close = 0;
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
(, accept, deny) = cd.getClaimsTokenCA(claimId);
uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
(, accept, deny) = cd.getClaimsTokenMV(claimId);
uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
if (status == 0 && caTokens >= sumassured.mul(10)) {
close = 1;
} else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) {
close = 1;
}
}
/**
* @dev Changes the status of an existing claim id, based on current
* status and current conditions of the system
* @param claimId Claim Id.
* @param stat status number.
*/
function _setClaimStatus(uint claimId, uint stat) internal {
uint origstat;
uint state12Count;
uint dateUpd;
uint coverId;
(, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId);
(, origstat) = cd.getClaimStatusNumber(claimId);
if (stat == 12 && origstat == 12) {
cd.updateState12Count(claimId, 1);
}
cd.setClaimStatus(claimId, stat);
if (state12Count >= 60 && stat == 12) {
cd.setClaimStatus(claimId, 13);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied));
}
cd.setClaimdateUpd(claimId, now);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Governance.sol";
import "./external/Governed.sol";
contract MemberRoles is Governed, Iupgradable {
TokenController public tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
TokenFunctions internal tf;
NXMToken public tk;
struct MemberRoleDetails {
uint memberCounter;
mapping(address => bool) memberActive;
address[] memberAddress;
address authorized;
}
enum Role {UnAssigned, AdvisoryBoard, Member, Owner}
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);
event ClaimPayoutAddressSet(address indexed member, address indexed payoutAddress);
MemberRoleDetails[] internal memberRoleData;
bool internal constructorCheck;
uint public maxABCount;
bool public launched;
uint public launchedOn;
mapping (address => address payable) internal claimPayoutAddress;
modifier checkRoleAuthority(uint _memberRoleId) {
if (memberRoleData[_memberRoleId].authorized != address(0))
require(msg.sender == memberRoleData[_memberRoleId].authorized);
else
require(isAuthorizedToGovern(msg.sender), "Not Authorized");
_;
}
/**
* @dev to swap advisory board member
* @param _newABAddress is address of new AB member
* @param _removeAB is advisory board member to be removed
*/
function swapABMember(
address _newABAddress,
address _removeAB
)
external
checkRoleAuthority(uint(Role.AdvisoryBoard)) {
_updateRole(_newABAddress, uint(Role.AdvisoryBoard), true);
_updateRole(_removeAB, uint(Role.AdvisoryBoard), false);
}
/**
* @dev to swap the owner address
* @param _newOwnerAddress is the new owner address
*/
function swapOwner(
address _newOwnerAddress
)
external {
require(msg.sender == address(ms));
_updateRole(ms.owner(), uint(Role.Owner), false);
_updateRole(_newOwnerAddress, uint(Role.Owner), true);
}
/**
* @dev is used to add initital advisory board members
* @param abArray is the list of initial advisory board members
*/
function addInitialABMembers(address[] calldata abArray) external onlyOwner {
//Ensure that NXMaster has initialized.
require(ms.masterInitialized());
require(maxABCount >=
SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length)
);
//AB count can't exceed maxABCount
for (uint i = 0; i < abArray.length; i++) {
require(checkRole(abArray[i], uint(MemberRoles.Role.Member)));
_updateRole(abArray[i], uint(Role.AdvisoryBoard), true);
}
}
/**
* @dev to change max number of AB members allowed
* @param _val is the new value to be set
*/
function changeMaxABCount(uint _val) external onlyInternal {
maxABCount = _val;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
td = TokenData(ms.getLatestAddress("TD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
}
/**
* @dev to change the master address
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0)) {
require(masterAddress == msg.sender);
}
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev to initiate the member roles
* @param _firstAB is the address of the first AB member
* @param memberAuthority is the authority (role) of the member
*/
function memberRolesInitiate(address _firstAB, address memberAuthority) public {
require(!constructorCheck);
_addInitialMemberRoles(_firstAB, memberAuthority);
constructorCheck = true;
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole(//solhint-disable-line
bytes32 _roleName,
string memory _roleDescription,
address _authorized
)
public
onlyAuthorizedToGovern {
_addRole(_roleName, _roleDescription, _authorized);
}
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole(//solhint-disable-line
address _memberAddress,
uint _roleId,
bool _active
)
public
checkRoleAuthority(_roleId) {
_updateRole(_memberAddress, _roleId, _active);
}
/**
* @dev to add members before launch
* @param userArray is list of addresses of members
* @param tokens is list of tokens minted for each array element
*/
function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner {
require(!launched);
for (uint i = 0; i < userArray.length; i++) {
require(!ms.isMember(userArray[i]));
tc.addToWhitelist(userArray[i]);
_updateRole(userArray[i], uint(Role.Member), true);
tc.mint(userArray[i], tokens[i]);
}
launched = true;
launchedOn = now;
}
/**
* @dev Called by user to pay joining membership fee
*/
function payJoiningFee(address _userAddress) public payable {
require(_userAddress != address(0));
require(!ms.isPause(), "Emergency Pause Applied");
if (msg.sender == address(ms.getLatestAddress("QT"))) {
require(td.walletAddress() != address(0), "No walletAddress present");
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(msg.value);
} else {
require(!qd.refundEligible(_userAddress));
require(!ms.isMember(_userAddress));
require(msg.value == td.joiningFee());
qd.setRefundEligible(_userAddress, true);
}
}
/**
* @dev to perform kyc verdict
* @param _userAddress whose kyc is being performed
* @param verdict of kyc process
*/
function kycVerdict(address payable _userAddress, bool verdict) public {
require(msg.sender == qd.kycAuthAddress());
require(!ms.isPause());
require(_userAddress != address(0));
require(!ms.isMember(_userAddress));
require(qd.refundEligible(_userAddress));
if (verdict) {
qd.setRefundEligible(_userAddress, false);
uint fee = td.joiningFee();
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(fee); // solhint-disable-line
} else {
qd.setRefundEligible(_userAddress, false);
_userAddress.transfer(td.joiningFee()); // solhint-disable-line
}
}
/**
* @dev withdraws membership for msg.sender if currently a member.
*/
function withdrawMembership() public {
require(!ms.isPause() && ms.isMember(msg.sender));
require(tc.totalLockedBalance(msg.sender) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(msg.sender);
tc.burnFrom(msg.sender, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
tc.removeFromWhitelist(msg.sender); // need clarification on whitelist
if (claimPayoutAddress[msg.sender] != address(0)) {
claimPayoutAddress[msg.sender] = address(0);
emit ClaimPayoutAddressSet(msg.sender, address(0));
}
}
/**
* @dev switches membership for msg.sender to the specified address.
* @param newAddress address of user to forward membership.
*/
function switchMembership(address newAddress) external {
_switchMembership(msg.sender, newAddress);
tk.transferFrom(msg.sender, newAddress, tk.balanceOf(msg.sender));
}
function switchMembershipOf(address member, address newAddress) external onlyInternal {
_switchMembership(member, newAddress);
}
/**
* @dev switches membership for member to the specified address.
* @param newAddress address of user to forward membership.
*/
function _switchMembership(address member, address newAddress) internal {
require(!ms.isPause() && ms.isMember(member) && !ms.isMember(newAddress));
require(tc.totalLockedBalance(member) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(member)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(member) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(member);
tc.addToWhitelist(newAddress);
_updateRole(newAddress, uint(Role.Member), true);
_updateRole(member, uint(Role.Member), false);
tc.removeFromWhitelist(member);
address payable previousPayoutAddress = claimPayoutAddress[member];
if (previousPayoutAddress != address(0)) {
address payable storedAddress = previousPayoutAddress == newAddress ? address(0) : previousPayoutAddress;
claimPayoutAddress[member] = address(0);
claimPayoutAddress[newAddress] = storedAddress;
// emit event for old address reset
emit ClaimPayoutAddressSet(member, address(0));
if (storedAddress != address(0)) {
// emit event for setting the payout address on the new member address if it's non zero
emit ClaimPayoutAddressSet(newAddress, storedAddress);
}
}
emit switchedMembership(member, newAddress, now);
}
function getClaimPayoutAddress(address payable _member) external view returns (address payable) {
address payable payoutAddress = claimPayoutAddress[_member];
return payoutAddress != address(0) ? payoutAddress : _member;
}
function setClaimPayoutAddress(address payable _address) external {
require(!ms.isPause(), "system is paused");
require(ms.isMember(msg.sender), "sender is not a member");
require(_address != msg.sender, "should be different than the member address");
claimPayoutAddress[msg.sender] = _address;
emit ClaimPayoutAddressSet(msg.sender, _address);
}
/// @dev Return number of member roles
function totalRoles() public view returns (uint256) {//solhint-disable-line
return memberRoleData.length;
}
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _newAuthorized New authorized address against role id
function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) {//solhint-disable-line
memberRoleData[_roleId].authorized = _newAuthorized;
}
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns (uint, address[] memory memberArray) {//solhint-disable-line
uint length = memberRoleData[_memberRoleId].memberAddress.length;
uint i;
uint j = 0;
memberArray = new address[](memberRoleData[_memberRoleId].memberCounter);
for (i = 0; i < length; i++) {
address member = memberRoleData[_memberRoleId].memberAddress[i];
if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) {//solhint-disable-line
memberArray[j] = member;
j++;
}
}
return (_memberRoleId, memberArray);
}
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberCounter Member length
function numberOfMembers(uint _memberRoleId) public view returns (uint) {//solhint-disable-line
return memberRoleData[_memberRoleId].memberCounter;
}
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns (address) {//solhint-disable-line
return memberRoleData[_memberRoleId].authorized;
}
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns (uint[] memory) {//solhint-disable-line
uint length = memberRoleData.length;
uint[] memory assignedRoles = new uint[](length);
uint counter = 0;
for (uint i = 1; i < length; i++) {
if (memberRoleData[i].memberActive[_memberAddress]) {
assignedRoles[counter] = i;
counter++;
}
}
return assignedRoles;
}
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns (bool) {//solhint-disable-line
if (_roleId == uint(Role.UnAssigned))
return true;
else
if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line
return true;
else
return false;
}
/// @dev Return total number of members assigned against each role id.
/// @return totalMembers Total members in particular role id
function getMemberLengthForAllRoles() public view returns (uint[] memory totalMembers) {//solhint-disable-line
totalMembers = new uint[](memberRoleData.length);
for (uint i = 0; i < memberRoleData.length; i++) {
totalMembers[i] = numberOfMembers(i);
}
}
/**
* @dev to update the member roles
* @param _memberAddress in concern
* @param _roleId the id of role
* @param _active if active is true, add the member, else remove it
*/
function _updateRole(address _memberAddress,
uint _roleId,
bool _active) internal {
// require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically");
if (_active) {
require(!memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1);
memberRoleData[_roleId].memberActive[_memberAddress] = true;
memberRoleData[_roleId].memberAddress.push(_memberAddress);
} else {
require(memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1);
delete memberRoleData[_roleId].memberActive[_memberAddress];
}
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function _addRole(
bytes32 _roleName,
string memory _roleDescription,
address _authorized
) internal {
emit MemberRole(memberRoleData.length, _roleName, _roleDescription);
memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized));
}
/**
* @dev to check if member is in the given member array
* @param _memberAddress in concern
* @param memberArray in concern
* @return boolean to represent the presence
*/
function _checkMemberInArray(
address _memberAddress,
address[] memory memberArray
)
internal
pure
returns (bool memberExists)
{
uint i;
for (i = 0; i < memberArray.length; i++) {
if (memberArray[i] == _memberAddress) {
memberExists = true;
break;
}
}
}
/**
* @dev to add initial member roles
* @param _firstAB is the member address to be added
* @param memberAuthority is the member authority(role) to be added for
*/
function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal {
maxABCount = 5;
_addRole("Unassigned", "Unassigned", address(0));
_addRole(
"Advisory Board",
"Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line
address(0)
);
_addRole(
"Member",
"Represents all users of Mutual.", //solhint-disable-line
memberAuthority
);
_addRole(
"Owner",
"Represents Owner of Mutual.", //solhint-disable-line
address(0)
);
// _updateRole(_firstAB, uint(Role.AdvisoryBoard), true);
_updateRole(_firstAB, uint(Role.Owner), true);
// _updateRole(_firstAB, uint(Role.Member), true);
launchedOn = 0;
}
function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) {
address memberAddress = memberRoleData[_memberRoleId].memberAddress[index];
return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]);
}
function membersLength(uint _memberRoleId) external view returns (uint) {
return memberRoleData[_memberRoleId].memberAddress.length;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../../abstract/Iupgradable.sol";
import "./MemberRoles.sol";
import "./external/Governed.sol";
import "./external/IProposalCategory.sol";
contract ProposalCategory is Governed, IProposalCategory, Iupgradable {
bool public constructorCheck;
MemberRoles internal mr;
struct CategoryStruct {
uint memberRoleToVote;
uint majorityVotePerc;
uint quorumPerc;
uint[] allowedToCreateProposal;
uint closingTime;
uint minStake;
}
struct CategoryAction {
uint defaultIncentive;
address contractAddress;
bytes2 contractName;
}
CategoryStruct[] internal allCategory;
mapping(uint => CategoryAction) internal categoryActionData;
mapping(uint => uint) public categoryABReq;
mapping(uint => uint) public isSpecialResolution;
mapping(uint => bytes) public categoryActionHashes;
bool public categoryActionHashUpdated;
/**
* @dev Adds new category (Discontinued, moved functionality to newCategory)
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
) external {}
/**
* @dev Initiates Default settings for Proposal Category contract (Adding default categories)
*/
function proposalCategoryInitiate() external {}
/**
* @dev Initiates Default action function hashes for existing categories
* To be called after the contract has been upgraded by governance
*/
function updateCategoryActionHashes() external onlyOwner {
require(!categoryActionHashUpdated, "Category action hashes already updated");
categoryActionHashUpdated = true;
categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)");
categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)");
categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)");
categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()");
categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)");
categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)");
categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)");
categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)");
categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)"); // solhint-disable-line
categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)");
categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)");
categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)");
categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)");
categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)");
categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)");
categoryActionHashes[29] = abi.encodeWithSignature("upgradeMultipleContracts(bytes2[],address[])");
categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)");
categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)");
categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)"); // solhint-disable-line
categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()");
}
/**
* @dev Gets Total number of categories added till now
*/
function totalCategories() external view returns (uint) {
return allCategory.length;
}
/**
* @dev Gets category details
*/
function category(uint _categoryId) external view returns (uint, uint, uint, uint, uint[] memory, uint, uint) {
return (
_categoryId,
allCategory[_categoryId].memberRoleToVote,
allCategory[_categoryId].majorityVotePerc,
allCategory[_categoryId].quorumPerc,
allCategory[_categoryId].allowedToCreateProposal,
allCategory[_categoryId].closingTime,
allCategory[_categoryId].minStake
);
}
/**
* @dev Gets category ab required and isSpecialResolution
* @return the category id
* @return if AB voting is required
* @return is category a special resolution
*/
function categoryExtendedData(uint _categoryId) external view returns (uint, uint, uint) {
return (
_categoryId,
categoryABReq[_categoryId],
isSpecialResolution[_categoryId]
);
}
/**
* @dev Gets the category acion details
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
*/
function categoryAction(uint _categoryId) external view returns (uint, address, bytes2, uint) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive
);
}
/**
* @dev Gets the category acion details of a category id
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
* @return action function hash
*/
function categoryActionDetails(uint _categoryId) external view returns (uint, address, bytes2, uint, bytes memory) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive,
categoryActionHashes[_categoryId]
);
}
/**
* @dev Updates dependant contract addresses
*/
function changeDependentContractAddress() public {
mr = MemberRoles(ms.getLatestAddress("MR"));
}
/**
* @dev Adds new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function newCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
_addCategory(
_name,
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_actionHash,
_contractAddress,
_contractName,
_incentives
);
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash);
}
}
/**
* @dev Changes the master address and update it's instance
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0))
require(masterAddress == msg.sender);
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev Updates category details (Discontinued, moved functionality to editCategory)
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
) public {}
/**
* @dev Updates category details
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function editCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
delete categoryActionHashes[_categoryId];
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash);
}
allCategory[_categoryId].memberRoleToVote = _memberRoleToVote;
allCategory[_categoryId].majorityVotePerc = _majorityVotePerc;
allCategory[_categoryId].closingTime = _closingTime;
allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal;
allCategory[_categoryId].minStake = _incentives[0];
allCategory[_categoryId].quorumPerc = _quorumPerc;
categoryActionData[_categoryId].defaultIncentive = _incentives[1];
categoryActionData[_categoryId].contractName = _contractName;
categoryActionData[_categoryId].contractAddress = _contractAddress;
categoryABReq[_categoryId] = _incentives[2];
isSpecialResolution[_categoryId] = _incentives[3];
emit Category(_categoryId, _name, _actionHash);
}
/**
* @dev Internal call to add new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function _addCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
internal
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
allCategory.push(
CategoryStruct(
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_incentives[0]
)
);
uint categoryId = allCategory.length - 1;
categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName);
categoryABReq[categoryId] = _incentives[2];
isSpecialResolution[categoryId] = _incentives[3];
emit Category(categoryId, _name, _actionHash);
}
/**
* @dev Internal call to check if given roles are valid or not
*/
function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal)
internal view returns (uint) {
uint totalRoles = mr.totalRoles();
if (_memberRoleToVote >= totalRoles) {
return 0;
}
for (uint i = 0; i < _allowedToCreateProposal.length; i++) {
if (_allowedToCreateProposal[i] >= totalRoles) {
return 0;
}
}
return 1;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IGovernance {
event Proposal(
address indexed proposalOwner,
uint256 indexed proposalId,
uint256 dateAdd,
string proposalTitle,
string proposalSD,
string proposalDescHash
);
event Solution(
uint256 indexed proposalId,
address indexed solutionOwner,
uint256 indexed solutionId,
string solutionDescHash,
uint256 dateAdd
);
event Vote(
address indexed from,
uint256 indexed proposalId,
uint256 indexed voteId,
uint256 dateAdd,
uint256 solutionChosen
);
event RewardClaimed(
address indexed member,
uint gbtReward
);
/// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal.
event VoteCast (uint256 proposalId);
/// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can
/// call any offchain actions
event ProposalAccepted (uint256 proposalId);
/// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time.
event CloseProposalOnTime (
uint256 indexed proposalId,
uint256 time
);
/// @dev ActionSuccess event is called whenever an onchain action is executed.
event ActionSuccess (
uint256 proposalId
);
/// @dev Creates a new proposal
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external;
/// @dev Edits the details of an existing proposal and creates new version
/// @param _proposalId Proposal id that details needs to be updated
/// @param _proposalDescHash Proposal description hash having long and short description of proposal.
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external;
/// @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentives
)
external;
/// @dev Submit proposal with solution
/// @param _proposalId Proposal id
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Creates a new proposal with solution and votes for the solution
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Casts vote
/// @param _proposalId Proposal id
/// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution
function submitVote(uint _proposalId, uint _solutionChosen) external;
function closeProposal(uint _proposalId) external;
function claimReward(address _memberAddress, uint _maxRecords) external returns (uint pendingDAppReward);
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalReward
);
function canCloseProposal(uint _proposalId) public view returns (uint closeValue);
function allowedToCatgorize() public view returns (uint roleId);
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
interface IMaster {
function getLatestAddress(bytes2 _module) external view returns (address);
}
contract Governed {
address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract
/// @dev modifier that allows only the authorized addresses to execute the function
modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
/// @dev checks if an address is authorized to govern
function isAuthorizedToGovern(address _toCheck) public view returns (bool) {
IMaster ms = IMaster(masterAddress);
return (ms.getLatestAddress("GV") == _toCheck);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IProposalCategory {
event Category(
uint indexed categoryId,
string categoryName,
string actionHash
);
/// @dev Adds new category
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
)
external;
/// @dev gets category details
function category(uint _categoryId)
external
view
returns (
uint categoryId,
uint memberRoleToVote,
uint majorityVotePerc,
uint quorumPerc,
uint[] memory allowedToCreateProposal,
uint closingTime,
uint minStake
);
///@dev gets category action details
function categoryAction(uint _categoryId)
external
view
returns (
uint categoryId,
address contractAddress,
bytes2 contractName,
uint defaultIncentive
);
/// @dev Gets Total number of categories added till now
function totalCategories() external view returns (uint numberOfCategories);
/// @dev Updates category details
/// @param _categoryId Category id that needs to be updated
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
public;
}
|
Internal call to close member voting _proposalId of proposal in concern category of proposal in concern/
|
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(,, majorityVote,,,,) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
| 2,578,443 |
/*
* Copyright 2020 DMM Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "../../../../node_modules/@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../node_modules/@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../protocol/interfaces/IDmmController.sol";
import "../../../utils/IERC20WithDecimals.sol";
import "../interfaces/IERC721TokenReceiver.sol";
import "../interfaces/IERC721.sol";
import "./IAssetIntroducerStakingV1Initializable.sol";
import "./IAssetIntroducerV1.sol";
import "./IAssetIntroducerStakingV1.sol";
import "../AssetIntroducerStakingData.sol";
contract AssetIntroducerStakingV1 is IAssetIntroducerStakingV1Initializable, IAssetIntroducerStakingV1, IERC721TokenReceiver, AssetIntroducerStakingData {
using SafeERC20 for IERC20;
using SafeMath for uint;
uint constant internal ONE_ETH = 1 ether;
function initialize(
address __owner,
address __guardian,
address __assetIntroducerProxy,
address __dmgIncentivesPool
) public initializer {
IOwnableOrGuardian.initialize(__owner, __guardian);
_assetIntroducerProxy = __assetIntroducerProxy;
_dmgIncentivesPool = __dmgIncentivesPool;
_guardCounter = 1;
}
function initializeOwnables(
address __owner,
address __guardian
) external {
require(
!_isOwnableInitialized,
"AssetIntroducerStakingV1::initializeOwnables: ALREADY_INITIALIZED"
);
_isOwnableInitialized = true;
_transferOwnership(__owner);
_transferGuardian(__guardian);
}
function assetIntroducerProxy() external view returns (address) {
return _assetIntroducerProxy;
}
function dmg() public view returns (address) {
return IAssetIntroducerV1(_assetIntroducerProxy).dmg();
}
function dmgIncentivesPool() external view returns (address) {
return _dmgIncentivesPool;
}
function buyAssetIntroducerSlot(
uint __tokenId,
uint __dmmTokenId,
StakingDuration __duration
)
external
nonReentrant
returns (bool) {
IAssetIntroducerV1 __assetIntroducerProxy = IAssetIntroducerV1(_assetIntroducerProxy);
(uint fullPriceDmg, uint additionalDiscount) = getAssetIntroducerPriceDmgByTokenIdAndStakingDuration(__tokenId, __duration);
uint userPriceDmg = fullPriceDmg / 2;
address __dmg = dmg();
address __dmgIncentivesPool = _dmgIncentivesPool;
require(
IERC20(__dmg).balanceOf(__dmgIncentivesPool) >= fullPriceDmg.sub(userPriceDmg),
"AssetIntroducerBuyerRouter::buyAssetIntroducerSlot: INSUFFICIENT_INCENTIVES"
);
IERC20(__dmg).safeTransferFrom(__dmgIncentivesPool, address(this), fullPriceDmg.sub(userPriceDmg));
IERC20(__dmg).safeTransferFrom(msg.sender, address(this), userPriceDmg);
_performStakingForToken(__tokenId, __dmmTokenId, __duration, __assetIntroducerProxy);
IERC20(__dmg).safeApprove(address(__assetIntroducerProxy), fullPriceDmg);
__assetIntroducerProxy.buyAssetIntroducerSlotViaStaking(__tokenId, additionalDiscount);
// Forward the NFT to the purchaser
IERC721(address(__assetIntroducerProxy)).safeTransferFrom(address(this), msg.sender, __tokenId);
emit IncentiveDmgUsed(__tokenId, msg.sender, fullPriceDmg.sub(userPriceDmg));
return true;
}
function withdrawStake() external nonReentrant {
UserStake[] memory userStakes = _userToStakesMap[msg.sender];
for (uint i = 0; i < userStakes.length; i++) {
if (!userStakes[i].isWithdrawn && block.timestamp > userStakes[i].unlockTimestamp) {
_userToStakesMap[msg.sender][i].isWithdrawn = true;
IERC20(userStakes[i].mToken).safeTransfer(msg.sender, userStakes[i].amount);
emit UserEndStaking(msg.sender, userStakes[i].tokenId, userStakes[i].mToken, userStakes[i].amount);
}
}
}
function getUserStakesByAddress(
address user
) external view returns (AssetIntroducerStakingData.UserStake[] memory) {
return _userToStakesMap[user];
}
function getActiveUserStakesByAddress(
address user
) external view returns (AssetIntroducerStakingData.UserStake[] memory) {
AssetIntroducerStakingData.UserStake[] memory allStakes = _userToStakesMap[user];
uint count = 0;
for (uint i = 0; i < allStakes.length; i++) {
if (!allStakes[i].isWithdrawn) {
count += 1;
}
}
AssetIntroducerStakingData.UserStake[] memory activeStakes = new AssetIntroducerStakingData.UserStake[](count);
count = 0;
for (uint i = 0; i < allStakes.length; i++) {
if (!allStakes[i].isWithdrawn) {
activeStakes[count++] = allStakes[i];
}
}
return activeStakes;
}
function balanceOf(
address user,
address mToken
) external view returns (uint) {
uint balance = 0;
AssetIntroducerStakingData.UserStake[] memory allStakes = _userToStakesMap[user];
for (uint i = 0; i < allStakes.length; i++) {
if (!allStakes[i].isWithdrawn && allStakes[i].mToken == mToken) {
balance += allStakes[i].amount;
}
}
return balance;
}
function getStakeAmountByTokenIdAndDmmTokenId(
uint __tokenId,
uint __dmmTokenId
) public view returns (uint) {
uint priceUsd = IAssetIntroducerV1(_assetIntroducerProxy).getAssetIntroducerPriceUsdByTokenId(__tokenId);
return _getStakeAmountByDmmTokenId(__dmmTokenId, priceUsd);
}
function getStakeAmountByCountryCodeAndIntroducerTypeAndDmmTokenId(
string calldata __countryCode,
AssetIntroducerData.AssetIntroducerType __introducerType,
uint __dmmTokenId
) external view returns (uint) {
uint priceUsd = IAssetIntroducerV1(_assetIntroducerProxy).getAssetIntroducerPriceUsdByCountryCodeAndIntroducerType(__countryCode, __introducerType);
return _getStakeAmountByDmmTokenId(__dmmTokenId, priceUsd);
}
function mapDurationEnumToSeconds(
StakingDuration __duration
) public pure returns (uint64) {
if (__duration == StakingDuration.TWELVE_MONTHS) {
return 86400 * 30 * 12;
} else if (__duration == StakingDuration.EIGHTEEN_MONTHS) {
return 86400 * 30 * 18;
} else {
revert("AssetIntroducerStakingV1::mapDurationEnumToSeconds: INVALID_DURATION");
}
}
function onERC721Received(
address,
address,
uint256,
bytes memory
) public returns (bytes4) {
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
function isReady() public view returns (bool) {
return IERC20(dmg()).allowance(_dmgIncentivesPool, address(this)) > 0 &&
IAssetIntroducerV1(_assetIntroducerProxy).stakingPurchaser() == address(this);
}
function getAssetIntroducerPriceDmgByTokenIdAndStakingDuration(
uint __tokenId,
StakingDuration __duration
) public view returns (uint, uint) {
IAssetIntroducerV1 __assetIntroducerProxy = IAssetIntroducerV1(_assetIntroducerProxy);
uint nonStakingDiscount = __assetIntroducerProxy.getAssetIntroducerDiscount();
uint totalDiscount = getTotalDiscountByStakingDuration(__duration);
uint additionalDiscount = totalDiscount.sub(nonStakingDiscount);
uint fullPriceDmg = __assetIntroducerProxy.getAssetIntroducerPriceDmgByTokenId(__tokenId);
uint originalPriceDmg = fullPriceDmg.mul(ONE_ETH).div(ONE_ETH.sub(nonStakingDiscount));
return (originalPriceDmg.mul(ONE_ETH.sub(totalDiscount)).div(ONE_ETH), additionalDiscount);
}
function getTotalDiscountByStakingDuration(
StakingDuration duration
) public view returns (uint) {
uint baseDiscount;
uint originalDiscount;
// The discount expired
if (duration == StakingDuration.TWELVE_MONTHS) {
// Discount is 95% at t=0 and decays to 25% at t=18_months; delta of 70%
originalDiscount = 0.7 ether;
baseDiscount = 0.25 ether;
} else if (duration == StakingDuration.EIGHTEEN_MONTHS) {
// Discount is 99% at t=0 and decays to 50% at t=18_months; delta of 49%
originalDiscount = 0.49 ether;
baseDiscount = 0.50 ether;
} else {
revert("AssetIntroducerStakingV1::getTotalDiscountByStakingDuration: INVALID_DURATION");
}
uint elapsedTime = block.timestamp.sub(IAssetIntroducerV1(_assetIntroducerProxy).initTimestamp());
// 18 months or 540 days
uint discountDurationInSeconds = 86400 * 30 * 18;
if (elapsedTime > discountDurationInSeconds) {
return baseDiscount;
} else {
return (originalDiscount.mul(discountDurationInSeconds.sub(elapsedTime)).div(discountDurationInSeconds)).add(baseDiscount);
}
}
// *************************
// ***** Internal Functions
// *************************
function _performStakingForToken(
uint __tokenId,
uint __dmmTokenId,
StakingDuration __duration,
IAssetIntroducerV1 __assetIntroducerProxy
) internal {
uint stakeAmount = getStakeAmountByTokenIdAndDmmTokenId(__tokenId, __dmmTokenId);
address mToken = IDmmController(__assetIntroducerProxy.dmmController()).getDmmTokenAddressByDmmTokenId(__dmmTokenId);
IERC20(mToken).safeTransferFrom(msg.sender, address(this), stakeAmount);
uint64 unlockTimestamp = uint64(block.timestamp) + mapDurationEnumToSeconds(__duration);
_userToStakesMap[msg.sender].push(UserStake({
isWithdrawn : false,
unlockTimestamp : unlockTimestamp,
mToken : mToken,
amount : stakeAmount,
tokenId : __tokenId
}));
emit UserBeginStaking(msg.sender, __tokenId, mToken, stakeAmount, unlockTimestamp);
}
function _getStakeAmountByDmmTokenId(
uint __dmmTokenId,
uint __priceUsd
) internal view returns (uint) {
IDmmController controller = IDmmController(IAssetIntroducerV1(_assetIntroducerProxy).dmmController());
address dmmToken = controller.getDmmTokenAddressByDmmTokenId(__dmmTokenId);
address underlyingToken = controller.getUnderlyingTokenForDmm(dmmToken);
uint usdPricePerToken = controller.underlyingTokenValuator().getTokenValue(underlyingToken, ONE_ETH);
uint numberOfDmmTokensStandardized = __priceUsd.mul(ONE_ETH).div(usdPricePerToken).mul(ONE_ETH).div(controller.getExchangeRate(dmmToken));
uint8 decimals = IERC20WithDecimals(dmmToken).decimals();
if (decimals > 18) {
return numberOfDmmTokensStandardized.mul(10 ** uint(decimals - 18));
} else if (decimals < 18) {
return numberOfDmmTokensStandardized.div(10 ** uint(18 - decimals));
} else {
return numberOfDmmTokensStandardized;
}
}
}
|
Forward the NFT to the purchaser
|
function buyAssetIntroducerSlot(
uint __tokenId,
uint __dmmTokenId,
StakingDuration __duration
)
external
nonReentrant
returns (bool) {
IAssetIntroducerV1 __assetIntroducerProxy = IAssetIntroducerV1(_assetIntroducerProxy);
(uint fullPriceDmg, uint additionalDiscount) = getAssetIntroducerPriceDmgByTokenIdAndStakingDuration(__tokenId, __duration);
uint userPriceDmg = fullPriceDmg / 2;
address __dmg = dmg();
address __dmgIncentivesPool = _dmgIncentivesPool;
require(
IERC20(__dmg).balanceOf(__dmgIncentivesPool) >= fullPriceDmg.sub(userPriceDmg),
"AssetIntroducerBuyerRouter::buyAssetIntroducerSlot: INSUFFICIENT_INCENTIVES"
);
IERC20(__dmg).safeTransferFrom(__dmgIncentivesPool, address(this), fullPriceDmg.sub(userPriceDmg));
IERC20(__dmg).safeTransferFrom(msg.sender, address(this), userPriceDmg);
_performStakingForToken(__tokenId, __dmmTokenId, __duration, __assetIntroducerProxy);
IERC20(__dmg).safeApprove(address(__assetIntroducerProxy), fullPriceDmg);
__assetIntroducerProxy.buyAssetIntroducerSlotViaStaking(__tokenId, additionalDiscount);
IERC721(address(__assetIntroducerProxy)).safeTransferFrom(address(this), msg.sender, __tokenId);
emit IncentiveDmgUsed(__tokenId, msg.sender, fullPriceDmg.sub(userPriceDmg));
return true;
}
| 908,087 |
pragma solidity ^0.4.25;
/*
* CryptoMiningWar - Build your own empire on Blockchain
* Author: InspiGames
* Website: https://cryptominingwar.github.io/
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract CryptoEngineerInterface {
uint256 public prizePool = 0;
address public gameSponsor;
function getPlayerData(address /*_addr*/)
public
pure
returns(
uint256 /*_engineerRoundNumber*/,
uint256 /*_virusNumber*/,
uint256 /*_virusDefence*/,
uint256 /*_research*/,
uint256 /*_researchPerDay*/,
uint256 /*_lastUpdateTime*/,
uint256[8] /*_engineersCount*/,
uint256 /*_nextTimeAtk*/,
uint256 /*_endTimeUnequalledDef*/
) {}
function fallback() public payable {}
function claimPrizePool(address /*_addr*/, uint256 /*_value*/) public pure {}
function isContractMiniGame() public pure returns( bool /*_isContractMiniGame*/) {}
}
contract CryptoMiningWarInterface {
uint256 public deadline;
mapping(address => PlayerData) public players;
struct PlayerData {
uint256 roundNumber;
mapping(uint256 => uint256) minerCount;
uint256 hashrate;
uint256 crystals;
uint256 lastUpdateTime;
uint256 referral_count;
uint256 noQuest;
}
function getPlayerData(address /*addr*/) public pure
returns (
uint256 /*crystals*/,
uint256 /*lastupdate*/,
uint256 /*hashratePerDay*/,
uint256[8] /*miners*/,
uint256 /*hasBoost*/,
uint256 /*referral_count*/,
uint256 /*playerBalance*/,
uint256 /*noQuest*/
) {}
function subCrystal( address /*_addr*/, uint256 /*_value*/ ) public pure {}
}
contract CryptoAirdropGameInterface {
mapping(address => PlayerData) public players;
struct PlayerData {
uint256 currentMiniGameId;
uint256 lastMiniGameId;
uint256 win;
uint256 share;
uint256 totalJoin;
uint256 miningWarRoundNumber;
}
function isContractMiniGame() public pure returns( bool /*_isContractMiniGame*/ ) {}
}
contract CryptoBossWannaCryInterface {
mapping(address => PlayerData) public players;
struct PlayerData {
uint256 currentBossRoundNumber;
uint256 lastBossRoundNumber;
uint256 win;
uint256 share;
uint256 dame;
uint256 nextTimeAtk;
}
function isContractMiniGame() public pure returns( bool /*_isContractMiniGame*/ ) {}
}
contract CrystalDeposit {
using SafeMath for uint256;
bool private init = false;
address private administrator;
// mini game
uint256 private round = 0;
uint256 private HALF_TIME = 1 days;
uint256 private RESET_QUEST_TIME= 4 hours;
uint256 constant private RESET_QUEST_FEE = 0.005 ether;
address private engineerAddress;
CryptoEngineerInterface public Engineer;
CryptoMiningWarInterface public MiningWar;
CryptoAirdropGameInterface public AirdropGame;
CryptoBossWannaCryInterface public BossWannaCry;
// mining war info
uint256 private miningWarDeadline;
uint256 constant private CRTSTAL_MINING_PERIOD = 86400;
/**
* @dev mini game information
*/
mapping(uint256 => Game) public games;
// quest info
mapping(uint256 => Quest) public quests;
mapping(address => PlayerQuest) public playersQuests;
/**
* @dev player information
*/
mapping(address => Player) public players;
struct Game {
uint256 round;
uint256 crystals;
uint256 prizePool;
uint256 endTime;
bool ended;
}
struct Player {
uint256 currentRound;
uint256 lastRound;
uint256 reward;
uint256 share; // your crystals share in current round
uint256 questSequence;
uint256 totalQuestFinish;
uint256 resetFreeTime;
}
struct Quest {
uint256 typeQuest;
uint256 levelOne;
uint256 levelTwo;
uint256 levelThree;
uint256 levelFour;
}
struct PlayerQuest {
bool haveQuest;
uint256 questId;
uint256 level;
uint256 numberOfTimes;
uint256 deposit;
uint256 miningWarRound; // current mining war round player join
uint256 referralCount; // current referral_count
uint256 totalMiner; // current total miner
uint256 totalEngineer; // current total engineer
uint256 airdropGameId; // current airdrop game id
uint256 totalJoinAirdrop; // total join the airdrop game
uint256 nextTimeAtkPlayer; //
uint256 dameBossWannaCry; // current dame boss
uint256 levelBossWannaCry; // current boss player atk
}
event EndRound(uint256 round, uint256 crystals, uint256 prizePool, uint256 endTime);
event AddPlayerQuest(address player, uint256 questId, uint256 questLv, uint256 deposit);
event ConfirmQuest(address player, uint256 questId, uint256 questLv, uint256 deposit, uint256 bonus, uint256 percent);
modifier isAdministrator()
{
require(msg.sender == administrator);
_;
}
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
constructor() public {
administrator = msg.sender;
initQuests();
engineerAddress = address(0x69fd0e5d0a93bf8bac02c154d343a8e3709adabf);
setMiningWarInterface(0xf84c61bb982041c030b8580d1634f00fffb89059);
setEngineerInterface(engineerAddress);
setAirdropGameInterface(0x5b813a2f4b58183d270975ab60700740af00a3c9);
setBossWannaCryInterface(0x54e96d609b183196de657fc7380032a96f27f384);
}
function initQuests() private
{
// type level 1 level 2 level 3 level 4
quests[0] = Quest(1 , 5 , 10 , 15 , 20 ); // Win x Starter Quest
quests[1] = Quest(2 , 1 , 2 , 3 , 4 ); // Buy x Miner
quests[2] = Quest(3 , 1 , 2 , 3 , 4 ); // Buy x Engineer
quests[3] = Quest(4 , 1 , 1 , 1 , 1 ); // Join An Airdrop Game
quests[4] = Quest(5 , 1 , 1 , 1 , 1 ); // Attack x Player
quests[5] = Quest(6 , 100 , 1000 , 10000 ,100000); // Attack x Hp Boss WannaCry
}
function () public payable
{
if (engineerAddress != msg.sender) addCurrentPrizePool(msg.value);
}
// ---------------------------------------------------------------------------------------
// SET INTERFACE CONTRACT
// ---------------------------------------------------------------------------------------
function setMiningWarInterface(address _addr) public isAdministrator
{
MiningWar = CryptoMiningWarInterface(_addr);
}
function setEngineerInterface(address _addr) public isAdministrator
{
CryptoEngineerInterface engineerInterface = CryptoEngineerInterface(_addr);
require(engineerInterface.isContractMiniGame() == true);
engineerAddress = _addr;
Engineer = engineerInterface;
}
function setAirdropGameInterface(address _addr) public isAdministrator
{
CryptoAirdropGameInterface airdropGameInterface = CryptoAirdropGameInterface(_addr);
require(airdropGameInterface.isContractMiniGame() == true);
AirdropGame = airdropGameInterface;
}
function setBossWannaCryInterface(address _addr) public isAdministrator
{
CryptoBossWannaCryInterface bossWannaCryInterface = CryptoBossWannaCryInterface(_addr);
require(bossWannaCryInterface.isContractMiniGame() == true);
BossWannaCry = bossWannaCryInterface;
}
/**
* @dev MainContract used this function to verify game's contract
*/
function isContractMiniGame() public pure returns( bool _isContractMiniGame )
{
_isContractMiniGame = true;
}
function upgrade(address addr) public isAdministrator
{
selfdestruct(addr);
}
// ---------------------------------------------------------------------------------------------
// SETUP GAME
// ---------------------------------------------------------------------------------------------
function setHalfTime(uint256 _time) public isAdministrator
{
HALF_TIME = _time;
}
function setResetQuestTime(uint256 _time) public isAdministrator
{
RESET_QUEST_TIME = _time;
}
/**
* @dev Main Contract call this function to setup mini game.
*/
function setupMiniGame( uint256 /*_miningWarRoundNumber*/, uint256 _miningWarDeadline ) public
{
miningWarDeadline = _miningWarDeadline;
}
/**
* @dev start the mini game
*/
function startGame() public
{
require(msg.sender == administrator);
require(init == false);
init = true;
miningWarDeadline = getMiningWarDealine();
games[round].ended = true;
startRound();
}
function startRound() private
{
require(games[round].ended == true);
uint256 crystalsLastRound = games[round].crystals;
uint256 prizePoolLastRound= games[round].prizePool;
round = round + 1;
uint256 endTime = now + HALF_TIME;
// claim 5% of current prizePool as rewards.
uint256 engineerPrizePool = getEngineerPrizePool();
uint256 prizePool = SafeMath.div(SafeMath.mul(engineerPrizePool, 5),100);
Engineer.claimPrizePool(address(this), prizePool);
if (crystalsLastRound <= 0) prizePool = SafeMath.add(prizePool, prizePoolLastRound);
games[round] = Game(round, 0, prizePool, endTime, false);
}
function endRound() private
{
require(games[round].ended == false);
require(games[round].endTime <= now);
Game storage g = games[round];
g.ended = true;
startRound();
emit EndRound(g.round, g.crystals, g.prizePool, g.endTime);
}
/**
* @dev player send crystals to the pot
*/
function share(uint256 _value) public disableContract
{
require(miningWarDeadline > now);
require(games[round].ended == false);
require(_value >= 10000);
require(playersQuests[msg.sender].haveQuest == false);
MiningWar.subCrystal(msg.sender, _value);
if (games[round].endTime <= now) endRound();
updateReward(msg.sender);
uint256 _share = SafeMath.mul(_value, CRTSTAL_MINING_PERIOD);
addPlayerQuest(msg.sender, _share);
}
function freeResetQuest(address _addr) public disableContract
{
_addr = msg.sender;
resetQuest(_addr);
}
function instantResetQuest(address _addr) public payable disableContract
{
require(msg.value >= RESET_QUEST_FEE);
_addr = msg.sender;
uint256 fee = devFee(msg.value);
address gameSponsor = getGameSponsor();
gameSponsor.transfer(fee);
administrator.transfer(fee);
uint256 prizePool = msg.value - (fee * 2);
addEngineerPrizePool(prizePool);
resetQuest(_addr);
}
function confirmQuest(address _addr) public disableContract
{
_addr = msg.sender;
bool _isFinish;
(_isFinish, ,) = checkQuest(_addr);
require(_isFinish == true);
require(playersQuests[_addr].haveQuest == true);
if (games[round].endTime <= now) endRound();
updateReward(_addr);
Player storage p = players[_addr];
Game storage g = games[round];
PlayerQuest storage pQ = playersQuests[_addr];
uint256 _share = pQ.deposit;
uint256 rate = 0;
// bonus
// lv 4 50 - 100 %
if (pQ.questId == 2) rate = 50 + randomNumber(_addr, 0, 51);
if (pQ.questId == 0 && pQ.level == 4) rate = 50 + randomNumber(_addr, 0, 51);
if (pQ.questId == 1 && pQ.level == 4) rate = 50 + randomNumber(_addr, 0, 51);
if (pQ.questId == 5 && pQ.level == 4) rate = 50 + randomNumber(_addr, 0, 51);
// lv 3 25 - 75 %
if (pQ.questId == 0 && pQ.level == 3) rate = 25 + randomNumber(_addr, 0, 51);
if (pQ.questId == 1 && pQ.level == 3) rate = 25 + randomNumber(_addr, 0, 51);
if (pQ.questId == 5 && pQ.level == 3) rate = 25 + randomNumber(_addr, 0, 51);
// lv 2 10 - 50 %
if (pQ.questId == 0 && pQ.level == 2) rate = 10 + randomNumber(_addr, 0, 41);
if (pQ.questId == 1 && pQ.level == 2) rate = 10 + randomNumber(_addr, 0, 41);
if (pQ.questId == 5 && pQ.level == 2) rate = 10 + randomNumber(_addr, 0, 41);
if (pQ.questId == 3) rate = 10 + randomNumber(_addr, 0, 51);
// lv 1 0 - 25 %
if (pQ.questId == 0 && pQ.level == 1) rate = randomNumber(_addr, 0, 26);
if (pQ.questId == 1 && pQ.level == 1) rate = randomNumber(_addr, 0, 26);
if (pQ.questId == 5 && pQ.level == 1) rate = randomNumber(_addr, 0, 26);
if (pQ.questId == 4) rate = randomNumber(_addr, 0, 26);
if (rate > 0) _share += SafeMath.div(SafeMath.mul(_share, rate), 100);
g.crystals = SafeMath.add(g.crystals, _share);
if (p.currentRound == round) {
p.share = SafeMath.add(p.share, _share);
} else {
p.share = _share;
p.currentRound = round;
}
p.questSequence += 1;
p.totalQuestFinish += 1;
pQ.haveQuest = false;
emit ConfirmQuest(_addr, pQ.questId, pQ.level, pQ.deposit, SafeMath.sub(_share, pQ.deposit), rate);
pQ.deposit = 0;
}
function checkQuest(address _addr) public view returns(bool _isFinish, uint256 _numberOfTimes, uint256 _number)
{
PlayerQuest memory pQ = playersQuests[_addr];
if (pQ.questId == 0) (_isFinish, _numberOfTimes, _number ) = checkWonStarterQuest(_addr);
if (pQ.questId == 1) (_isFinish, _numberOfTimes, _number ) = checkBuyMinerQuest(_addr);
if (pQ.questId == 2) (_isFinish, _numberOfTimes, _number ) = checkBuyEngineerQuest(_addr);
if (pQ.questId == 3) (_isFinish, _numberOfTimes, _number ) = checkJoinAirdropQuest(_addr);
if (pQ.questId == 4) (_isFinish, _numberOfTimes, _number ) = checkAtkPlayerQuest(_addr);
if (pQ.questId == 5) (_isFinish, _numberOfTimes, _number ) = ckeckAtkBossWannaCryQuest(_addr);
}
function getData(address _addr)
public
view
returns(
// current game
uint256 _prizePool,
uint256 _crystals,
uint256 _endTime,
// player info
uint256 _reward,
uint256 _share,
uint256 _questSequence,
// current quest of player
uint256 _deposit,
uint256 _resetFreeTime,
uint256 _typeQuest,
uint256 _numberOfTimes,
uint256 _number,
bool _isFinish,
bool _haveQuest
) {
(_prizePool, _crystals, _endTime) = getCurrentGame();
(_reward, _share, _questSequence, , _resetFreeTime) = getPlayerData(_addr);
(_haveQuest, _typeQuest, _isFinish, _numberOfTimes, _number, _deposit) = getCurrentQuest(_addr);
}
function withdrawReward() public disableContract
{
if (games[round].endTime <= now) endRound();
updateReward(msg.sender);
Player storage p = players[msg.sender];
uint256 balance = p.reward;
if (address(this).balance >= balance) {
msg.sender.transfer(balance);
// update player
p.reward = 0;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
// INTERNAL
// ---------------------------------------------------------------------------------------------------------------------------------
function addCurrentPrizePool(uint256 _value) private
{
require(games[round].ended == false);
require(init == true);
games[round].prizePool += _value;
}
function devFee(uint256 _amount) private pure returns(uint256)
{
return SafeMath.div(SafeMath.mul(_amount, 5), 100);
}
function resetQuest(address _addr) private
{
if (games[round].endTime <= now) endRound();
updateReward(_addr);
uint256 currentQuestId= playersQuests[_addr].questId;
uint256 questId = randomNumber(_addr, 0, 6);
if (currentQuestId == questId && questId < 5) questId += 1;
if (currentQuestId == questId && questId >= 5) questId -= 1;
uint256 level = 1 + randomNumber(_addr, questId + 1, 4);
uint256 numberOfTimes = getNumberOfTimesQuest(questId, level);
if (questId == 0) addWonStarterQuest(_addr); // won x starter quest
if (questId == 1) addBuyMinerQuest(_addr); // buy x miner
if (questId == 2) addBuyEngineerQuest(_addr); // buy x engineer
if (questId == 3) addJoinAirdropQuest(_addr); // join airdrop game
if (questId == 4) addAtkPlayerQuest(_addr); // atk a player
if (questId == 5) addAtkBossWannaCryQuest(_addr); // atk hp boss
PlayerQuest storage pQ = playersQuests[_addr];
players[_addr].questSequence = 0;
players[_addr].resetFreeTime = now + RESET_QUEST_TIME;
pQ.questId = questId;
pQ.level = level;
pQ.numberOfTimes = numberOfTimes;
emit AddPlayerQuest(_addr, questId, level, pQ.deposit);
}
function getCurrentGame() private view returns(uint256 _prizePool, uint256 _crystals, uint256 _endTime)
{
Game memory g = games[round];
_prizePool = g.prizePool;
_crystals = g.crystals;
_endTime = g.endTime;
}
function getCurrentQuest(address _addr) private view returns(bool _haveQuest, uint256 _typeQuest, bool _isFinish, uint256 _numberOfTimes, uint256 _number, uint256 _deposit)
{
PlayerQuest memory pQ = playersQuests[_addr];
_haveQuest = pQ.haveQuest;
_deposit = pQ.deposit;
_typeQuest = quests[pQ.questId].typeQuest;
(_isFinish, _numberOfTimes, _number) = checkQuest(_addr);
}
function getPlayerData(address _addr) private view returns(uint256 _reward, uint256 _share, uint256 _questSequence, uint256 _totalQuestFinish, uint256 _resetFreeTime)
{
Player memory p = players[_addr];
_reward = p.reward;
_questSequence = p.questSequence;
_totalQuestFinish = p.totalQuestFinish;
_resetFreeTime = p.resetFreeTime;
if (p.currentRound == round) _share = players[_addr].share;
if (p.currentRound != p.lastRound) _reward += calculateReward(_addr, p.currentRound);
}
function updateReward(address _addr) private
{
Player storage p = players[_addr];
if (
games[p.currentRound].ended == true &&
p.lastRound < p.currentRound
) {
p.reward = SafeMath.add(p.reward, calculateReward(msg.sender, p.currentRound));
p.lastRound = p.currentRound;
}
}
/**
* @dev calculate reward
*/
function randomNumber(address _addr, uint256 randNonce, uint256 _maxNumber) private view returns(uint256)
{
return uint256(keccak256(abi.encodePacked(now, _addr, randNonce))) % _maxNumber;
}
function calculateReward(address _addr, uint256 _round) private view returns(uint256)
{
Player memory p = players[_addr];
Game memory g = games[_round];
if (g.endTime > now) return 0;
if (g.crystals == 0) return 0;
return SafeMath.div(SafeMath.mul(g.prizePool, p.share), g.crystals);
}
// --------------------------------------------------------------------------------------------------------------
// ADD QUEST INTERNAL
// --------------------------------------------------------------------------------------------------------------
function addPlayerQuest(address _addr, uint256 _share) private
{
uint256 questId = randomNumber(_addr, 0, 6);
uint256 level = 1 + randomNumber(_addr, questId + 1, 4);
uint256 numberOfTimes = getNumberOfTimesQuest(questId, level);
if (questId == 0) addWonStarterQuest(_addr); // won x starter quest
if (questId == 1) addBuyMinerQuest(_addr); // buy x miner
if (questId == 2) addBuyEngineerQuest(_addr); // buy x engineer
if (questId == 3) addJoinAirdropQuest(_addr); // join airdrop game
if (questId == 4) addAtkPlayerQuest(_addr); // atk a player
if (questId == 5) addAtkBossWannaCryQuest(_addr); // atk hp boss
PlayerQuest storage pQ = playersQuests[_addr];
pQ.deposit = _share;
pQ.haveQuest = true;
pQ.questId = questId;
pQ.level = level;
pQ.numberOfTimes = numberOfTimes;
players[_addr].resetFreeTime = now + RESET_QUEST_TIME;
emit AddPlayerQuest(_addr, questId, level, _share);
}
function getNumberOfTimesQuest(uint256 _questId, uint256 _level) private view returns(uint256)
{
Quest memory q = quests[_questId];
if (_level == 1) return q.levelOne;
if (_level == 2) return q.levelTwo;
if (_level == 3) return q.levelThree;
if (_level == 4) return q.levelFour;
return 0;
}
function addWonStarterQuest(address _addr) private
{
uint256 miningWarRound;
uint256 referralCount;
(miningWarRound, referralCount) = getPlayerMiningWarData(_addr);
playersQuests[_addr].miningWarRound = miningWarRound;
playersQuests[_addr].referralCount = referralCount;
}
function addBuyMinerQuest(address _addr) private
{
uint256 miningWarRound;
(miningWarRound, ) = getPlayerMiningWarData(_addr);
playersQuests[_addr].totalMiner = getTotalMiner(_addr);
playersQuests[_addr].miningWarRound = miningWarRound;
}
function addBuyEngineerQuest(address _addr) private
{
playersQuests[_addr].totalEngineer = getTotalEngineer(_addr);
}
function addJoinAirdropQuest(address _addr) private
{
uint256 airdropGameId; // current airdrop game id
uint256 totalJoinAirdrop;
(airdropGameId , totalJoinAirdrop) = getPlayerAirdropGameData(_addr);
playersQuests[_addr].airdropGameId = airdropGameId;
playersQuests[_addr].totalJoinAirdrop = totalJoinAirdrop;
}
function addAtkPlayerQuest(address _addr) private
{
playersQuests[_addr].nextTimeAtkPlayer = getNextTimeAtkPlayer(_addr);
}
function addAtkBossWannaCryQuest(address _addr) private
{
uint256 dameBossWannaCry; // current dame boss
uint256 levelBossWannaCry;
(levelBossWannaCry, dameBossWannaCry) = getPlayerBossWannaCryData(_addr);
playersQuests[_addr].levelBossWannaCry = levelBossWannaCry;
playersQuests[_addr].dameBossWannaCry = dameBossWannaCry;
}
// --------------------------------------------------------------------------------------------------------------
// CHECK QUEST INTERNAL
// --------------------------------------------------------------------------------------------------------------
function checkWonStarterQuest(address _addr) private view returns(bool _isFinish, uint256 _numberOfTimes, uint256 _number)
{
PlayerQuest memory pQ = playersQuests[_addr];
uint256 miningWarRound;
uint256 referralCount;
(miningWarRound, referralCount) = getPlayerMiningWarData(_addr);
_numberOfTimes = pQ.numberOfTimes;
if (pQ.miningWarRound != miningWarRound) _number = referralCount;
if (pQ.miningWarRound == miningWarRound) _number = SafeMath.sub(referralCount, pQ.referralCount);
if (
(pQ.miningWarRound != miningWarRound && referralCount >= pQ.numberOfTimes) ||
(pQ.miningWarRound == miningWarRound && referralCount >= SafeMath.add(pQ.referralCount, pQ.numberOfTimes))
) {
_isFinish = true;
}
}
function checkBuyMinerQuest(address _addr) private view returns(bool _isFinish, uint256 _numberOfTimes, uint256 _number)
{
PlayerQuest memory pQ = playersQuests[_addr];
uint256 miningWarRound;
(miningWarRound, ) = getPlayerMiningWarData(_addr);
uint256 totalMiner = getTotalMiner(_addr);
_numberOfTimes = pQ.numberOfTimes;
if (pQ.miningWarRound != miningWarRound) _number = totalMiner;
if (pQ.miningWarRound == miningWarRound) _number = SafeMath.sub(totalMiner, pQ.totalMiner);
if (
(pQ.miningWarRound != miningWarRound && totalMiner >= pQ.numberOfTimes) ||
(pQ.miningWarRound == miningWarRound && totalMiner >= SafeMath.add(pQ.totalMiner, pQ.numberOfTimes))
) {
_isFinish = true;
}
}
function checkBuyEngineerQuest(address _addr) private view returns(bool _isFinish, uint256 _numberOfTimes, uint256 _number)
{
PlayerQuest memory pQ = playersQuests[_addr];
uint256 totalEngineer = getTotalEngineer(_addr);
_numberOfTimes = pQ.numberOfTimes;
_number = SafeMath.sub(totalEngineer, pQ.totalEngineer);
if (totalEngineer >= SafeMath.add(pQ.totalEngineer, pQ.numberOfTimes)) {
_isFinish = true;
}
}
function checkJoinAirdropQuest(address _addr) private view returns(bool _isFinish, uint256 _numberOfTimes, uint256 _number)
{
PlayerQuest memory pQ = playersQuests[_addr];
uint256 airdropGameId; // current airdrop game id
uint256 totalJoinAirdrop;
(airdropGameId , totalJoinAirdrop) = getPlayerAirdropGameData(_addr);
_numberOfTimes = pQ.numberOfTimes;
if (
(pQ.airdropGameId != airdropGameId) ||
(pQ.airdropGameId == airdropGameId && totalJoinAirdrop >= SafeMath.add(pQ.totalJoinAirdrop, pQ.numberOfTimes))
) {
_isFinish = true;
_number = _numberOfTimes;
}
}
function checkAtkPlayerQuest(address _addr) private view returns(bool _isFinish, uint256 _numberOfTimes, uint256 _number)
{
PlayerQuest memory pQ = playersQuests[_addr];
uint256 nextTimeAtkPlayer = getNextTimeAtkPlayer(_addr);
_numberOfTimes = pQ.numberOfTimes;
if (nextTimeAtkPlayer > pQ.nextTimeAtkPlayer) {
_isFinish = true;
_number = _numberOfTimes;
}
}
function ckeckAtkBossWannaCryQuest(address _addr) private view returns(bool _isFinish, uint256 _numberOfTimes, uint256 _number)
{
PlayerQuest memory pQ = playersQuests[_addr];
uint256 dameBossWannaCry; // current dame boss
uint256 levelBossWannaCry;
(levelBossWannaCry, dameBossWannaCry) = getPlayerBossWannaCryData(_addr);
_numberOfTimes = pQ.numberOfTimes;
if (pQ.levelBossWannaCry != levelBossWannaCry) _number = dameBossWannaCry;
if (pQ.levelBossWannaCry == levelBossWannaCry) _number = SafeMath.sub(dameBossWannaCry, pQ.dameBossWannaCry);
if (
(pQ.levelBossWannaCry != levelBossWannaCry && dameBossWannaCry >= pQ.numberOfTimes) ||
(pQ.levelBossWannaCry == levelBossWannaCry && dameBossWannaCry >= SafeMath.add(pQ.dameBossWannaCry, pQ.numberOfTimes))
) {
_isFinish = true;
}
}
// --------------------------------------------------------------------------------------------------------------
// INTERFACE FUNCTION INTERNAL
// --------------------------------------------------------------------------------------------------------------
// Mining War
function getMiningWarDealine () private view returns(uint256)
{
return MiningWar.deadline();
}
function getTotalMiner(address _addr) private view returns(uint256 _total)
{
uint256[8] memory _minersCount;
(, , , _minersCount, , , , ) = MiningWar.getPlayerData(_addr);
for (uint256 idx = 0; idx < 8; idx ++) {
_total += _minersCount[idx];
}
}
function getPlayerMiningWarData(address _addr) private view returns(uint256 _roundNumber, uint256 _referral_count)
{
(_roundNumber, , , , _referral_count, ) = MiningWar.players(_addr);
}
// ENGINEER
function addEngineerPrizePool(uint256 _value) private
{
Engineer.fallback.value(_value)();
}
function getGameSponsor() public view returns(address)
{
return Engineer.gameSponsor();
}
function getEngineerPrizePool() private view returns(uint256)
{
return Engineer.prizePool();
}
function getNextTimeAtkPlayer(address _addr) private view returns(uint256 _nextTimeAtk)
{
(, , , , , , , _nextTimeAtk,) = Engineer.getPlayerData(_addr);
}
function getTotalEngineer(address _addr) private view returns(uint256 _total)
{
uint256[8] memory _engineersCount;
(, , , , , , _engineersCount, ,) = Engineer.getPlayerData(_addr);
for (uint256 idx = 0; idx < 8; idx ++) {
_total += _engineersCount[idx];
}
}
// AIRDROP GAME
function getPlayerAirdropGameData(address _addr) private view returns(uint256 _currentGameId, uint256 _totalJoin)
{
(_currentGameId, , , , _totalJoin, ) = AirdropGame.players(_addr);
}
// BOSS WANNACRY
function getPlayerBossWannaCryData(address _addr) private view returns(uint256 _currentBossRoundNumber, uint256 _dame)
{
(_currentBossRoundNumber, , , , _dame, ) = BossWannaCry.players(_addr);
}
}
|
current game player info current quest of player
|
function getData(address _addr)
public
view
returns(
uint256 _prizePool,
uint256 _crystals,
uint256 _endTime,
uint256 _reward,
uint256 _share,
uint256 _questSequence,
uint256 _deposit,
uint256 _resetFreeTime,
uint256 _typeQuest,
uint256 _numberOfTimes,
uint256 _number,
bool _isFinish,
bool _haveQuest
) {
(_prizePool, _crystals, _endTime) = getCurrentGame();
(_reward, _share, _questSequence, , _resetFreeTime) = getPlayerData(_addr);
(_haveQuest, _typeQuest, _isFinish, _numberOfTimes, _number, _deposit) = getCurrentQuest(_addr);
}
| 12,611,704 |
./partial_match/97/0xfa165689a563a753Fd458107dB5b83E97921d9b0/sources/HollywoodToken.sol
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "HOLLY::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 11,384,249 |
./partial_match/5/0x77be012d30B357e34EfBc90Ec14da2CEF3Db208B/sources/Token.sol
|
set Admin Role . See {AccessControl}. Requirements: - the caller must have the `ADMIN_ROLE`./
|
function setRoleAdmin(bytes32 roleId, bytes32 adminRoleId) public {
_setRoleAdmin(roleId, adminRoleId);
}
| 16,887,340 |
./partial_match/3/0x0B1f567Ca36289d32d6df47C285A72667f342C72/sources/FUNDSZ.sol
|
roll up $50 - House bonus
|
function rollUpD50FL(address _user, uint _referralCount, uint _referralIndex) internal returns(uint){
if(((users[users[_user].referrals[_referralIndex]].membershipExpired).add(GRACE_PERIOD) >= now) && (users[users[_user].referrals[_referralIndex]].donated == 2)){
_referralCount++;
}
if(_referralIndex == 0)
return _referralCount;
_referralIndex--;
rollUpD50FL( _user, _referralCount, _referralIndex);
}
| 5,281,310 |
./full_match/43114/0xc9070B3EFE0aacC5AfB4B31C5DbDCA7C6B4bAAA9/sources/contracts/YieldWolf.sol
|
updates the performance fee can only be called by the owner _performanceFee new performance fee fee in basis points/
|
function setPerformanceFee(uint256 _performanceFee) external onlyOwner {
require(_performanceFee <= PERFORMANCE_FEE_CAP, 'setPerformanceFee: CAP_EXCEEDED');
performanceFee = _performanceFee;
emit SetPerformanceFee(_performanceFee);
}
| 4,507,351 |
// File: contracts/IERC20.sol
pragma solidity 0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts/SafeMath.sol
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @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) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: contracts/NETLINKStandard.sol
pragma solidity 0.4.24;
/**
* @title NETLINKStandard
* @dev the interface of NETLINKStandard
*/
contract NETLINKStandard {
uint256 public stakeStartTime;
uint256 public stakeMinAge;
uint256 public stakeMaxAge;
function mint() public returns (bool);
function coinAge() constant public returns (uint256);
function annualInterest() constant public returns (uint256);
event Mint(address indexed _address, uint _reward);
}
// File: contracts/Ownable.sol
pragma solidity 0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event 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;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit 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;
}
}
// File: contracts/NETLINK.sol
pragma solidity 0.4.24;
contract NETLINK is IERC20, NETLINKStandard, Ownable {
using SafeMath for uint256;
string public name = "NETLINK SHARES";
string public symbol = "NLS";
uint public decimals = 18;
uint public chainStartTime; //chain start time
uint public chainStartBlockNumber; //chain start block number
uint public stakeStartTime; //stake start time
uint public stakeMinAge = 1 days; // minimum age for coin age: 1D
uint public stakeMaxAge = 180 days; // stake age of full weight: 180D
uint public totalSupply;
uint public maxTotalSupply;
uint public totalInitialSupply;
uint constant MIN_STAKING = 1; // minium amount of token to stake
uint constant STAKE_START_TIME = 1576108800; // 12.12.2019
uint constant STEP1_ENDTIME = 1591833600; // 11.06.2020
uint constant STEP2_ENDTIME = 1607731200; // 12.12.2020
uint constant STEP3_ENDTIME = 1623369600; // 11.06.2021
uint constant STEP4_ENDTIME = 1639267200; // 12.12.2021
uint constant STEP5_ENDTIME = 1923264000; // 12.12.2050
struct Period {
uint start;
uint end;
uint interest;
}
mapping (uint => Period) periods;
mapping(address => bool) public noPOSRewards;
struct transferInStruct {
uint128 amount;
uint64 time;
}
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(address => transferInStruct[]) transferIns;
event Burn(address indexed burner, uint256 value);
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
modifier canPoSMint() {
require(totalSupply < maxTotalSupply);
_;
}
constructor() public {
// 50 mil is reserved for POS rewards
maxTotalSupply = 1500 * 10**23; // 150 Mil.
totalInitialSupply = 1000 * 10**23; // 100 Mil.
chainStartTime = now;
chainStartBlockNumber = block.number;
balances[msg.sender] = totalInitialSupply;
totalSupply = totalInitialSupply;
// 4 periods for 2 years
stakeStartTime = 1576108800;
periods[0] = Period(STAKE_START_TIME, STEP1_ENDTIME, 65 * 10 ** 18);
periods[1] = Period(STEP1_ENDTIME, STEP2_ENDTIME, 34 * 10 ** 18);
periods[2] = Period(STEP2_ENDTIME, STEP3_ENDTIME, 20 * 10 ** 18);
periods[3] = Period(STEP3_ENDTIME, STEP4_ENDTIME, 134 * 10 ** 16);
periods[4] = Period(STEP4_ENDTIME, STEP5_ENDTIME, 134 * 10 ** 16);
}
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
if (msg.sender == _to)
return mint();
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
if (transferIns[msg.sender].length > 0)
delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
return true;
}
function totalSupply() public view returns (uint256) {
return totalSupply;
}
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
if (transferIns[_from].length > 0)
delete transferIns[_from];
uint64 _now = uint64(now);
transferIns[_from].push(transferInStruct(uint128(balances[_from]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function mint() canPoSMint public returns (bool) {
// minimum stake of 1 NLS is required to earn staking.
if (balances[msg.sender] < MIN_STAKING.mul(1 ether))
return false;
if (transferIns[msg.sender].length <= 0)
return false;
uint reward = getProofOfStakeReward(msg.sender);
if (reward <= 0)
return false;
totalSupply = totalSupply.add(reward);
balances[msg.sender] = balances[msg.sender].add(reward);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now)));
emit Transfer(address(0), msg.sender, reward);
emit Mint(msg.sender, reward);
return true;
}
function getBlockNumber() view public returns (uint blockNumber) {
blockNumber = block.number.sub(chainStartBlockNumber);
}
function coinAge() constant public returns (uint myCoinAge) {
myCoinAge = getCoinAge(msg.sender,now);
}
function annualInterest() constant public returns (uint interest) {
uint _now = now;
interest = periods[getPeriodNumber(_now)].interest;
}
function getProofOfStakeReward(address _address) public view returns (uint totalReward) {
require((now >= stakeStartTime) && (stakeStartTime > 0));
require(!noPOSRewards[_address]);
uint _now = now;
totalReward = 0;
for (uint i=0; i < getPeriodNumber(_now) + 1; i ++) {
totalReward += (getCoinAgeofPeriod(_address, i, _now)).mul(periods[i].interest).div(100).div(365);
}
}
function getPeriodNumber(uint _now) public view returns (uint periodNumber) {
for (uint i = 4; i >= 0; i --) {
if( _now >= periods[i].start){
return i;
}
}
}
function getCoinAgeofPeriod(address _address, uint _pid, uint _now) public view returns (uint _coinAge) {
if (transferIns[_address].length <= 0)
return 0;
if (_pid < 0 || _pid > 4)
return 0;
_coinAge = 0;
uint nCoinSeconds;
uint i;
if (periods[_pid].start < _now &&
periods[_pid].end >= _now) {
// calculate the current period
for (i = 0; i < transferIns[_address].length; i ++) {
if (uint(periods[_pid].start) > uint(transferIns[_address][i].time) ||
uint(periods[_pid].end) <= uint(transferIns[_address][i].time))
continue;
nCoinSeconds = _now.sub(uint(transferIns[_address][i].time));
if (nCoinSeconds < stakeMinAge)
continue;
if ( nCoinSeconds > stakeMaxAge )
nCoinSeconds = stakeMaxAge;
nCoinSeconds = nCoinSeconds.sub(stakeMinAge);
_coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days));
}
}else{
// calculate for the ended preriods which user did not claimed
for (i = 0; i < transferIns[_address].length; i++) {
if (uint(periods[_pid].start) > uint(transferIns[_address][i].time) ||
uint(periods[_pid].end) <= uint(transferIns[_address][i].time))
continue;
nCoinSeconds = (uint(periods[_pid].end)).sub(uint(transferIns[_address][i].time));
if (nCoinSeconds < stakeMinAge)
continue;
if ( nCoinSeconds > stakeMaxAge )
nCoinSeconds = stakeMaxAge;
nCoinSeconds = nCoinSeconds.sub(stakeMinAge);
_coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days));
}
}
_coinAge = _coinAge.div(1 ether);
}
function getCoinAge(address _address, uint _now) internal view returns (uint _coinAge) {
if (transferIns[_address].length <= 0)
return 0;
for (uint i = 0; i < transferIns[_address].length; i++) {
if (_now < uint(transferIns[_address][i].time).add(stakeMinAge))
continue;
uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time));
if ( nCoinSeconds > stakeMaxAge )
nCoinSeconds = stakeMaxAge;
nCoinSeconds = nCoinSeconds.sub(stakeMinAge);
_coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days));
}
_coinAge = _coinAge.div(1 ether);
// return _coinAge;
}
// function ownerSetStakeStartTime(uint timestamp) onlyOwner public {
// require((stakeStartTime <= 0) && (timestamp >= chainStartTime));
// //stakeStartTime = timestamp;
// stakeStartTime = 1537228800
// }
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now)));
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function ownerBurnToken(uint _value) public onlyOwner {
require(_value > 0);
balances[msg.sender] = balances[msg.sender].sub(_value);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now)));
totalSupply = totalSupply.sub(_value);
totalInitialSupply = totalInitialSupply.sub(_value);
maxTotalSupply = maxTotalSupply.sub(_value*10);
emit Burn(msg.sender, _value);
}
/* Batch token transfer. Used by contract creator to distribute initial tokens to holders */
function batchTransfer(address[] _recipients, uint[] _values) onlyOwner public returns (bool) {
require(_recipients.length > 0 && _recipients.length == _values.length);
uint total = 0;
for (uint i = 0; i < _values.length; i++) {
total = total.add(_values[i]);
}
require(total <= balances[msg.sender]);
uint64 _now = uint64(now);
for (uint j = 0; j < _recipients.length; j++) {
balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]);
transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now));
emit Transfer(msg.sender, _recipients[j], _values[j]);
}
balances[msg.sender] = balances[msg.sender].sub(total);
if (transferIns[msg.sender].length > 0)
delete transferIns[msg.sender];
if (balances[msg.sender] > 0)
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
return true;
}
function disablePOSReward(address _account, bool _enabled) onlyOwner public {
noPOSRewards[_account] = _enabled;
}
}
|
return the address of the owner./
|
function owner() public view returns(address) {
return _owner;
}
| 1,000,535 |
./full_match/1/0xb49b0a89f5eFD0F55cb272Caa962D183068360d8/sources/contracts/PacemakerHonoraries.sol
|
activate or deactivate burning/
|
function flipBurnState() public onlyOwner {
burnIsActive = !burnIsActive;
}
| 3,141,055 |
./partial_match/97/0x54e9874f5fFFC4Bac58aFdFFcDc056564E8C1f63/sources/BEPTokenModal.sol
|
Interface of the ERC20 standard as defined in the EIP. Does not include the optional functions; to access them see {ERC20Detailed}./
|
interface IBEP20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address _owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 11,373,227 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
// data
string public name = "ArchStorage";
uint256 public fileIDs = 0;
uint256 public fileNum = 0;
uint256 public transactionCount = 0;
mapping(uint256 => File) public files;
mapping(address => UserDetail) user;
struct File {
uint256 fileId;
string fileHash;
uint256 fileSize;
string fileType;
string fileName;
string fileDescription;
uint256 uploadTime;
address uploader;
uint256 lastChange;
uint256 lastSize;
bool isPrivate;
string[] allowedUsers;
}
struct UserDetail {
address addr;
string name;
string password;
bool isUserLoggedIn;
}
struct Transaction {
address userAddress;
string userName;
uint256 fileId;
string fileName;
string fileHash;
uint256 fileSize;
string transactionType;
uint256 changeLevel;
uint256 uploadTime;
uint256 lastSize;
}
Transaction[] transactions;
//events
// event transactionAdded(Transaction temp);
event FileUploaded(
uint256 fileId,
string fileHash,
uint256 fileSize,
string fileType,
string fileName,
string fileDescription,
uint256 uploadTime,
address uploader,
uint256 lastChange,
uint256 lastSize,
bool isPrivate,
string[] allowedUsers
);
event FileUpdated(
string fileHash,
uint256 fileSize,
string fileType,
string fileName,
uint256 uploadTime,
address uploader,
uint256 lastChange,
uint256 lastSize,
bool isPrivate,
string[] allowedUsers
);
constructor() public {}
function uploadFile(
string memory _fileHash,
uint256 _fileSize,
string memory _fileType,
string memory _fileName,
string memory _fileDescription,
bool filePrivacy,
string[] memory allowedFileUsers
) public {
// Make sure the file hash exists
require(bytes(_fileHash).length > 0);
// Make sure file type exists
require(bytes(_fileType).length > 0);
require(
keccak256(abi.encodePacked(_fileType)) ==
keccak256(abi.encodePacked("text/plain")) ||
keccak256(abi.encodePacked(_fileType)) ==
keccak256(
abi.encodePacked(
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
) ||
keccak256(abi.encodePacked(_fileType)) ==
keccak256(abi.encodePacked("application/pdf"))
);
// Make sure file description exists
require(bytes(_fileDescription).length > 0);
// Make sure file fileName exists
require(bytes(_fileName).length > 0);
// Make sure uploader address exists
require(msg.sender != address(0));
// Make sure file size is more than 0
require(_fileSize > 0);
// Increment file id
fileIDs++;
fileNum++;
// Add File to the contract
files[fileIDs] = File(
fileIDs,
_fileHash,
_fileSize,
_fileType,
_fileName,
_fileDescription,
block.timestamp,
msg.sender,
0,
0,
filePrivacy,
allowedFileUsers
);
Transaction memory temp;
temp.userAddress = msg.sender;
temp.userName = user[msg.sender].name;
temp.fileId = fileIDs;
temp.fileName = _fileName;
temp.fileHash = _fileHash;
temp.fileSize = _fileSize;
temp.transactionType = "ADD";
temp.changeLevel = 0;
temp.lastSize = 0;
temp.uploadTime = block.timestamp;
transactions.push(temp);
transactionCount++;
// Trigger an event
emit FileUploaded(
fileIDs,
_fileHash,
_fileSize,
_fileType,
_fileName,
_fileDescription,
block.timestamp,
msg.sender,
0,
0,
filePrivacy,
allowedFileUsers
);
}
function updateFile(
string memory _fileHash,
uint256 _fileSize,
string memory _fileType,
string memory _fileName,
uint256 _fileID,
uint256 _changeValue,
uint256 _lastSize,
bool filePrivacy,
string[] memory allowedFileUsers,
string memory _fileDescription
) public {
// Make sure the file hash exists
require(bytes(_fileHash).length > 0);
// Make sure file type exists
require(bytes(_fileType).length > 0);
require(
keccak256(abi.encodePacked(_fileType)) ==
keccak256(abi.encodePacked("text/plain")) ||
keccak256(abi.encodePacked(_fileType)) ==
keccak256(
abi.encodePacked(
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
) ||
keccak256(abi.encodePacked(_fileType)) ==
keccak256(abi.encodePacked("application/pdf"))
);
require(bytes(_fileName).length > 0);
// Make sure uploader address exists
require(msg.sender != address(0));
// Make sure file size is more than 0
require(_fileSize > 0);
require(_fileID > 0 && _fileID <= fileIDs);
require(_changeValue >= 0);
// update current file
files[_fileID].fileHash = _fileHash;
files[_fileID].fileSize = _fileSize;
files[_fileID].fileType = _fileType;
files[_fileID].fileName = _fileName;
files[_fileID].uploadTime = block.timestamp;
files[_fileID].lastChange = _changeValue;
files[_fileID].lastSize = _lastSize;
files[_fileID].isPrivate = filePrivacy;
files[_fileID].allowedUsers = allowedFileUsers;
files[_fileID].fileDescription = _fileDescription;
Transaction memory temp;
temp.userAddress = msg.sender;
temp.userName = user[msg.sender].name;
temp.fileId = _fileID;
temp.fileName = files[_fileID].fileName;
temp.fileHash = _fileHash;
temp.fileSize = _fileSize;
temp.transactionType = "UPDATE";
temp.changeLevel = _changeValue;
temp.uploadTime = block.timestamp;
temp.lastSize = _lastSize;
transactions.push(temp);
transactionCount++;
// Trigger an event
emit FileUpdated(
_fileHash,
_fileSize,
_fileType,
_fileName,
block.timestamp,
msg.sender,
_changeValue,
_lastSize,
filePrivacy,
allowedFileUsers
);
}
function getFile(uint256 _fileID) public view returns (File memory) {
return files[_fileID];
}
function deleteFile(uint256 _fileID) public {
//require(_fileID.length > 0);
// for (uint256 i = 0; i < _fileID.length; i++) {
Transaction memory temp;
temp.userAddress = msg.sender;
temp.userName = user[msg.sender].name;
temp.fileId = _fileID;
temp.fileName = files[_fileID].fileName;
temp.fileHash = files[_fileID].fileHash;
temp.fileSize = files[_fileID].fileSize;
temp.transactionType = "DELETE";
temp.changeLevel = 0;
temp.uploadTime = block.timestamp;
transactions.push(temp);
transactionCount++;
delete files[_fileID];
fileNum -= 1;
// if (files[_fileID].isPrivate == false) {
// transactions.push(temp);
// transactionCount++;
// delete files[_fileID];
// fileNum -= 1;
// } else if (files[_fileID].isPrivate == true) {
// if (files[_fileID].uploader == msg.sender) {
// transactions.push(temp);
// transactionCount++;
// delete files[_fileID];
// fileNum -= 1;
// } else {
// for (
// uint256 i = 0;
// i < files[_fileID].allowedUsers.length;
// i++
// ) {
// if (files[_fileID].allowedUsers[i] == msg.sender) {
// transactions.push(temp);
// transactionCount++;
// delete files[_fileID];
// fileNum -= 1;
// }
// }
// }
// }
// }
}
// user registration function
function register(
address _address,
string memory _name,
string memory _password
) public returns (bool) {
require(user[_address].addr != msg.sender);
user[_address].addr = _address;
user[_address].name = _name;
user[_address].password = _password;
user[_address].isUserLoggedIn = false;
return true;
}
// user login function
function login(address _address, string memory _password)
public
returns (bool)
{
if (
keccak256(abi.encodePacked(user[_address].password)) ==
keccak256(abi.encodePacked(_password))
) {
user[_address].isUserLoggedIn = true;
return user[_address].isUserLoggedIn;
} else {
return false;
}
}
// check the user logged In or not
function checkIsUserLogged(address _address) public view returns (bool) {
return (user[_address].isUserLoggedIn);
}
function checkUserName(address _address)
public
view
returns (string memory)
{
return (user[_address].name);
}
// logout the user
function logout(address _address) public {
user[_address].isUserLoggedIn = false;
}
function getAllTransactions() public view returns (Transaction[] memory) {
return transactions;
}
function getAllowedUsers(uint256 fileID)
public
view
returns (string[] memory)
{
string[] memory gottenAllowedUsers;
return gottenAllowedUsers = files[fileID].allowedUsers;
}
}
|
Make sure the file hash exists Make sure file type exists Make sure uploader address exists Make sure file size is more than 0 update current file Trigger an event
|
function updateFile(
string memory _fileHash,
uint256 _fileSize,
string memory _fileType,
string memory _fileName,
uint256 _fileID,
uint256 _changeValue,
uint256 _lastSize,
bool filePrivacy,
string[] memory allowedFileUsers,
string memory _fileDescription
) public {
require(bytes(_fileHash).length > 0);
require(bytes(_fileType).length > 0);
require(
keccak256(abi.encodePacked(_fileType)) ==
keccak256(abi.encodePacked("text/plain")) ||
keccak256(abi.encodePacked(_fileType)) ==
keccak256(
abi.encodePacked(
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
)
) ||
keccak256(abi.encodePacked(_fileType)) ==
keccak256(abi.encodePacked("application/pdf"))
);
require(bytes(_fileName).length > 0);
require(msg.sender != address(0));
require(_fileSize > 0);
require(_fileID > 0 && _fileID <= fileIDs);
require(_changeValue >= 0);
files[_fileID].fileHash = _fileHash;
files[_fileID].fileSize = _fileSize;
files[_fileID].fileType = _fileType;
files[_fileID].fileName = _fileName;
files[_fileID].uploadTime = block.timestamp;
files[_fileID].lastChange = _changeValue;
files[_fileID].lastSize = _lastSize;
files[_fileID].isPrivate = filePrivacy;
files[_fileID].allowedUsers = allowedFileUsers;
files[_fileID].fileDescription = _fileDescription;
Transaction memory temp;
temp.userAddress = msg.sender;
temp.userName = user[msg.sender].name;
temp.fileId = _fileID;
temp.fileName = files[_fileID].fileName;
temp.fileHash = _fileHash;
temp.fileSize = _fileSize;
temp.transactionType = "UPDATE";
temp.changeLevel = _changeValue;
temp.uploadTime = block.timestamp;
temp.lastSize = _lastSize;
transactions.push(temp);
transactionCount++;
emit FileUpdated(
_fileHash,
_fileSize,
_fileType,
_fileName,
block.timestamp,
msg.sender,
_changeValue,
_lastSize,
filePrivacy,
allowedFileUsers
);
}
| 7,228,117 |
// SPDX-License-Identifier: MIT
pragma solidity <=0.8.0;
/**
* @title AddressProxy
* @author Kurt Merbeth </www.merbeth.io>
* @notice Stores contract names and their addresses in a mapping.
* @dev Addresses can be accessed by addresses["<contract name>"].
* In addition to the management of contract addresses in public 'addresses' mapping, several admins can be created and deleted.
* The owner cannot be deleted from the admins mapping, but can be changed.
*/
contract AddressProxy {
address public owner;
mapping(address => uint8) public admins;
mapping(string => address) public addresses;
/**
* @dev Set owner to msg.sender and add msg.sender to admins mapping.
*/
constructor () {
owner = msg.sender;
admins[msg.sender] = 1;
}
/**
* @dev Modifier checks if msg.sender is in admin mapping or is owner
* of this smart contract.
*/
modifier isAdmin() {
require((admins[msg.sender] > 0) || (msg.sender == owner), "address is not in owner list.");
_;
}
/**
* @dev Modifier checks if msg.sender is owner
*/
modifier isOwner() {
require(msg.sender == owner, "msg.sender is not owner");
_;
}
/**
* @dev Emitted when addresses mapping is modified.
*/
event contractAddressModified(string eventName, string contractName, address contractAddress);
/**
* @dev Emitted when admins mapping is modified.
*/
event adminModified(string eventName, address admin);
/**
* @dev Add a new contract address to addresses mapping.
* This function can only called by admins or owner.
* Emits an { contractAddressModified } event.
* @param name The name of the contract to add.
* @param contractAddress The address of the contract to add.
*/
function addContractAddress(string memory name, address contractAddress) public isAdmin {
addresses[name] = contractAddress;
emit contractAddressModified("add", name, contractAddress);
}
/**
* @dev Removes an address from addresses mapping.
* For this purpose the address of the sepcific contract is set to address(0) in addresses mapping.
* Emits an { contractAddressModified } event.
* @param name The name of the contract to remove
*/
function removeContractAddress(string memory name) public isAdmin {
address cAddress = addresses[name];
addresses[name] = address(0);
emit contractAddressModified("remove", name, cAddress);
}
/**
* @dev Adds a new admin to admins mapping.
* Function can only called by admins or owner.
* An admin can't add itself twice
* Emits an { adminModified } event.
* @param newAdmin Address of new admin.
*/
function addAdmin(address newAdmin) public isAdmin {
require(msg.sender != newAdmin, "address of new admin and msg.sender are the same");
admins[newAdmin] = 1;
emit adminModified("new", newAdmin);
}
/**
* @dev Removes an admin from admins mapping.
* Function can only called by admins or owner.
* Admins can't remove themself.
* Owner of this smart contract can't be removed drom admins list.
* Set admins[<address>] to 0.
* Emits an { adminModified } event.
* @param oldAdmin The address to remove from admins list.
*/
function removeAdmin(address oldAdmin) public isAdmin {
require(msg.sender != oldAdmin, "you can't remove yourself");
require(oldAdmin != owner, "owner can't removed from admin list");
admins[oldAdmin] = 0;
emit adminModified("rem", oldAdmin);
}
/**
* @dev Overwrites the existing owner.
* Only the current owner can call this function.
* Adds new owner to admins list if necessary.
* Emits an { adminModified } event.
* @param newOwner Address of the new owner.
*/
function setOwner(address newOwner) public isOwner {
owner = newOwner;
if(admins[newOwner] == 0) {
admins[newOwner] == 1;
}
emit adminModified("owner", newOwner);
}
}
|
Overwrites the existing owner. Only the current owner can call this function. Adds new owner to admins list if necessary. Emits an { adminModified } event. newOwner Address of the new owner./
|
function setOwner(address newOwner) public isOwner {
owner = newOwner;
if(admins[newOwner] == 0) {
admins[newOwner] == 1;
}
emit adminModified("owner", newOwner);
}
| 1,761,058 |
./full_match/1/0x899CC5f7e0dCCEC1565A6C39320f6716076d314c/sources/browser/Proxy.sol
|
Returns the current implementation. return impl Address of the current implementation/
|
function _implementation() internal view override returns (address impl) {
bytes32 slot = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
assembly {
impl := sload(slot)
}
}
| 16,447,208 |
./full_match/80001/0xA743Af88C6c92a790c9b9d857d8C82ACb352e6f3/sources/contracts/ClampSwap.sol
|
need to take IERC20 token approval from user before calling this function using this user able to swap and withdraw token to a address if receiver was not msg.sender and it's also a clamp account then it was need to update the reserveBaseTokenBalancesByAddress @note need to check for above condition
|
function indexSwapToERC20WithReceiver(
uint _indexIdentifier,
uint _percentage,
address _returnBaseToken,
address _receiver
) external {
uint[] memory amountsOut = internalSwapWithReceiver(
_indexIdentifier,
_percentage,
_returnBaseToken,
_receiver
);
if (_receiver == msg.sender) {
reserveBaseTokenBalancesByAddress[_receiver][
_returnBaseToken
] += sum(amountsOut);
}
}
| 9,485,319 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.7.0 <0.9.0;
pragma abicoder v2;
/**
* @title OpenHouse
* @dev Create, join, and interact with OpenHouse-enabled rooms
*/
contract OpenHouse {
string[] private rooms;
mapping (string => bool) private _roomsMap;
mapping (string => bool) private _roomsPublic;
mapping (string => address[]) private _memberships;
mapping (address => string[]) private _reverseMemberships;
mapping (string => mapping (address => bool)) private _membershipsMap;
/**
* @dev Create a room, or join it if it already exists.
* @param name defines the room
*/
function addRoom(string calldata name, bool isPublic) public {
if (!_roomsMap[name]){
_roomsMap[name] = true;
_roomsPublic[name] = isPublic;
rooms.push(name);
}
address sender = msg.sender;
if (!_membershipsMap[name][sender]) {
_membershipsMap[name][sender] = true;
_memberships[name].push(sender);
_reverseMemberships[sender].push(name);
}
}
/**
* @dev List all rooms that have already been created.
*/
function listRooms() public view returns (string[] memory) {
return rooms;
}
/**
* @dev List all rooms for which the sender has membership
*/
function listSenderRooms() public view returns (string[] memory) {
address sender = msg.sender;
return _reverseMemberships[sender];
}
/**
* @dev Check if the sender is a member of the given room
* @param name specifies the room to check membership for
*/
function senderIsInRoom(string calldata name) public view returns (bool) {
address sender = msg.sender;
return _membershipsMap[name][sender];
}
/**
* @dev Check if a room exists
*/
function roomExists(string calldata name) public view returns (bool) {
return _roomsMap[name];
}
/**
* @dev Check if a room is public
*/
function roomIsPublic(string calldata name) public view returns (bool) {
return _roomsPublic[name];
}
/**
* @dev Return the list of addresses that belong to a room.
* @param name specifies the room to list memberships for.
*/
function members(string calldata name) public view returns (address[] memory) {
return _memberships[name];
}
}
|
Check if a room is public/
|
function roomIsPublic(string calldata name) public view returns (bool) {
return _roomsPublic[name];
}
| 5,476,188 |
./partial_match/1/0xF66C6fDBDD7d57dD14D23d0C8A4E58Cc4869bBfa/sources/vsToken.sol
|
EARLY RELEASE CODE /
|
function setEarlyReleaseFee(
address _wallet,
uint32 _duration,
uint8 _percentage
) external onlyOwner {
_setEarlyReleaseFee(_wallet, _duration, _percentage);
}
| 3,949,067 |
./full_match/1/0x94D792E07216796Cb235E328823199fb8DA3C911/sources/src/manager/Manager.sol
|
A DAO's contract addresses from its token _token The ERC-721 token address return metadata Metadata deployed address return auction Auction deployed address return treasury Treasury deployed address return governor Governor deployed address
|
function getAddresses(address _token)
external
view
returns (
address metadata,
address auction,
address treasury,
address governor
)
{
DAOAddresses storage addresses = daoAddressesByToken[_token];
metadata = addresses.metadata;
auction = addresses.auction;
treasury = addresses.treasury;
governor = addresses.governor;
}
| 3,052,230 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.6;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/drafts/ERC20Permit.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol";
import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import "@uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol";
import "./interfaces/IVault.sol";
import "./interfaces/IUniversalVault.sol";
/// @title Hypervisor
/// @notice A Uniswap V2-like interface with fungible liquidity to Uniswap V3
/// which allows for arbitrary liquidity provision: one-sided, lop-sided, and balanced
contract Hypervisor is IVault, IUniswapV3MintCallback, IUniswapV3SwapCallback, ERC20Permit, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SignedSafeMath for int256;
IUniswapV3Pool public pool;
IERC20 public token0;
IERC20 public token1;
uint24 public fee;
int24 public tickSpacing;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
address public owner;
uint256 public deposit0Max;
uint256 public deposit1Max;
uint256 public maxTotalSupply;
mapping(address => bool) public list; /// whitelist of depositors
bool public whitelisted; /// depositors must be on list
bool public directDeposit; /// enter uni on deposit (avoid if client uses public rpc)
uint256 public constant PRECISION = 1e36;
bool rebalanceCalled;
bool mintCalled;
/// events
event MaxTotalSupplySet(uint256 _maxTotalSupply);
event DepositMaxSet(uint256 _deposit0Max, uint256 _deposit1Max);
/// @param _pool Uniswap V3 pool for which liquidity is managed
/// @param _owner Owner of the Hypervisor
constructor(
address _pool,
address _owner,
string memory name,
string memory symbol
) ERC20Permit(name) ERC20(name, symbol) {
require(_pool != address(0));
require(_owner != address(0));
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
require(address(token0) != address(0));
require(address(token1) != address(0));
fee = pool.fee();
tickSpacing = pool.tickSpacing();
owner = _owner;
maxTotalSupply = 0; /// no cap
deposit0Max = uint256(-1);
deposit1Max = uint256(-1);
whitelisted = false;
}
/// @notice Deposit tokens
/// @param deposit0 Amount of token0 transfered from sender to Hypervisor
/// @param deposit1 Amount of token1 transfered from sender to Hypervisor
/// @param to Address to which liquidity tokens are minted
/// @param from Address from which asset tokens are transferred
/// @return shares Quantity of liquidity tokens minted as a result of deposit
function deposit(
uint256 deposit0,
uint256 deposit1,
address to,
address from
) external override returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0);
require(deposit0 <= deposit0Max && deposit1 <= deposit1Max);
require(to != address(0) && to != address(this), "to");
require(!whitelisted || list[msg.sender]);
/// update fees
(uint128 baseLiquidity, uint128 limitLiquidity) = zeroBurn();
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
shares = deposit1.add(deposit0.mul(price).div(PRECISION));
if (deposit0 > 0) {
token0.safeTransferFrom(from, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(from, address(this), deposit1);
}
uint256 total = totalSupply();
if (total != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(total).div(pool0PricedInToken1.add(pool1));
if (directDeposit) {
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
}
_mint(to, shares);
emit Deposit(from, to, shares, deposit0, deposit1);
/// Check total supply cap not exceeded. A value of 0 means no limit.
require(maxTotalSupply == 0 || total <= maxTotalSupply, "max");
}
/// @notice Update fees of the positions
/// @return baseLiquidity Fee of base position
/// @return limitLiquidity Fee of limit position
function zeroBurn() internal returns(uint128 baseLiquidity, uint128 limitLiquidity) {
/// update fees for inclusion
(baseLiquidity, , ) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(limitLiquidity, , ) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
}
/// @notice Pull liquidity tokens from liquidity and receive the tokens
/// @param shares Number of liquidity tokens to pull from liquidity
/// @return base0 amount of token0 received from base position
/// @return base1 amount of token1 received from base position
/// @return limit0 amount of token0 received from limit position
/// @return limit1 amount of token1 received from limit position
function pullLiquidity(
uint256 shares
) external onlyOwner returns(
uint256 base0,
uint256 base1,
uint256 limit0,
uint256 limit1
) {
zeroBurn();
(base0, base1) = _burnLiquidity(
baseLower,
baseUpper,
_liquidityForShares(baseLower, baseUpper, shares),
address(this),
false
);
(limit0, limit1) = _burnLiquidity(
limitLower,
limitUpper,
_liquidityForShares(limitLower, limitUpper, shares),
address(this),
false
);
}
/// @param shares Number of liquidity tokens to redeem as pool assets
/// @param to Address to which redeemed pool assets are sent
/// @param from Address from which liquidity tokens are sent
/// @return amount0 Amount of token0 redeemed by the submitted liquidity tokens
/// @return amount1 Amount of token1 redeemed by the submitted liquidity tokens
function withdraw(
uint256 shares,
address to,
address from
) nonReentrant external override returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0), "to");
/// update fees
zeroBurn();
/// Withdraw liquidity from Uniswap pool
(uint256 base0, uint256 base1) = _burnLiquidity(
baseLower,
baseUpper,
_liquidityForShares(baseLower, baseUpper, shares),
to,
false
);
(uint256 limit0, uint256 limit1) = _burnLiquidity(
limitLower,
limitUpper,
_liquidityForShares(limitLower, limitUpper, shares),
to,
false
);
// Push tokens proportional to unused balances
uint256 supply = totalSupply();
uint256 unusedAmount0 = token0.balanceOf(address(this)).mul(shares).div(supply);
uint256 unusedAmount1 = token1.balanceOf(address(this)).mul(shares).div(supply);
if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0);
if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1);
amount0 = base0.add(limit0).add(unusedAmount0);
amount1 = base1.add(limit1).add(unusedAmount1);
require(
from == msg.sender || IUniversalVault(from).owner() == msg.sender,
"own"
);
_burn(from, shares);
emit Withdraw(from, to, shares, amount0, amount1);
}
/// @param _baseLower The lower tick of the base position
/// @param _baseUpper The upper tick of the base position
/// @param _limitLower The lower tick of the limit position
/// @param _limitUpper The upper tick of the limit position
/// @param feeRecipient Address of recipient of 10% of earned fees since last rebalance
/// @param swapQuantity Quantity of tokens to swap; if quantity is positive,
/// `swapQuantity` token0 are swaped for token1, if negative, `swapQuantity`
/// token1 is swaped for token0
/// @param amountMin Minimum Amount of tokens should be received in swap
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address feeRecipient,
int256 swapQuantity,
int256 amountMin,
uint160 sqrtPriceLimitX96
) nonReentrant external override onlyOwner {
require(
_baseLower < _baseUpper &&
_baseLower % tickSpacing == 0 &&
_baseUpper % tickSpacing == 0
);
require(
_limitLower < _limitUpper &&
_limitLower % tickSpacing == 0 &&
_limitUpper % tickSpacing == 0
);
require(
_limitUpper != _baseUpper ||
_limitLower != _baseLower
);
require(feeRecipient != address(0));
/// update fees
(uint128 baseLiquidity, uint128 limitLiquidity) = zeroBurn();
/// Withdraw all liquidity and collect all fees from Uniswap pool
(, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper);
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
(baseLiquidity, , ) = _position(baseLower, baseUpper);
(limitLiquidity, , ) = _position(limitLower, limitUpper);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true);
/// transfer 10% of fees for VISR buybacks
if (fees0 > 0) token0.safeTransfer(feeRecipient, fees0.div(10));
if (fees1 > 0) token1.safeTransfer(feeRecipient, fees1.div(10));
emit Rebalance(
currentTick(),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
fees0,
fees1,
totalSupply()
);
/// swap tokens if required
if (swapQuantity != 0) {
rebalanceCalled = true;
pool.swap(
address(this),
swapQuantity > 0,
swapQuantity > 0 ? swapQuantity : -swapQuantity,
sqrtPriceLimitX96,
abi.encode(amountMin)
);
}
baseLower = _baseLower;
baseUpper = _baseUpper;
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLower = _limitLower;
limitUpper = _limitUpper;
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
/// @notice Compound pending fees
/// @return baseToken0Owed Pending fees of base token0
/// @return baseToken1Owed Pending fees of base token1
/// @return limitToken0Owed Pending fees of limit token0
/// @return limitToken1Owed Pending fees of limit token1
function compound() external onlyOwner returns (
uint128 baseToken0Owed,
uint128 baseToken1Owed,
uint128 limitToken0Owed,
uint128 limitToken1Owed
) {
// update fees for compounding
zeroBurn();
(, baseToken0Owed,baseToken1Owed) = _position(baseLower, baseUpper);
(, limitToken0Owed,limitToken1Owed) = _position(limitLower, limitUpper);
// collect fees
pool.collect(address(this), baseLower, baseLower, baseToken0Owed, baseToken1Owed);
pool.collect(address(this), limitLower, limitUpper, limitToken0Owed, limitToken1Owed);
uint128 baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
uint128 limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
/// @notice Add tokens to base liquidity
/// @param amount0 Amount of token0 to add
/// @param amount1 Amount of token1 to add
function addBaseLiquidity(uint256 amount0, uint256 amount1) external onlyOwner {
uint128 baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0,
amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
}
/// @notice Add tokens to limit liquidity
/// @param amount0 Amount of token0 to add
/// @param amount1 Amount of token1 to add
function addLimitLiquidity(uint256 amount0, uint256 amount1) external onlyOwner {
uint128 limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0,
amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
/// @notice Adds the liquidity for the given position
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param liquidity The amount of liquidity to mint
/// @param payer Payer Data
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address payer
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
mintCalled = true;
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(payer)
);
}
}
/// @notice Burn liquidity from the sender and collect tokens owed for the liquidity
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param liquidity The amount of liquidity to burn
/// @param to The address which should receive the fees collected
/// @param collectAll If true, collect all tokens owed in the pool, else collect the owed tokens of the burn
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
/// Burn liquidity
(uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);
// Collect amount owed
uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);
uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);
}
}
}
/// @notice Get the liquidity amount for given liquidity tokens
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param shares Shares of position
/// @return The amount of liquidity toekn for shares
function _liquidityForShares(
int24 tickLower,
int24 tickUpper,
uint256 shares
) internal view returns (uint128) {
(uint128 position, , ) = _position(tickLower, tickUpper);
return _uint128Safe(uint256(position).mul(shares).div(totalSupply()));
}
/// @notice Get the info of the given position
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @return liquidity The amount of liquidity of the position
/// @return tokensOwed0 Amount of token0 owed
/// @return tokensOwed1 Amount of token1 owed
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (
uint128 liquidity,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper));
(liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey);
}
/// @notice Callback function of uniswapV3Pool mint
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool));
require(mintCalled == true);
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
mintCalled = false;
}
/// @notice Callback function of uniswapV3Pool swap
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external override {
require(msg.sender == address(pool));
require(rebalanceCalled == true);
int256 amountMin = abi.decode(data, (int256));
if (amount0Delta > 0) {
require(amount0Delta >= amountMin);
token0.safeTransfer(msg.sender, uint256(amount0Delta));
} else if (amount1Delta > 0) {
require(amount1Delta >= amountMin);
token1.safeTransfer(msg.sender, uint256(amount1Delta));
}
rebalanceCalled = false;
}
/// @return total0 Quantity of token0 in both positions and unused in the Hypervisor
/// @return total1 Quantity of token1 in both positions and unused in the Hypervisor
function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) {
(, uint256 base0, uint256 base1) = getBasePosition();
(, uint256 limit0, uint256 limit1) = getLimitPosition();
total0 = token0.balanceOf(address(this)).add(base0).add(limit0);
total1 = token1.balanceOf(address(this)).add(base1).add(limit1);
}
/// @return liquidity Amount of total liquidity in the base position
/// @return amount0 Estimated amount of token0 that could be collected by
/// burning the base position
/// @return amount1 Estimated amount of token1 that could be collected by
/// burning the base position
function getBasePosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(
baseLower,
baseUpper
);
(amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
/// @return liquidity Amount of total liquidity in the limit position
/// @return amount0 Estimated amount of token0 that could be collected by
/// burning the limit position
/// @return amount1 Estimated amount of token1 that could be collected by
/// burning the limit position
function getLimitPosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(
limitLower,
limitUpper
);
(amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
/// @notice Get the amounts of the given numbers of liquidity tokens
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidity The amount of liquidity tokens
/// @return Amount of token0 and token1
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
/// @notice Get the liquidity amount of the given numbers of token0 and token1
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0
/// @param amount0 The amount of token1
/// @return Amount of liquidity tokens
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
/// @return tick Uniswap pool's current price tick
function currentTick() public view returns (int24 tick) {
(, tick, , , , , ) = pool.slot0();
}
function _uint128Safe(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
/// @param _maxTotalSupply The maximum liquidity token supply the contract allows
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner {
maxTotalSupply = _maxTotalSupply;
emit MaxTotalSupplySet(_maxTotalSupply);
}
/// @param _deposit0Max The maximum amount of token0 allowed in a deposit
/// @param _deposit1Max The maximum amount of token1 allowed in a deposit
function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external onlyOwner {
deposit0Max = _deposit0Max;
deposit1Max = _deposit1Max;
emit DepositMaxSet(_deposit0Max, _deposit1Max);
}
/// @param listed Array of addresses to be appended
function appendList(address[] memory listed) external onlyOwner {
for (uint8 i; i < listed.length; i++) {
list[listed[i]] = true;
}
}
/// @param listed Address of listed to remove
function removeListed(address listed) external onlyOwner {
list[listed] = false;
}
/// @notice Toggle Direct Deposit
function toggleDirectDeposit() external onlyOwner {
directDeposit = !directDeposit;
}
/// @notice Toogle Whitelist configuration
function toggleWhitelist() external onlyOwner {
whitelisted = !whitelisted;
}
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
modifier onlyOwner {
require(msg.sender == owner, "only owner");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.5 <0.8.0;
import "../token/ERC20/ERC20.sol";
import "./IERC20Permit.sol";
import "../cryptography/ECDSA.sol";
import "../utils/Counters.sol";
import "./EIP712.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping (address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) internal EIP712(name, "1") {
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// 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 = ECDSA.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();
}
}
// 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity 0.7.6;
interface IVault {
function deposit(
uint256,
uint256,
address,
address
) external returns (uint256);
function withdraw(
uint256,
address,
address
) external returns (uint256, uint256);
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address feeRecipient,
int256 swapQuantity,
int256 amountMin,
uint160 sqrtPriceLimitX96
) external;
function getTotalAmounts() external view returns (uint256, uint256);
event Deposit(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Withdraw(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Rebalance(
int24 tick,
uint256 totalAmount0,
uint256 totalAmount1,
uint256 feeAmount0,
uint256 feeAmount1,
uint256 totalSupply
);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
interface IUniversalVault {
/* user events */
event Locked(address delegate, address token, uint256 amount);
event Unlocked(address delegate, address token, uint256 amount);
event RageQuit(address delegate, address token, bool notified, string reason);
/* data types */
struct LockData {
address delegate;
address token;
uint256 balance;
}
/* initialize function */
function initialize() external;
/* user functions */
function lock(
address token,
uint256 amount,
bytes calldata permission
) external;
function unlock(
address token,
uint256 amount,
bytes calldata permission
) external;
function rageQuit(address delegate, address token)
external
returns (bool notified, string memory error);
function transferERC20(
address token,
address to,
uint256 amount
) external;
function transferETH(address to, uint256 amount) external payable;
/* pure functions */
function calculateLockID(address delegate, address token)
external
pure
returns (bytes32 lockID);
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) external view returns (bytes32 permissionHash);
function getNonce() external view returns (uint256 nonce);
function owner() external view returns (address ownerAddress);
function getLockSetCount() external view returns (uint256 count);
function getLockAt(uint256 index) external view returns (LockData memory lockData);
function getBalanceDelegated(address token, address delegate)
external
view
returns (uint256 balance);
function getBalanceLocked(address token) external view returns (uint256 balance);
function checkBalances() external view returns (bool validity);
}
// 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.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-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.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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) internal {
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 = _getChainId();
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view virtual returns (bytes32) {
if (_getChainId() == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
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()
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
|
Add tokens to base liquidity amount0 Amount of token0 to add amount1 Amount of token1 to add
|
function addBaseLiquidity(uint256 amount0, uint256 amount1) external onlyOwner {
uint128 baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0,
amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
}
| 1,467,191 |
pragma solidity 0.4.24;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./lib/Whitelist.sol";
import "./lib/Withdrawable.sol";
import "./TraceToSPListInterface.sol";
/**
* @title TraceToSPList
* @dev This contract is the whitelist contract for service providers.
*/
contract TraceToSPList is Whitelist, TraceToSPListInterface{
using SafeMath for uint256;
struct meta {
uint256 ratePerService;
string companyName;
string email;
string uriForRubrics;
string hashFroRubrics;
uint256 lv;
uint256 idx;
}
mapping(address => meta) pendingMetaInfo;
mapping(address => meta) metaInfo;
address[] spList;
event NewPendingSP(address sp);
event RateUpdated(address sp, uint256 rate);
/**
* @dev only service providers
*/
modifier onlySP {
require(isSP(msg.sender));
_;
}
/**
* @dev constructor of this contract, it will use the constructor of whiltelist contract
* @param owner Owner of this contract
*/
constructor( address owner ) Whitelist(owner) public {}
/**
* @dev add the current wallet as a pending sp
* @param _rate the service price for this sp
* @param _companyName the company name for this sp
* @param _uriForRubrics IPFS link for a JSON object data which contains rubrics
* @param _hashFroRubrics hash for the JSON object data
* @param _lv level of infomation they are checking
*/
function addPendingSP(uint256 _rate, string _companyName, string _email, string _uriForRubrics, string _hashFroRubrics, uint256 _lv)
public {
pendingMetaInfo[msg.sender] = meta(_rate, _companyName, _email, _uriForRubrics, _hashFroRubrics, _lv, 0);
emit NewPendingSP(msg.sender);
}
/**
* @dev Approve a pending sp, only can be called by the owner
* @param _sp the address of this sp
*/
function approveSP(address _sp)
public
onlyOwner {
spList.push(_sp);
metaInfo[_sp] = pendingMetaInfo[_sp];
metaInfo[_sp].idx = spList.length - 1;
delete pendingMetaInfo[_sp];
addAddressToWhitelist(_sp);
}
/**
* @dev Remove a sp, only can be called by the owner
* @param _sp the address of this sp
*/
function removeSP(address _sp)
public
onlyOwner {
if(spList.length == 1){
delete spList[0];
}else{
spList[metaInfo[_sp].idx] = spList[spList.length-1];
}
spList.length = spList.length-1;
delete metaInfo[_sp];
removeAddressFromWhitelist(_sp);
}
/**
* @dev Update the service price for verifiers themselves, only can be called by the verifiers
* @param _rate the updated price
*/
function setRate(uint256 _rate)
public
onlySP{
metaInfo[msg.sender].ratePerService = _rate;
emit RateUpdated(msg.sender, _rate);
}
/**
* @dev get the full list of SPs
* @param _startIdx the start idx for retreving
* @param _length the list length
* @return SPs the list of SPs
*/
function getSPList(uint256 _startIdx, uint256 _length)
public
view
returns (address[] SPs){
require(_startIdx+_length <= spList.length);
SPs = new address[](_length);
for (uint256 i = 0; i<_length; i++){
SPs[i] = spList[i+_startIdx];
}
}
/**
* @dev check whether a wallet is a sp
* @param _sp the wallet going to be checked
* @return _isSP true if the user is a sp
*/
function isSP(address _sp)
public
view
returns (bool _isSP){
return isWhitelisted(_sp);
}
/**
* @dev get the price for a SP
* @param _sp the wallet that is going to be checked
* @return _rate the price in t2t
*/
function getSPRate(address _sp)
public
view
returns (uint256 _rate){
return metaInfo[_sp].ratePerService;
}
/**
* @dev check/get details of a pending sp
* @return _rate the service price for this sp
* @return _companyName the company name for this sp
* @return _uriForRubrics IPFS link for a JSON object data which contains rubrics, for the format of rubrics please check docs.traceto.io
* @return _hashFroRubrics hash for the JSON object data
* @return _lv level of infomation they are checking
*/
function getPendingSPDetail(address _sp)
public
view
returns (uint256 _rate, string _companyName, string _email, string _uriForRubrics, string _hashFroRubrics, uint256 _lv){
return (pendingMetaInfo[_sp].ratePerService, pendingMetaInfo[_sp].companyName, pendingMetaInfo[_sp].email, pendingMetaInfo[_sp].uriForRubrics, pendingMetaInfo[_sp].hashFroRubrics, pendingMetaInfo[_sp].lv);
}
/**
* @dev check get details of a sp
* @return _rate the service price for this sp
* @return _companyName the company name for this sp
* @return _uriForRubrics IPFS link for a JSON object data which contains rubrics
* @return _hashFroRubrics hash for the JSON object data
* @return _lv level of infomation they are checking
*/
function getSPDetail(address _sp)
public
view
returns (uint256 _rate, string _companyName, string _email, string _uriForRubrics, string _hashFroRubrics, uint256 _lv){
return (metaInfo[_sp].ratePerService, metaInfo[_sp].companyName, metaInfo[_sp].email, metaInfo[_sp].uriForRubrics, metaInfo[_sp].hashFroRubrics, metaInfo[_sp].lv);
}
}
|
Approve a pending sp, only can be called by the owner _sp the address of this sp/
|
function approveSP(address _sp)
public
onlyOwner {
spList.push(_sp);
metaInfo[_sp] = pendingMetaInfo[_sp];
metaInfo[_sp].idx = spList.length - 1;
delete pendingMetaInfo[_sp];
addAddressToWhitelist(_sp);
}
| 1,772,679 |
./full_match/4/0xf4DFaA57818f57243801CE729d34c1eC8AD47CfF/sources/browser/hook.sol
|
pay referral 10% pay equal from 40% to 6 parent
|
function payIndex1(uint256 _baseUserId,uint256 _planIndex, uint256 _referrerId,uint256 _paidAmount, uint[11] memory prcnt) internal returns(bool)
{
uint256 _networkId = networkId;
boosterGain[_referrerId][_planIndex] += _paidAmount * prcnt[0] / 100000000;
uint256 pId = _baseUserId;
uint256 tmp;
uint256 i;
for(i=0;i<6;i++)
{
( ,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId);
boosterGain[pId][i] += _paidAmount * prcnt[1] / 100000000;
}
tmp = 0;
uint tmp2;
for(i=0;i<5;i++)
{
( ,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,_planIndex,false, pId);
tmp = _paidAmount * prcnt[i+2] / 100000000;
tmp2 = 0;
if(i > 2) tmp2 = (2**(_planIndex +1)) * levelBuyPrice[0] * prcnt[i+5] / 100000000;
autoPoolGain[pId][_planIndex][i+1] += tmp - tmp2;
reInvestGain[pId] += tmp2;
}
if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod;
}
| 742,450 |
./full_match/1313161554/0xEF72330b252490648D01B242eCfFbb10b3C01B61/sources/contracts/JetStaking/JetStakingV2.sol
|
withdraw a set of stream Ids. Allows user to select stream ids to withdraw from UI. streamIds to withdraw.
|
function batchWithdraw(uint256[] calldata streamIds)
external
virtual
pausable(1)
{
User storage userAccount = users[msg.sender];
for (uint256 i = 0; i < streamIds.length; i++) {
if (
userAccount.pendings[streamIds[i]] != 0 &&
block.timestamp > userAccount.releaseTime[streamIds[i]]
) {
_withdraw(streamIds[i]);
}
}
}
| 13,233,194 |
pragma solidity ^0.4.11;
/// @dev `Owned` is a base level contract that assigns an `owner` that can be
/// later changed
contract Owned {
/// @dev `owner` is the only address that can call a function with this
/// modifier
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
address public owner;
/// @notice The Constructor assigns the message sender to be `owner`
function Owned() {
owner = msg.sender;
}
address public newOwner;
/// @notice `owner` can step down and assign some other address to this role
/// @param _newOwner The address of the new owner. 0x0 can be used to create
/// an unowned neutral vault, however that cannot be undone
function changeOwner(address _newOwner) onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
}
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
contract ERC20Token {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) 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) 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) 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) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/*
Copyright 2017, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title DynamicCeiling Contract
/// @author Jordi Baylina
/// @dev This contract calculates the ceiling from a series of curves.
/// These curves are committed first and revealed later.
/// All the curves must be in increasing order and the last curve is marked
/// as the last one.
/// This contract allows to hide and reveal the ceiling at will of the owner.
contract DynamicCeiling is Owned {
using SafeMath for uint256;
struct Curve {
bytes32 hash;
// Absolute limit for this curve
uint256 limit;
// The funds remaining to be collected are divided by `slopeFactor` smooth ceiling
// with a long tail where big and small buyers can take part.
uint256 slopeFactor;
// This keeps the curve flat at this number, until funds to be collected is less than this
uint256 collectMinimum;
}
address public contribution;
Curve[] public curves;
uint256 public currentIndex;
uint256 public revealedCurves;
bool public allRevealed;
/// @dev `contribution` is the only address that can call a function with this
/// modifier
modifier onlyContribution {
require(msg.sender == contribution);
_;
}
function DynamicCeiling(address _owner, address _contribution) {
owner = _owner;
contribution = _contribution;
}
/// @notice This should be called by the creator of the contract to commit
/// all the curves.
/// @param _curveHashes Array of hashes of each curve. Each hash is calculated
/// by the `calculateHash` method. More hashes than actual curves can be
/// committed in order to hide also the number of curves.
/// The remaining hashes can be just random numbers.
function setHiddenCurves(bytes32[] _curveHashes) public onlyOwner {
require(curves.length == 0);
curves.length = _curveHashes.length;
for (uint256 i = 0; i < _curveHashes.length; i = i.add(1)) {
curves[i].hash = _curveHashes[i];
}
}
/// @notice Anybody can reveal the next curve if he knows it.
/// @param _limit Ceiling cap.
/// (must be greater or equal to the previous one).
/// @param _last `true` if it's the last curve.
/// @param _salt Random number used to commit the curve
function revealCurve(uint256 _limit, uint256 _slopeFactor, uint256 _collectMinimum,
bool _last, bytes32 _salt) public {
require(!allRevealed);
require(curves[revealedCurves].hash == calculateHash(_limit, _slopeFactor, _collectMinimum,
_last, _salt));
require(_limit != 0 && _slopeFactor != 0 && _collectMinimum != 0);
if (revealedCurves > 0) {
require(_limit >= curves[revealedCurves.sub(1)].limit);
}
curves[revealedCurves].limit = _limit;
curves[revealedCurves].slopeFactor = _slopeFactor;
curves[revealedCurves].collectMinimum = _collectMinimum;
revealedCurves = revealedCurves.add(1);
if (_last) allRevealed = true;
}
/// @notice Reveal multiple curves at once
function revealMulti(uint256[] _limits, uint256[] _slopeFactors, uint256[] _collectMinimums,
bool[] _lasts, bytes32[] _salts) public {
// Do not allow none and needs to be same length for all parameters
require(_limits.length != 0 &&
_limits.length == _slopeFactors.length &&
_limits.length == _collectMinimums.length &&
_limits.length == _lasts.length &&
_limits.length == _salts.length);
for (uint256 i = 0; i < _limits.length; i = i.add(1)) {
revealCurve(_limits[i], _slopeFactors[i], _collectMinimums[i],
_lasts[i], _salts[i]);
}
}
/// @notice Move to curve, used as a failsafe
function moveTo(uint256 _index) public onlyOwner {
require(_index < revealedCurves && // No more curves
_index == currentIndex.add(1)); // Only move one index at a time
currentIndex = _index;
}
/// @return Return the funds to collect for the current point on the curve
/// (or 0 if no curves revealed yet)
function toCollect(uint256 collected) public onlyContribution returns (uint256) {
if (revealedCurves == 0) return 0;
// Move to the next curve
if (collected >= curves[currentIndex].limit) { // Catches `limit == 0`
uint256 nextIndex = currentIndex.add(1);
if (nextIndex >= revealedCurves) return 0; // No more curves
currentIndex = nextIndex;
if (collected >= curves[currentIndex].limit) return 0; // Catches `limit == 0`
}
// Everything left to collect from this limit
uint256 difference = curves[currentIndex].limit.sub(collected);
// Current point on the curve
uint256 collect = difference.div(curves[currentIndex].slopeFactor);
// Prevents paying too much fees vs to be collected; breaks long tail
if (collect <= curves[currentIndex].collectMinimum) {
if (difference > curves[currentIndex].collectMinimum) {
return curves[currentIndex].collectMinimum;
} else {
return difference;
}
} else {
return collect;
}
}
/// @notice Calculates the hash of a curve.
/// @param _limit Ceiling cap.
/// @param _last `true` if it's the last curve.
/// @param _salt Random number that will be needed to reveal this curve.
/// @return The calculated hash of this curve to be used in the `setHiddenCurves` method
function calculateHash(uint256 _limit, uint256 _slopeFactor, uint256 _collectMinimum,
bool _last, bytes32 _salt) public constant returns (bytes32) {
return keccak256(_limit, _slopeFactor, _collectMinimum, _last, _salt);
}
/// @return Return the total number of curves committed
/// (can be larger than the number of actual curves on the curve to hide
/// the real number of curves)
function nCurves() public constant returns (uint256) {
return curves.length;
}
}
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount)
returns(bool);
}
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { if (msg.sender != controller) throw; _; }
address public controller;
function Controlled() { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data);
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.1'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = getBlockNumber();
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) returns (bool success) {
if (!transfersEnabled) throw;
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
if (!transfersEnabled) throw;
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
if (parentSnapShotBlock >= getBlockNumber()) throw;
// Do not allow transfer to 0x0 or the token contract itself
if ((_to == 0) || (_to == address(this))) throw;
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, getBlockNumber());
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
if (!TokenController(controller).onTransfer(_from, _to, _amount))
throw;
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, getBlockNumber());
if (previousBalanceTo + _amount < previousBalanceTo) throw; // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) constant returns (uint256 balance) {
return balanceOfAt(_owner, getBlockNumber());
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) returns (bool success) {
if (!transfersEnabled) throw;
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_amount!=0) && (allowed[msg.sender][_spender] !=0)) throw;
// Alerts the token controller of the approve function call
if (isContract(controller)) {
if (!TokenController(controller).onApprove(msg.sender, _spender, _amount))
throw;
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) returns (bool success) {
if (!approve(_spender, _amount)) throw;
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() constant returns (uint) {
return totalSupplyAt(getBlockNumber());
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = getBlockNumber();
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) onlyController returns (bool) {
uint curTotalSupply = getValueAt(totalSupplyHistory, getBlockNumber());
if (curTotalSupply + _amount < curTotalSupply) throw; // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
var previousBalanceTo = balanceOf(_owner);
if (previousBalanceTo + _amount < previousBalanceTo) throw; // Check for overflow
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController returns (bool) {
uint curTotalSupply = getValueAt(totalSupplyHistory, getBlockNumber());
if (curTotalSupply < _amount) throw;
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
var previousBalanceFrom = balanceOf(_owner);
if (previousBalanceFrom < _amount) throw;
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < getBlockNumber())) {
Checkpoint newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(getBlockNumber());
newCheckPoint.value = uint128(_value);
} else {
Checkpoint oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () payable {
if (isContract(controller)) {
if (! TokenController(controller).proxyPayment.value(msg.value)(msg.sender))
throw;
} else {
throw;
}
}
//////////
// Testing specific methods
//////////
/// @notice This function is overridden by the test Mocks.
function getBlockNumber() internal constant returns (uint256) {
return block.number;
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
ERC20Token token = ERC20Token(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
/*
Copyright 2017, Jarrad Hope (Status Research & Development GmbH)
*/
contract SNT is MiniMeToken {
// @dev SNT constructor just parametrizes the MiniMeIrrevocableVestedToken constructor
function SNT(address _tokenFactory)
MiniMeToken(
_tokenFactory,
0x0, // no parent token
0, // no snapshot block number from parent
"Status Network Token", // Token name
18, // Decimals
"SNT", // Symbol
true // Enable transfers
) {}
}
/*
Copyright 2017, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title StatusContribution Contract
/// @author Jordi Baylina
/// @dev This contract will be the SNT controller during the contribution period.
/// This contract will determine the rules during this period.
/// Final users will generally not interact directly with this contract. ETH will
/// be sent to the SNT token contract. The ETH is sent to this contract and from here,
/// ETH is sent to the contribution walled and SNTs are mined according to the defined
/// rules.
contract StatusContribution is Owned, TokenController {
using SafeMath for uint256;
uint256 constant public failSafeLimit = 300000 ether;
uint256 constant public maxGuaranteedLimit = 30000 ether;
uint256 constant public exchangeRate = 10000;
uint256 constant public maxGasPrice = 50000000000;
uint256 constant public maxCallFrequency = 100;
MiniMeToken public SGT;
MiniMeToken public SNT;
uint256 public startBlock;
uint256 public endBlock;
address public destEthDevs;
address public destTokensDevs;
address public destTokensReserve;
uint256 public maxSGTSupply;
address public destTokensSgt;
DynamicCeiling public dynamicCeiling;
address public sntController;
mapping (address => uint256) public guaranteedBuyersLimit;
mapping (address => uint256) public guaranteedBuyersBought;
uint256 public totalGuaranteedCollected;
uint256 public totalNormalCollected;
uint256 public finalizedBlock;
uint256 public finalizedTime;
mapping (address => uint256) public lastCallBlock;
bool public paused;
modifier initialized() {
require(address(SNT) != 0x0);
_;
}
modifier contributionOpen() {
require(getBlockNumber() >= startBlock &&
getBlockNumber() <= endBlock &&
finalizedBlock == 0 &&
address(SNT) != 0x0);
_;
}
modifier notPaused() {
require(!paused);
_;
}
function StatusContribution() {
paused = false;
}
/// @notice This method should be called by the owner before the contribution
/// period starts This initializes most of the parameters
/// @param _snt Address of the SNT token contract
/// @param _sntController Token controller for the SNT that will be transferred after
/// the contribution finalizes.
/// @param _startBlock Block when the contribution period starts
/// @param _endBlock The last block that the contribution period is active
/// @param _dynamicCeiling Address of the contract that controls the ceiling
/// @param _destEthDevs Destination address where the contribution ether is sent
/// @param _destTokensReserve Address where the tokens for the reserve are sent
/// @param _destTokensSgt Address of the exchanger SGT-SNT where the SNT are sent
/// to be distributed to the SGT holders.
/// @param _destTokensDevs Address where the tokens for the dev are sent
/// @param _sgt Address of the SGT token contract
/// @param _maxSGTSupply Quantity of SGT tokens that would represent 10% of status.
function initialize(
address _snt,
address _sntController,
uint256 _startBlock,
uint256 _endBlock,
address _dynamicCeiling,
address _destEthDevs,
address _destTokensReserve,
address _destTokensSgt,
address _destTokensDevs,
address _sgt,
uint256 _maxSGTSupply
) public onlyOwner {
// Initialize only once
require(address(SNT) == 0x0);
SNT = MiniMeToken(_snt);
require(SNT.totalSupply() == 0);
require(SNT.controller() == address(this));
require(SNT.decimals() == 18); // Same amount of decimals as ETH
require(_sntController != 0x0);
sntController = _sntController;
require(_startBlock >= getBlockNumber());
require(_startBlock < _endBlock);
startBlock = _startBlock;
endBlock = _endBlock;
require(_dynamicCeiling != 0x0);
dynamicCeiling = DynamicCeiling(_dynamicCeiling);
require(_destEthDevs != 0x0);
destEthDevs = _destEthDevs;
require(_destTokensReserve != 0x0);
destTokensReserve = _destTokensReserve;
require(_destTokensSgt != 0x0);
destTokensSgt = _destTokensSgt;
require(_destTokensDevs != 0x0);
destTokensDevs = _destTokensDevs;
require(_sgt != 0x0);
SGT = MiniMeToken(_sgt);
require(_maxSGTSupply >= MiniMeToken(SGT).totalSupply());
maxSGTSupply = _maxSGTSupply;
}
/// @notice Sets the limit for a guaranteed address. All the guaranteed addresses
/// will be able to get SNTs during the contribution period with his own
/// specific limit.
/// This method should be called by the owner after the initialization
/// and before the contribution starts.
/// @param _th Guaranteed address
/// @param _limit Limit for the guaranteed address.
function setGuaranteedAddress(address _th, uint256 _limit) public initialized onlyOwner {
require(getBlockNumber() < startBlock);
require(_limit > 0 && _limit <= maxGuaranteedLimit);
guaranteedBuyersLimit[_th] = _limit;
GuaranteedAddress(_th, _limit);
}
/// @notice If anybody sends Ether directly to this contract, consider he is
/// getting SNTs.
function () public payable notPaused {
proxyPayment(msg.sender);
}
//////////
// MiniMe Controller functions
//////////
/// @notice This method will generally be called by the SNT token contract to
/// acquire SNTs. Or directly from third parties that want to acquire SNTs in
/// behalf of a token holder.
/// @param _th SNT holder where the SNTs will be minted.
function proxyPayment(address _th) public payable notPaused initialized contributionOpen returns (bool) {
require(_th != 0x0);
if (guaranteedBuyersLimit[_th] > 0) {
buyGuaranteed(_th);
} else {
buyNormal(_th);
}
return true;
}
function onTransfer(address, address, uint256) public returns (bool) {
return false;
}
function onApprove(address, address, uint256) public returns (bool) {
return false;
}
function buyNormal(address _th) internal {
require(tx.gasprice <= maxGasPrice);
// Antispam mechanism
address caller;
if (msg.sender == address(SNT)) {
caller = _th;
} else {
caller = msg.sender;
}
// Do not allow contracts to game the system
require(!isContract(caller));
require(getBlockNumber().sub(lastCallBlock[caller]) >= maxCallFrequency);
lastCallBlock[caller] = getBlockNumber();
uint256 toCollect = dynamicCeiling.toCollect(totalNormalCollected);
uint256 toFund;
if (msg.value <= toCollect) {
toFund = msg.value;
} else {
toFund = toCollect;
}
totalNormalCollected = totalNormalCollected.add(toFund);
doBuy(_th, toFund, false);
}
function buyGuaranteed(address _th) internal {
uint256 toCollect = guaranteedBuyersLimit[_th];
uint256 toFund;
if (guaranteedBuyersBought[_th].add(msg.value) > toCollect) {
toFund = toCollect.sub(guaranteedBuyersBought[_th]);
} else {
toFund = msg.value;
}
guaranteedBuyersBought[_th] = guaranteedBuyersBought[_th].add(toFund);
totalGuaranteedCollected = totalGuaranteedCollected.add(toFund);
doBuy(_th, toFund, true);
}
function doBuy(address _th, uint256 _toFund, bool _guaranteed) internal {
assert(msg.value >= _toFund); // Not needed, but double check.
assert(totalCollected() <= failSafeLimit);
if (_toFund > 0) {
uint256 tokensGenerated = _toFund.mul(exchangeRate);
assert(SNT.generateTokens(_th, tokensGenerated));
destEthDevs.transfer(_toFund);
NewSale(_th, _toFund, tokensGenerated, _guaranteed);
}
uint256 toReturn = msg.value.sub(_toFund);
if (toReturn > 0) {
// If the call comes from the Token controller,
// then we return it to the token Holder.
// Otherwise we return to the sender.
if (msg.sender == address(SNT)) {
_th.transfer(toReturn);
} else {
msg.sender.transfer(toReturn);
}
}
}
// NOTE on Percentage format
// Right now, Solidity does not support decimal numbers. (This will change very soon)
// So in this contract we use a representation of a percentage that consist in
// expressing the percentage in "x per 10**18"
// This format has a precision of 16 digits for a percent.
// Examples:
// 3% = 3*(10**16)
// 100% = 100*(10**16) = 10**18
//
// To get a percentage of a value we do it by first multiplying it by the percentage in (x per 10^18)
// and then divide it by 10**18
//
// Y * X(in x per 10**18)
// X% of Y = -------------------------
// 100(in x per 10**18)
//
/// @notice This method will can be called by the owner before the contribution period
/// end or by anybody after the `endBlock`. This method finalizes the contribution period
/// by creating the remaining tokens and transferring the controller to the configured
/// controller.
function finalize() public initialized {
require(getBlockNumber() >= startBlock);
require(msg.sender == owner || getBlockNumber() > endBlock);
require(finalizedBlock == 0);
// Do not allow termination until all curves revealed.
require(dynamicCeiling.allRevealed());
// Allow premature finalization if final limit is reached
if (getBlockNumber() <= endBlock) {
var (,lastLimit,,) = dynamicCeiling.curves(dynamicCeiling.revealedCurves().sub(1));
require(totalNormalCollected >= lastLimit);
}
finalizedBlock = getBlockNumber();
finalizedTime = now;
uint256 percentageToSgt;
if (SGT.totalSupply() >= maxSGTSupply) {
percentageToSgt = percent(10); // 10%
} else {
//
// SGT.totalSupply()
// percentageToSgt = 10% * -------------------
// maxSGTSupply
//
percentageToSgt = percent(10).mul(SGT.totalSupply()).div(maxSGTSupply);
}
uint256 percentageToDevs = percent(20); // 20%
//
// % To Contributors = 41% + (10% - % to SGT holders)
//
uint256 percentageToContributors = percent(41).add(percent(10).sub(percentageToSgt));
uint256 percentageToReserve = percent(29);
// SNT.totalSupply() -> Tokens minted during the contribution
// totalTokens -> Total tokens that should be after the allocation
// of devTokens, sgtTokens and reserve
// percentageToContributors -> Which percentage should go to the
// contribution participants
// (x per 10**18 format)
// percent(100) -> 100% in (x per 10**18 format)
//
// percentageToContributors
// SNT.totalSupply() = -------------------------- * totalTokens =>
// percent(100)
//
//
// percent(100)
// => totalTokens = ---------------------------- * SNT.totalSupply()
// percentageToContributors
//
uint256 totalTokens = SNT.totalSupply().mul(percent(100)).div(percentageToContributors);
// Generate tokens for SGT Holders.
//
// percentageToReserve
// reserveTokens = ----------------------- * totalTokens
// percentage(100)
//
assert(SNT.generateTokens(
destTokensReserve,
totalTokens.mul(percentageToReserve).div(percent(100))));
//
// percentageToSgt
// sgtTokens = ----------------------- * totalTokens
// percentage(100)
//
assert(SNT.generateTokens(
destTokensSgt,
totalTokens.mul(percentageToSgt).div(percent(100))));
//
// percentageToDevs
// devTokens = ----------------------- * totalTokens
// percentage(100)
//
assert(SNT.generateTokens(
destTokensDevs,
totalTokens.mul(percentageToDevs).div(percent(100))));
SNT.changeController(sntController);
Finalized();
}
function percent(uint256 p) internal returns (uint256) {
return p.mul(10**16);
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns (bool) {
if (_addr == 0) return false;
uint256 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
//////////
// Constant functions
//////////
/// @return Total tokens issued in weis.
function tokensIssued() public constant returns (uint256) {
return SNT.totalSupply();
}
/// @return Total Ether collected.
function totalCollected() public constant returns (uint256) {
return totalNormalCollected.add(totalGuaranteedCollected);
}
//////////
// Testing specific methods
//////////
/// @notice This function is overridden by the test Mocks.
function getBlockNumber() internal constant returns (uint256) {
return block.number;
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyOwner {
if (SNT.controller() == address(this)) {
SNT.claimTokens(_token);
}
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
ERC20Token token = ERC20Token(_token);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
/// @notice Pauses the contribution if there is any issue
function pauseContribution() onlyOwner {
paused = true;
}
/// @notice Resumes the contribution
function resumeContribution() onlyOwner {
paused = false;
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount);
event NewSale(address indexed _th, uint256 _amount, uint256 _tokens, bool _guaranteed);
event GuaranteedAddress(address indexed _th, uint256 _limit);
event Finalized();
}
/*
Copyright 2017, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title ContributionWallet Contract
/// @author Jordi Baylina
/// @dev This contract will be hold the Ether during the contribution period.
/// The idea of this contract is to avoid recycling Ether during the contribution
/// period. So all the ETH collected will be locked here until the contribution
/// period ends
// @dev Contract to hold sale raised funds during the sale period.
// Prevents attack in which the Aragon Multisig sends raised ether
// to the sale contract to mint tokens to itself, and getting the
// funds back immediately.
contract ContributionWallet {
// Public variables
address public multisig;
uint256 public endBlock;
StatusContribution public contribution;
// @dev Constructor initializes public variables
// @param _multisig The address of the multisig that will receive the funds
// @param _endBlock Block after which the multisig can request the funds
// @param _contribution Address of the StatusContribution contract
function ContributionWallet(address _multisig, uint256 _endBlock, address _contribution) {
require(_multisig != 0x0);
require(_contribution != 0x0);
require(_endBlock != 0 && _endBlock <= 4000000);
multisig = _multisig;
endBlock = _endBlock;
contribution = StatusContribution(_contribution);
}
// @dev Receive all sent funds without any further logic
function () public payable {}
// @dev Withdraw function sends all the funds to the wallet if conditions are correct
function withdraw() public {
require(msg.sender == multisig); // Only the multisig can request it
require(block.number > endBlock || // Allow after end block
contribution.finalizedBlock() != 0); // Allow when sale is finalized
multisig.transfer(this.balance);
}
}
/*
Copyright 2017, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title DevTokensHolder Contract
/// @author Jordi Baylina
/// @dev This contract will hold the tokens of the developers.
/// Tokens will not be able to be collected until 6 months after the contribution
/// period ends. And it will be increasing linearly until 2 years.
// collectable tokens
// | _/-------- vestedTokens rect
// | _/
// | _/
// | _/
// | _/
// | _/
// | _/
// | _/
// | |
// | . |
// | . |
// | . |
// +===+======+--------------+----------> time
// Contrib 6 Months 24 Months
// End
contract DevTokensHolder is Owned {
using SafeMath for uint256;
uint256 collectedTokens;
StatusContribution contribution;
MiniMeToken snt;
function DevTokensHolder(address _owner, address _contribution, address _snt) {
owner = _owner;
contribution = StatusContribution(_contribution);
snt = MiniMeToken(_snt);
}
/// @notice The Dev (Owner) will call this method to extract the tokens
function collectTokens() public onlyOwner {
uint256 balance = snt.balanceOf(address(this));
uint256 total = collectedTokens.add(balance);
uint256 finalizedTime = contribution.finalizedTime();
require(finalizedTime > 0 && getTime() > finalizedTime.add(months(6)));
uint256 canExtract = total.mul(getTime().sub(finalizedTime)).div(months(24));
canExtract = canExtract.sub(collectedTokens);
if (canExtract > balance) {
canExtract = balance;
}
collectedTokens = collectedTokens.add(canExtract);
assert(snt.transfer(owner, canExtract));
TokensWithdrawn(owner, canExtract);
}
function months(uint256 m) internal returns (uint256) {
return m.mul(30 days);
}
function getTime() internal returns (uint256) {
return now;
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyOwner {
require(_token != address(snt));
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
ERC20Token token = ERC20Token(_token);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount);
event TokensWithdrawn(address indexed _holder, uint256 _amount);
}
/*
Copyright 2017, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title SGTExchanger Contract
/// @author Jordi Baylina
/// @dev This contract will be used to distribute SNT between SGT holders.
/// SGT token is not transferable, and we just keep an accounting between all tokens
/// deposited and the tokens collected.
/// The controllerShip of SGT should be transferred to this contract before the
/// contribution period starts.
contract SGTExchanger is TokenController, Owned {
using SafeMath for uint256;
mapping (address => uint256) public collected;
uint256 public totalCollected;
MiniMeToken public sgt;
MiniMeToken public snt;
StatusContribution public statusContribution;
function SGTExchanger(address _sgt, address _snt, address _statusContribution) {
sgt = MiniMeToken(_sgt);
snt = MiniMeToken(_snt);
statusContribution = StatusContribution(_statusContribution);
}
/// @notice This method should be called by the SGT holders to collect their
/// corresponding SNTs
function collect() public {
uint256 finalizedBlock = statusContribution.finalizedBlock();
require(finalizedBlock != 0);
require(getBlockNumber() > finalizedBlock);
uint256 total = totalCollected.add(snt.balanceOf(address(this)));
uint256 balance = sgt.balanceOfAt(msg.sender, finalizedBlock);
// First calculate how much correspond to him
uint256 amount = total.mul(balance).div(sgt.totalSupplyAt(finalizedBlock));
// And then subtract the amount already collected
amount = amount.sub(collected[msg.sender]);
require(amount > 0); // Notify the user that there are no tokens to exchange
totalCollected = totalCollected.add(amount);
collected[msg.sender] = collected[msg.sender].add(amount);
assert(snt.transfer(msg.sender, amount));
TokensCollected(msg.sender, amount);
}
function proxyPayment(address) public payable returns (bool) {
throw;
}
function onTransfer(address, address, uint256) public returns (bool) {
return false;
}
function onApprove(address, address, uint256) public returns (bool) {
return false;
}
//////////
// Testing specific methods
//////////
/// @notice This function is overridden by the test Mocks.
function getBlockNumber() internal constant returns (uint256) {
return block.number;
}
//////////
// Safety Method
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyOwner {
require(_token != address(snt));
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
ERC20Token token = ERC20Token(_token);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount);
event TokensCollected(address indexed _holder, uint256 _amount);
}
/*
Copyright 2017, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title SNTPlaceholder Contract
/// @author Jordi Baylina
/// @dev The SNTPlaceholder contract will take control over the SNT after the contribution
/// is finalized and before the Status Network is deployed.
/// The contract allows for SNT transfers and transferFrom and implements the
/// logic for transferring control of the token to the network when the offering
/// asks it to do so.
contract SNTPlaceHolder is TokenController, Owned {
using SafeMath for uint256;
MiniMeToken public snt;
StatusContribution public contribution;
uint256 public activationTime;
address public sgtExchanger;
/// @notice Constructor
/// @param _owner Trusted owner for this contract.
/// @param _snt SNT token contract address
/// @param _contribution StatusContribution contract address
/// @param _sgtExchanger SGT-SNT Exchange address. (During the first week
/// only this exchanger will be able to move tokens)
function SNTPlaceHolder(address _owner, address _snt, address _contribution, address _sgtExchanger) {
owner = _owner;
snt = MiniMeToken(_snt);
contribution = StatusContribution(_contribution);
sgtExchanger = _sgtExchanger;
}
/// @notice The owner of this contract can change the controller of the SNT token
/// Please, be sure that the owner is a trusted agent or 0x0 address.
/// @param _newController The address of the new controller
function changeController(address _newController) public onlyOwner {
snt.changeController(_newController);
ControllerChanged(_newController);
}
//////////
// MiniMe Controller Interface functions
//////////
// In between the offering and the network. Default settings for allowing token transfers.
function proxyPayment(address) public payable returns (bool) {
return false;
}
function onTransfer(address _from, address, uint256) public returns (bool) {
return transferable(_from);
}
function onApprove(address _from, address, uint256) public returns (bool) {
return transferable(_from);
}
function transferable(address _from) internal returns (bool) {
// Allow the exchanger to work from the beginning
if (activationTime == 0) {
uint256 f = contribution.finalizedTime();
if (f > 0) {
activationTime = f.add(1 weeks);
} else {
return false;
}
}
return (getTime() > activationTime) || (_from == sgtExchanger);
}
//////////
// Testing specific methods
//////////
/// @notice This function is overrided by the test Mocks.
function getTime() internal returns (uint256) {
return now;
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyOwner {
if (snt.controller() == address(this)) {
snt.claimTokens(_token);
}
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
ERC20Token token = ERC20Token(_token);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount);
event ControllerChanged(address indexed _newController);
}
|
This method can be used by the controller to extract mistakenly sent tokens to this contract. _token The address of the token contract that you want to recover set to 0 in case you want to extract ether.
|
function claimTokens(address _token) public onlyOwner {
require(_token != address(snt));
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
ERC20Token token = ERC20Token(_token);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount);
event TokensCollected(address indexed _holder, uint256 _amount);
| 1,088,530 |
/*
/ | __ / ____|
/ | |__) | | |
/ / | _ / | |
/ ____ | | | |____
/_/ _ |_| _ _____|
* ARC: token/KYFToken.sol
*
* Latest source (may be newer): https://github.com/arcxgame/contracts/blob/master/contracts/token/KYFToken.sol
*
* Contract Dependencies: (none)
* Libraries: (none)
*
* MIT License
* ===========
*
* Copyright (c) 2020 ARC
*
* 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
*/
/* ===============================================
* Flattened with Solidifier by Coinage
*
* https://solidifier.coina.ge
* ===============================================
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.16;
interface IKYFV2 {
function checkVerified(
address _user
)
external
view
returns (bool);
}
// SPDX-License-Identifier: MIT
contract KYFToken {
/* ========== Variables ========== */
address public owner;
mapping (address => bool) public kyfInstances;
address[] public kyfInstancesArray;
/* ========== Events ========== */
event KyfStatusUpdated(address _address, bool _status);
/* ========== Modifier ========== */
modifier onlyOwner() {
require(
msg.sender == owner,
"Can only be called by owner"
);
_;
}
/* ========== View Functions ========== */
function isVerified(
address _user
)
public
view
returns (bool)
{
for (uint256 i = 0; i < kyfInstancesArray.length; i++) {
IKYFV2 kyfContract = IKYFV2(kyfInstancesArray[i]);
if (kyfContract.checkVerified(_user) == true) {
return true;
}
}
return false;
}
/* ========== Owner Functions ========== */
function transferOwnership(
address _owner
)
public
onlyOwner
{
owner = _owner;
}
function setApprovedKYFInstance(
address _kyfContract,
bool _status
)
public
onlyOwner
{
if (_status == true) {
kyfInstancesArray.push(_kyfContract);
kyfInstances[_kyfContract] = true;
emit KyfStatusUpdated(_kyfContract, true);
return;
}
// Remove the kyfContract from the kyfInstancesArray array.
for (uint i = 0; i < kyfInstancesArray.length; i++) {
if (address(kyfInstancesArray[i]) == _kyfContract) {
delete kyfInstancesArray[i];
kyfInstancesArray[i] = kyfInstancesArray[kyfInstancesArray.length - 1];
// Decrease the size of the array by one.
kyfInstancesArray.length--;
break;
}
}
// And remove it from the synths mapping
delete kyfInstances[_kyfContract];
emit KyfStatusUpdated(_kyfContract, false);
}
/* ========== ERC20 Functions ========== */
/**
* @dev Returns the name of the token.
*/
function name()
public
view
returns (string memory)
{
return "ARC KYF Token";
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol()
public
view
returns (string memory)
{
return "ARCKYF";
}
/**
* @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 0;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply()
public
view
returns (uint256)
{
return kyfInstancesArray.length;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(
address account
)
public
view
returns (uint256)
{
if (isVerified(account)) {
return 1;
}
return 0;
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(
address spender,
uint256 amount
)
public
returns (bool)
{
return false;
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(
address recipient,
uint256 amount
)
public
returns (bool)
{
return false;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return 0;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
)
public
returns (bool)
{
return false;
}
}
|
See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./
|
function transfer(
address recipient,
uint256 amount
)
public
returns (bool)
{
return false;
}
| 5,722,046 |
./partial_match/4/0x3c3d4e051D347f1dfDebe1F235754b6e12E01ecf/sources/InstantSwap.sol
|
Internal function of swap/
|
function _swapOut(address assetAdd, uint256 asset)
internal {
uint256 value = toToken(assetAdd, asset);
require(IERC20(assetAdd).balanceOf(msg.sender) >= asset,
"Insufficient asset Balance");
uint256 fee = value.mul(swapFee).div(100);
poolFee = poolFee.add(fee);
require(IERC20(USDC).balanceOf(address(this)) >= value,
"Insufficient token balance");
_claim(assetAdd, asset, value.sub(fee));
}
| 8,620,917 |
./full_match/42/0xd7F5cE8Eebe3a6Cc05DF785bd283a094640Bb76A/sources/BlockchainForestDefi.sol
|
Local variablespour testActionspour test
|
function swapHalfDaiToUsdc(uint _amount) public onlyOwner {
uint amountTemp = _amount.mul(1e18);
IUniswapV2Router02 UniswapRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address[] memory path = new address[](2);
path[0] = daiTokenAddress;
path[1] = usdtTokenAddress;
IERC20 daiInstance = IERC20(daiTokenAddress);
daiInstance.approve(address(UniswapRouter), amountTemp);
UniswapRouter.swapExactTokensForTokens(amountTemp, 1, path, address(this), now + 120 );
}
| 16,217,092 |
pragma solidity ^0.4.26;
import "../bancorContracts/solidity/contracts/token/interfaces/IERC20Token.sol";
import "../bancorContracts/solidity/contracts/converter/BancorConverter.sol";
import "./interfaces/ICToken.sol";
contract BCConverter is BancorConverter {
uint constant MAX_UINT = 2**256 - 1;
mapping(address => ICToken) public uTokens2cTokens;
mapping(address => IERC20Token) public cTokens2uTokens;
constructor(
ISmartToken _token,
IContractRegistry _registry,
uint32 _maxConversionFee,
IERC20Token _reserveToken,
uint32 _reserveRatio
)
BancorConverter(
_token,
_registry,
_maxConversionFee,
_reserveToken,
_reserveRatio
)
public
{
}
// Overloading the addReseve function to add the compound token for a given underlying token
/**
* @dev all compound tokens going to be listed should be passed through this function with their underlying token.
*
* @param _uToken undelying token used by compound cToken
* @param _cToken compound token contract address of the underlying token
* @param _ratio constant reserve ratio, represented in ppm, 1-1000000
*
*/
function addReserve(IERC20Token _uToken ,IERC20Token _cToken, uint32 _ratio)
public
ownerOnly
inactive
validAddress(_cToken)
notThis(_cToken)
validReserveRatio(_ratio)
{
addReserve(_cToken,_ratio);
// adding uToken to reserve without adding its ratio to the total ratio amount
// since both tokens are represented by the same asset at any time
// allowing both tokens to be swapped
ICToken cToken = ICToken(_cToken);
IERC20Token uToken = IERC20Token(cToken.underlying());
require(uToken == _uToken);
cTokens2uTokens[cToken] = uToken;
uTokens2cTokens[uToken] = cToken;
require(address(uToken) != address(token) && !reserves[uToken].isSet); // validate input
reserves[uToken].ratio = _ratio;
reserves[uToken].isVirtualBalanceEnabled = false;
reserves[uToken].virtualBalance = 0;
reserves[uToken].isSaleEnabled = true;
reserves[uToken].isSet = true;
uToken.approve(address(cToken),MAX_UINT);
}
/**
* @dev This function approves the underlying token used as reserve to be spent by the compound tokens contracts
* it is most likely to not be called, since apporval of the underlying token is set max_uint for the compound token
* it is just a safety measure.
*
*/
function approveTokensToCompound() public {
for (uint16 i = 0; i < reserveTokens.length; i++) {
IERC20Token reserveToken = reserveTokens[i];
IERC20Token uToken = cTokens2uTokens[reserveToken];
if(address(uToken) != address(0x0)) uToken.approve(reserveToken,MAX_UINT);
}
}
/**
* @dev This function aims to automate the minting of coumpound tokens when adding its underlying tokens to the reserve
* It allow also the deposit of any reserve token, user should first approve the ERC20 transer.
*
* @param _reserveToken token address
* @param _amount token amount to be deposited
*
*/
function addReserveBalance(IERC20Token _reserveToken, uint _amount)
public
ownerOnly
validReserve(_reserveToken)
inactive
{
ensureTransferFrom(_reserveToken, msg.sender, this, _amount);
}
/**
* @dev returns the converted value of an underlying amount in compound to compound tokens value
*
* @param _uToken underlying token address used as asset in compound token contract
* @param _cToken compound token contract address of the underlying token
* @param _uAmount underlying amount to convert
*
* @return converted underlying amount
*/
function uAmount2cAmount(IERC20Token _uToken, ICToken _cToken, uint _uAmount) public view returns(uint) {
return _uAmount.mul(10**uint(_uToken.decimals())).div(_cToken.exchangeRateCurrent());
}
/**
* @dev returns the converted value of a compound token to its underlying token value
*
* @param _cToken compound token contract address of the underlying token
* @param _uToken underlying token address used as asset in compound token contract
* @param _cAmount compound token amount to convert
*
* @return converted compound token amount
*/
function cAmount2uAmount(ICToken _cToken, IERC20Token _uToken, uint _cAmount) public view returns(uint) {
return _cAmount.mul(_cToken.exchangeRateCurrent()).div(10**uint(_uToken.decimals()));
}
/**
* @dev returns the reserve's balance following the token address, if the token is an underlying token
* is hold by compound ctoken contract.
* note that prior to version 17, you should use 'getConnectorBalance' instead
*
* @param _reserveToken reserve token contract address
*
* @return reserve balance
*/
function getReserveBalance(IERC20Token _reserveToken)
public
view
validReserve(_reserveToken)
returns (uint256)
{
ICToken cToken = uTokens2cTokens[_reserveToken];
if (address(cToken) == address(0x0)) {
return _reserveToken.balanceOf(this);
}
else {
return cToken.balanceOfUnderlying(this);
}
}
// ensureTransferFrom was modified to mint or redeem compound tokens balance in some specific cases:
// - If _token is an underlying token, with its compound token set in uTokens2cTokens mapping:
// - When transfering it outside of the contract, the needed value should be first redeemed then transfered.
// - Following bancor flow, if someone calls any conversion functions implemented in this contract the tokens should
// be transfered to BancorNetwork without no minting or redeem.
// - When the underlying tokens are deposited to the contract, that same balance is converted to compound through "mint"
// - If _token is not an underlying token but its compound token or another token listed in the reserve the reimplemented
// function will behave the same as the implemented function in the inherited contract.
// The function was changed to return a value that is being transfered due to "Truncation-Related Issues" as mentioned in
// https://blog.openzeppelin.com/compound-audit/, a truncation always happens when minting/redeeming tokens due to compound
// implementation, meaning that if you mint x amount and redeem the total amount in the same transaction the value returned
// is slightly lower than the initial amount used to mint cTokens. This issue is making the amount return by compound when
// redeeming tokens not predictable (by a very small value)
function ensureTransferFrom(IERC20Token _token, address _from, address _to, uint256 _amount) private {
// We must assume that functions `transfer` and `transferFrom` do not return anything,
// because not all tokens abide the requirement of the ERC20 standard to return success or failure.
// This is because in the current compiler version, the calling contract can handle more returned data than expected but not less.
// This may change in the future, so that the calling contract will revert if the size of the data is not exactly what it expects.
uint prevBalance = _token.balanceOf(_to);
uint nextBalance;
ICToken cToken = uTokens2cTokens[_token];
if(cToken==address(0))
{
if (_from == address(this)) INonStandardERC20(_token).transfer(_to, _amount);
else INonStandardERC20(_token).transferFrom(_from, _to, _amount);
nextBalance = _token.balanceOf(_to);
}
else
{
if (_from == address(this))
{
require(cToken.redeemUnderlying(_amount)==0,"compound redeem error");
INonStandardERC20(_token).transfer(_to,_amount);
nextBalance = _token.balanceOf(_to);
}
else
{
INonStandardERC20(_token).transferFrom(_from, _to, _amount);
nextBalance = _token.balanceOf(_to);
if(_to == address(this)) require(cToken.mint(_amount)==0,"compound mint error");
}
}
require(nextBalance.sub(prevBalance)>0,"transfe error");
}
// Disable upgrade since this converter contract is different than normal bancorConverter
// to enable it bancor upgrader contract has to take this logic into account, please note
// that this procedure was done to avoid any possible issue with the asset held by the contract.
function upgrade() public ownerOnly {
}
// Funding will accept underlying tokens or their corresponding compound tokens plus any other token listed as a reserve
function fund(uint256 _amount)
public
multipleReservesOnly
{
uint256 supply = token.totalSupply();
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
// iterate through the reserve tokens and transfer a percentage equal to the ratio between _amount
// and the total supply in each reserve from the caller to the converter
for (uint16 i = 0; i < reserveTokens.length; i++) {
IERC20Token reserveToken;
uint256 reserveBalance;
uint256 reserveAmount;
reserveToken = reserveTokens[i];
// ---------------------------------------------------------------------//
// changed reserveToken.balanceOf(this) to getReserveBalance(reserveToken)
// ---------------------------------------------------------------------//
reserveBalance = getReserveBalance(reserveToken);
reserveAmount = formula.calculateFundCost(supply, reserveBalance, totalReserveRatio, _amount);
// ---------------------------------------------------------------------//
// first check of the user approve enough compound tokens to the contract
// if not we switch to the underlying token since a user can aprove either
// ones-----------------------------------------------------------------//
// ---------------------------------------------------------------------//
IERC20Token uToken = cTokens2uTokens[reserveToken];
if( uToken != address(0) )
{
if( reserveToken.allowance(msg.sender,this) < reserveAmount || reserveToken.balanceOf(msg.sender) < reserveAmount) {
reserveToken = uToken;
reserveBalance = getReserveBalance(reserveToken);
reserveAmount = formula.calculateFundCost(supply, reserveBalance, totalReserveRatio, _amount);
}
}
Reserve storage reserve = reserves[reserveToken];
// transfer funds from the caller in the reserve token
ensureTransferFrom(reserveToken, msg.sender, this, reserveAmount);
// dispatch price data update for the smart token/reserve
emit PriceDataUpdate(reserveToken, supply + _amount, reserveBalance +reserveAmount, reserve.ratio);
}
// issue new funds to the caller in the smart token
token.issue(msg.sender, _amount);
}
// Liquidate will only return underlying tokens, in the opposite of funding function that accepts both underlying and
// compound tokens
function liquidate(uint256 _amount)
public
multipleReservesOnly
{
uint256 supply = token.totalSupply();
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
// destroy _amount from the caller's balance in the smart token
token.destroy(msg.sender, _amount);
// iterate through the reserve tokens and send a percentage equal to the ratio between _amount
// and the total supply from each reserve balance to the caller
IERC20Token reserveToken;
uint256 reserveBalance;
uint256 reserveAmount;
for (uint16 i = 0; i < reserveTokens.length; i++) {
reserveToken = reserveTokens[i];
// ---------------------------------------------------------------------//
// if the reserve token is cToken switch it to its corresponding underlying
// ---------------------------------------------------------------------//
IERC20Token uToken = cTokens2uTokens[reserveToken];
if(uToken != address(0)) reserveToken = uToken;
// ---------------------------------------------------------------------//
// changed reserveToken.balanceOf(this) to getReserveBalance(reserveToken)
// ---------------------------------------------------------------------//
reserveBalance = getReserveBalance(reserveToken);
reserveAmount = formula.calculateLiquidateReturn(supply, reserveBalance, totalReserveRatio, _amount);
Reserve storage reserve = reserves[reserveToken];
// transfer funds to the caller in the reserve token
ensureTransferFrom(reserveToken, this, msg.sender, reserveAmount);
// dispatch price data update for the smart token/reserve
emit PriceDataUpdate(reserveToken, supply - _amount, reserveBalance - reserveAmount, reserve.ratio);
}
}
// ----------------------------------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------------------------------- //
// Minimal changes have been done to the functions below, mainly the XXXX.balanceOf(this) was replaced with ------- //
// getReserveBalance(XXXX) since the underlying balance has to be converted from the compound balance--------------- //
// The changes can be submited as PR on the main repo BancorConverter without risk since this contract-------------- //
// ----------------------------------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------------------------------------- //
function convertInternal(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn)
public
only(BANCOR_NETWORK)
greaterThanZero(_minReturn)
returns (uint256)
{
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its reserves
if (_toToken == token)
return buy(_fromToken, _amount, _minReturn);
else if (_fromToken == token)
return sell(_toToken, _amount, _minReturn);
uint256 amount;
uint256 feeAmount;
// conversion between 2 reserves
(amount, feeAmount) = getCrossReserveReturn(_fromToken, _toToken, _amount);
// ensure the trade gives something in return and meets the minimum requested amount
require(amount != 0 && amount >= _minReturn);
Reserve storage fromReserve = reserves[_fromToken];
Reserve storage toReserve = reserves[_toToken];
// ensure that the trade won't deplete the reserve balance
// ---------------------------------------------------------------------//
// changed _toToken.balanceOf(this) to getReserveBalance(_toToken)
// ---------------------------------------------------------------------//
uint256 toReserveBalance = getReserveBalance(_toToken);
assert(amount < toReserveBalance);
// transfer funds from the caller in the from reserve token
ensureTransferFrom(_fromToken, msg.sender, this, _amount);
// transfer funds to the caller in the to reserve token
ensureTransferFrom(_toToken, this, msg.sender, amount);
// dispatch the conversion event
// the fee is higher (magnitude = 2) since cross reserve conversion equals 2 conversions (from / to the smart token)
dispatchConversionEvent(_fromToken, _toToken, _amount, amount, feeAmount);
// dispatch price data updates for the smart token / both reserves
// ---------------------------------------------------------------------//
// changed _fromToken.balanceOf(this) to getReserveBalance(_fromToken)
// ---------------------------------------------------------------------//
emit PriceDataUpdate(_fromToken, token.totalSupply(), getReserveBalance(_fromToken), fromReserve.ratio);
// ---------------------------------------------------------------------//
// changed _toToken.balanceOf(this) to getReserveBalance(_toToken)
// ---------------------------------------------------------------------//
emit PriceDataUpdate(_toToken, token.totalSupply(), getReserveBalance(_toToken), toReserve.ratio);
return amount;
}
function buy(IERC20Token _reserveToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) {
uint256 amount;
uint256 feeAmount;
(amount, feeAmount) = getPurchaseReturn(_reserveToken, _depositAmount);
// ensure the trade gives something in return and meets the minimum requested amount
require(amount != 0 && amount >= _minReturn);
Reserve storage reserve = reserves[_reserveToken];
// transfer funds from the caller in the reserve token
ensureTransferFrom(_reserveToken, msg.sender, this, _depositAmount);
// issue new funds to the caller in the smart token
token.issue(msg.sender, amount);
// dispatch the conversion event
dispatchConversionEvent(_reserveToken, token, _depositAmount, amount, feeAmount);
// dispatch price data update for the smart token/reserve
// -----------------------------------------------------------------------//
// changed _reserveToken.balanceOf(this) to getReserveBalance(_reserveToken)
// -----------------------------------------------------------------------//
emit PriceDataUpdate(_reserveToken, token.totalSupply(), getReserveBalance(_reserveToken), reserve.ratio);
return amount;
}
function sell(IERC20Token _reserveToken, uint256 _sellAmount, uint256 _minReturn) internal returns (uint256) {
require(_sellAmount <= token.balanceOf(msg.sender)); // validate input
uint256 amount;
uint256 feeAmount;
(amount, feeAmount) = getSaleReturn(_reserveToken, _sellAmount);
// ensure the trade gives something in return and meets the minimum requested amount
require(amount != 0 && amount >= _minReturn);
// ensure that the trade will only deplete the reserve balance if the total supply is depleted as well
uint256 tokenSupply = token.totalSupply();
// ---------------------------------------------------------------------//
// changed reserveToken.balanceOf(this) to getReserveBalance(reserveToken)
// ---------------------------------------------------------------------//
uint256 reserveBalance = getReserveBalance(_reserveToken);
assert(amount < reserveBalance || (amount == reserveBalance && _sellAmount == tokenSupply));
Reserve storage reserve = reserves[_reserveToken];
// destroy _sellAmount from the caller's balance in the smart token
token.destroy(msg.sender, _sellAmount);
// transfer funds to the caller in the reserve token
ensureTransferFrom(_reserveToken, this, msg.sender, amount);
// dispatch the conversion event
dispatchConversionEvent(token, _reserveToken, _sellAmount, amount, feeAmount);
// dispatch price data update for the smart token/reserve
// -----------------------------------------------------------------------//
// changed _reserveToken.balanceOf(this) to getReserveBalance(_reserveToken)
// -----------------------------------------------------------------------//
emit PriceDataUpdate(_reserveToken, token.totalSupply(), getReserveBalance(_reserveToken), reserve.ratio);
return amount;
}
function getPurchaseReturn(IERC20Token _reserveToken, uint256 _depositAmount)
public
view
active
validReserve(_reserveToken)
returns (uint256, uint256)
{
Reserve storage reserve = reserves[_reserveToken];
uint256 tokenSupply = token.totalSupply();
// ---------------------------------------------------------------------//
// changed _reserveToken.balanceOf(this) to getReserveBalance(_reserveToken)
// ---------------------------------------------------------------------//
uint256 reserveBalance = getReserveBalance(_reserveToken);
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
uint256 amount = formula.calculatePurchaseReturn(tokenSupply, reserveBalance, reserve.ratio, _depositAmount);
uint256 finalAmount = getFinalAmount(amount, 1);
// return the amount minus the conversion fee and the conversion fee
return (finalAmount, amount - finalAmount);
}
function getSaleReturn(IERC20Token _reserveToken, uint256 _sellAmount)
public
view
active
validReserve(_reserveToken)
returns (uint256, uint256)
{
Reserve storage reserve = reserves[_reserveToken];
uint256 tokenSupply = token.totalSupply();
// -----------------------------------------------------------------------//
// changed _reserveToken.balanceOf(this) to getReserveBalance(_reserveToken)
// -----------------------------------------------------------------------//
uint256 reserveBalance = getReserveBalance(_reserveToken);
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
uint256 amount = formula.calculateSaleReturn(tokenSupply, reserveBalance, reserve.ratio, _sellAmount);
uint256 finalAmount = getFinalAmount(amount, 1);
// return the amount minus the conversion fee and the conversion fee
return (finalAmount, amount - finalAmount);
}
//---------------------------------------------------------------------------------------------------------------//
// no changes were applied to dispatchConversionEvent , it was ported here because it was marked as private, meaning
// that it cannot be inherited ----------------------------------------------------------------------------------//
//---------------------------------------------------------------------------------------------------------------//
function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private {
// fee amount is converted to 255 bits -
// negative amount means the fee is taken from the source token, positive amount means its taken from the target token
// currently the fee is always taken from the target token
// since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow
assert(_feeAmount < 2 ** 255);
emit Conversion(_fromToken, _toToken, msg.sender, _amount, _returnAmount, int256(_feeAmount));
}
function getCrossReserveReturn(IERC20Token _fromReserveToken, IERC20Token _toReserveToken, uint256 _amount)
public
view
active
validReserve(_fromReserveToken)
validReserve(_toReserveToken)
returns (uint256, uint256)
{
Reserve storage fromReserve = reserves[_fromReserveToken];
Reserve storage toReserve = reserves[_toReserveToken];
// ---------------------------------------------------------------------//
// changed reserveToken.balanceOf(this) to getReserveBalance(xxxxxxxxx)
// ---------------------------------------------------------------------//
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
uint256 amount = formula.calculateCrossReserveReturn(
getReserveBalance(_fromReserveToken),
fromReserve.ratio,
getReserveBalance(_toReserveToken),
toReserve.ratio,
_amount);
uint256 finalAmount = getFinalAmount(amount, 2);
// return the amount minus the conversion fee and the conversion fee
// the fee is higher (magnitude = 2) since cross reserve conversion equals 2 conversions (from / to the smart token)
return (finalAmount, amount - finalAmount);
}
function quickConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee)
public
payable
returns (uint256)
{
IBancorNetwork bancorNetwork = IBancorNetwork(addressOf(BANCOR_NETWORK));
// we need to transfer the source tokens from the caller to the BancorNetwork contract,
// so it can execute the conversion on behalf of the caller
if (msg.value == 0) {
// not ETH, send the source tokens to the BancorNetwork contract
// if the token is the smart token, no allowance is required - destroy the tokens
// from the caller and issue them to the BancorNetwork contract
if (_path[0] == token) {
token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token
token.issue(bancorNetwork, _amount); // issue _amount new tokens to the BancorNetwork contract
} else {
// otherwise, we assume we already have allowance, transfer the tokens directly to the BancorNetwork contract
ensureTransferFrom(_path[0], msg.sender, bancorNetwork, _amount);
}
}
// execute the conversion and pass on the ETH with the call
return bancorNetwork.convertFor2.value(msg.value)(_path, _amount, _minReturn, msg.sender, _affiliateAccount, _affiliateFee);
}
/**
* @dev calculates the expected return of converting a given amount of tokens
*
* @param _fromToken contract address of the token to convert from
* @param _toToken contract address of the token to convert to
* @param _amount amount of tokens received from the user
*
* @return amount of tokens that the user will receive
* @return amount of tokens that the user will pay as fee
*/
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256, uint256) {
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its reserves
if (_toToken == token)
return getPurchaseReturn(_fromToken, _amount);
else if (_fromToken == token)
return getSaleReturn(_toToken, _amount);
// conversion between 2 reserves
return getCrossReserveReturn(_fromToken, _toToken, _amount);
}
/**
* @dev converts a specific amount of _fromToken to _toToken
* note that prior to version 16, you should use 'convert' instead
*
* @param _fromToken ERC20 token to convert from
* @param _toToken ERC20 token to convert to
* @param _amount amount to convert, in fromToken
* @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
* @param _affiliateAccount affiliate account
* @param _affiliateFee affiliate fee in PPM
*
* @return conversion return amount
*/
function convert2(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256) {
IERC20Token[] memory path = new IERC20Token[](3);
(path[0], path[1], path[2]) = (_fromToken, token, _toToken);
return quickConvert2(path, _amount, _minReturn, _affiliateAccount, _affiliateFee);
}
/**
* @dev deprecated, backward compatibility
*/
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
return convertInternal(_fromToken, _toToken, _amount, _minReturn);
}
/**
* @dev deprecated, backward compatibility
*/
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
return convert2(_fromToken, _toToken, _amount, _minReturn, address(0), 0);
}
/**
* @dev deprecated, backward compatibility
*/
function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256) {
return quickConvert2(_path, _amount, _minReturn, address(0), 0);
}
/**
* @dev deprecated, backward compatibility
*/
function quickConvertPrioritized2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256[] memory, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256) {
return quickConvert2(_path, _amount, _minReturn, _affiliateAccount, _affiliateFee);
}
/**
* @dev deprecated, backward compatibility
*/
function quickConvertPrioritized(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256, uint8, bytes32, bytes32) public payable returns (uint256) {
return quickConvert2(_path, _amount, _minReturn, address(0), 0);
}
/**
* @dev deprecated, backward compatibility
*/
function completeXConversion(IERC20Token[] _path, uint256 _minReturn, uint256 _conversionId, uint256, uint8, bytes32, bytes32) public returns (uint256) {
return completeXConversion2(_path, _minReturn, _conversionId);
}
/**
* @dev deprecated, backward compatibility
*/
function connectors(address _address) public view returns (uint256, uint32, bool, bool, bool) {
Reserve storage reserve = reserves[_address];
return(reserve.virtualBalance, reserve.ratio, reserve.isVirtualBalanceEnabled, reserve.isSaleEnabled, reserve.isSet);
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokens(uint256 _index) public view returns (IERC20Token) {
return BancorConverter.reserveTokens[_index];
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokenCount() public view returns (uint16) {
return reserveTokenCount();
}
/**
* @dev deprecated, backward compatibility
*/
function addConnector(IERC20Token _token, uint32 _weight, bool /*_enableVirtualBalance*/) public {
addReserve(_token, _weight);
}
/**
* @dev deprecated, backward compatibility
*/
function updateConnector(IERC20Token _connectorToken, uint32 /*_weight*/, bool /*_enableVirtualBalance*/, uint256 _virtualBalance) public {
updateReserveVirtualBalance(_connectorToken, _virtualBalance);
}
/**
* @dev deprecated, backward compatibility
*/
function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256) {
return getReserveBalance(_connectorToken);
}
/**
* @dev deprecated, backward compatibility
*/
function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _amount) public view returns (uint256, uint256) {
return getCrossReserveReturn(_fromConnectorToken, _toConnectorToken, _amount);
}
}
|
destroy _amount from the caller's balance in the smart token iterate through the reserve tokens and send a percentage equal to the ratio between _amount and the total supply from each reserve balance to the caller --------------------------------------------------------------------- if the reserve token is cToken switch it to its corresponding underlying --------------------------------------------------------------------- --------------------------------------------------------------------- changed reserveToken.balanceOf(this) to getReserveBalance(reserveToken) --------------------------------------------------------------------- transfer funds to the caller in the reserve token dispatch price data update for the smart token/reserve
|
function liquidate(uint256 _amount)
public
multipleReservesOnly
{
uint256 supply = token.totalSupply();
IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA));
token.destroy(msg.sender, _amount);
IERC20Token reserveToken;
uint256 reserveBalance;
uint256 reserveAmount;
for (uint16 i = 0; i < reserveTokens.length; i++) {
reserveToken = reserveTokens[i];
IERC20Token uToken = cTokens2uTokens[reserveToken];
if(uToken != address(0)) reserveToken = uToken;
reserveBalance = getReserveBalance(reserveToken);
reserveAmount = formula.calculateLiquidateReturn(supply, reserveBalance, totalReserveRatio, _amount);
Reserve storage reserve = reserves[reserveToken];
ensureTransferFrom(reserveToken, this, msg.sender, reserveAmount);
emit PriceDataUpdate(reserveToken, supply - _amount, reserveBalance - reserveAmount, reserve.ratio);
}
}
| 15,804,674 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// @title: OnChainBots
// @author: theaibutcher
//
// On chain PFP collection of 10k unique profile images with the following properties:
// - a single Ethereum transaction created everything
// - all metadata on chain
// - all images on chain in svg format
// - all created in the constraints of a single txn without need of any other txns to load additional data
// - no use of other deployed contracts
// - all 10,000 OnChain Bots are unique
// - there are 6 traits with 171 values (including 3 traits of no scars, no buttons, and no earring)
// - the traits have distribution and rarities interesting for collecting
// - everything on chain can be used in other apps and collections in the future
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
/**
* @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);
}
/**
* @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;
}
/**
* @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);
}
}
/*
* @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;
}
}
/**
* @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);
}
}
/**
* @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;
}
}
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
/**
* @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(to).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 {}
}
/**
* @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);
}
/**
* @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();
}
}
// Bring on the OnChain Bots!
contract OnChainBots is ERC721Enumerable, ReentrancyGuard, Ownable {
using Strings for uint256;
uint256 public constant maxSupply = 10000;
uint256 public numClaimed = 0;
string[] private background = ["FFF","dda","e92","3DF","FEF","9de","367","ccc"]; // only trait that is uniform, no need for rarity weights
string[] private fur1 = ["fd1","28F","324","3D4","ffc","81F","f89","F6F","049","901","fc5","ffe","574","bcc","d04","AAA","AB3","ff0","fd1"];
string[] private fur2 = ["259","000","000","000","000","000","000","000","000","000","060","000","96e","56e","799","801","310","d9f","000"];
uint8[] private fur_w =[249, 246, 223, 141, 116, 114, 93, 90, 89, 86, 74, 72, 55, 48, 39, 32, 28, 14, 8];
string[] private eyes = ["abe","080","653","000","be7","abe","080","653","000","be7","cef","abe","080","653","000","be7","cef","abe","080","653","000","be7","cef"];
uint8[] private eyes_w = [245, 121, 107, 101, 79, 78, 70, 68, 62, 58, 56, 51, 50, 48, 44, 38, 35, 33, 31, 22, 15, 10, 7];
string[] private earring = ["999","fe7","999","999","fe7","bdd"];
uint8[] private earring_w = [251, 32, 29, 17, 16, 8, 5];
string[] private buttons1 = ["f00","f00","222","f00","f00","f00","f00","f00","f00","00f","00f","00f","00f","00f","00f","00f","222","00f","f0f","222","f0f","f0f","f0f","f0f","f0f","f0f","f0f","f80","f80","f80","f80","f80","f00","f80","f80","f80","90f","90f","00f","90f","90f","90f","222"];
string[] private buttons2 = ["d00","00f","f00","f0f","f80","90f","f48","0f0","ff0","f00","00d","f0f","f80","90f","f48","0f0","ddd","ff0","f00","653","00f","d0d","f80","90f","f48","0f0","ff0","f00","f0f","00f","d60","f48","ddd","90f","0f0","ff0","f00","00f","fd1","f0f","f80","70d","fd1"];
uint8[] private buttons_w = [251, 55, 45, 43, 38, 37, 34, 33, 32, 31, 31, 31, 31, 31, 30, 30, 29, 29, 28, 27, 27, 27, 26, 25, 24, 22, 21, 20, 19, 19, 19, 19, 19, 19, 18, 17, 16, 15, 14, 13, 11, 9, 8, 6];
string[] private scar1 = ["f00","f00","f00","f00","f00","f00","f00","000","000","000","000","000","000","000","f00","080","080","080","080","080","080","080","808","808","808","808","808","808","f00","808","90f","f48","22d","90f","90f","ff0",""];
string[] private scar2 = ["0f0","000","080","ff0","90f","080","f48","f00","0f0","000","080","ff0","90f","080","000","f00","0f0","000","080","ff0","90f","080","f00","0f0","000","080","ff0","90f","f00","080","f00","000","000","0f0","000","f48",""];
uint8[] private scar_w = [251, 64, 47, 42, 39, 38, 36, 35, 34, 34, 33, 29, 28, 26, 26, 25, 25, 25, 22, 21, 20, 20, 18, 17, 17, 15, 14, 14, 13, 13, 12, 12, 12, 10, 9, 8, 7];
string[] private z = ['<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 500 500"><rect x="0" y="0" width="500" height="500" style="fill:#',
'"/><polygon points="93 214, 13 393, 87 413, 165 220, 145 213, 93 214" style="fill:#', '"/><polygon points = "268 416, 270 489, 333 489, 339 416, 268 416" style="fill:#', '"/><polygon points= "177 416, 178 488, 243 489, 243 416, 177 416" style="fill:#',
'"/><polygon points="176 368, 178 415, 268 416, 339 416, 345 368, 176 368" style="fill:#', '"/><polygon points =" 350 209, 433 399, 489 384, 399 207" style="fill:#', '"/><polygon points ="160 213, 171 367, 348 367, 343 209, 160 213" style="fill:#',
'"/><polygon points="40 22, 56 209, 455 201, 452 10, 40 22 " style="fill:#', '"/><polygon points="252 142,223 162,284 161,252 142" style="fill:#', '"/><circle cx="174" cy="93" r="15" style="fill:#',
'"/><circle cx="325" cy="93" r="15" style="fill:#',
'"/>',
'</svg>'];
string private cross='<rect x="95" y="275" width="10" height="40" style="fill:#872"/><rect x="85" y="285" width="30" height="10" style="fill:#872"/>';
string private but1='<circle cx="257" cy="250" r="5" style="fill:#';
string private but2='"/><circle cx="257" cy="300" r="5" style="fill:#';
string private hh1='<polygon points="76 169, 110 170, 77 172, 110 173, 76 169" style="fill:#';
string private hh2='"/><polygon points="76 174, 110 175, 77 177, 110 178, 76 174" style="fill:#';
string private sl1='<rect x="152" y="85" width="290" height="50" style="fill:#';
string private sl2='<rect x="140" y="50" width="280" height="50" style="fill:#';
string private ey1='<rect x="325" y="90" width="20" height="5" style="fill:#';
string private ey2='"/><rect x="154" y="90" width="20" height="5" style="fill:#';
string private zz='"/>';
string private ea1='<circle cx="100" cy="290" r="14" style="fill:#';
string private ea2='fe7';
string private ea3='999';
string private ea4='"/><circle cx="100" cy="290" r="4" style="fill:#000"/>';
string private ea5='<circle cx="100" cy="290" r="12" style="fill:#';
string private ea6='bdd';
string private tr1='", "attributes": [{"trait_type": "Background","value": "';
string private tr2='"},{"trait_type": "Fur","value": "';
string private tr3='"},{"trait_type": "Tattoo","value": "';
string private tr4='"},{"trait_type": "Scar","value": "';
string private tr5='"},{"trait_type": "Eyes","value": "';
string private tr6='"},{"trait_type": "Buttons","value": "';
string private tr8='"}],"image": "data:image/svg+xml;base64,';
string private ra1='A';
string private ra2='C';
string private ra4='E';
string private ra5='F';
string private ra6='G';
string private co1=', ';
string private rl1='{"name": "OnChain Bots #';
string private rl3='"}';
string private rl4='data:application/json;base64,';
address[2] private _shareholders;
uint[2] private _shares;
uint256 public mintPrice = 30000000 gwei; // 0.03 ETH
bool public saleIsActive = false;
event PaymentReleased(address to, uint256 amount);
struct Bot { // structure
uint8 bg;
uint8 fur;
uint8 eyes;
uint8 earring;
uint8 buttons;
uint8 scare;
}
// this was used to create the distributon of 10,000 and tested for uniqueness for the given parameters of this collection
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function usew(uint8[] memory w,uint256 i) internal pure returns (uint8) {
uint8 ind=0;
uint256 j=uint256(w[0]);
while (j<=i) {
ind++;
j+=uint256(w[ind]);
}
return ind;
}
function randomOne(uint256 tokenId) internal view returns (Bot memory) {
tokenId=12839-tokenId; // avoid dupes
Bot memory bot;
bot.bg = uint8(random(string(abi.encodePacked(ra1,tokenId.toString()))) % 8);
bot.fur = usew(fur_w,random(string(abi.encodePacked(but1,tokenId.toString())))%1817);
bot.eyes = usew(eyes_w,random(string(abi.encodePacked(ra2,tokenId.toString())))%1429);
bot.earring = usew(earring_w,random(string(abi.encodePacked(ra4,tokenId.toString())))%358);
bot.buttons = usew(buttons_w,random(string(abi.encodePacked(ra5,tokenId.toString())))%1329);
bot.scare = usew(scar_w,random(string(abi.encodePacked(ra6,tokenId.toString())))%1111);
if (tokenId==6291) {
bot.scare++; // perturb dupe
}
return bot;
}
// get string attributes of properties, used in tokenURI call
function getTraits(Bot memory bot) internal view returns (string memory) {
string memory o=string(abi.encodePacked(tr1,uint256(bot.bg).toString(),tr2,uint256(bot.fur).toString(),tr3,uint256(bot.earring).toString()));
return string(abi.encodePacked(o,tr4,uint256(bot.scare).toString(),tr5,uint256(bot.eyes).toString(),tr6,uint256(bot.buttons).toString(),tr8));
}
// return comma separated traits in order: scare, fur, buttons, eyes, earring, mouth, background
function getAttributes(uint256 tokenId) public view returns (string memory) {
Bot memory bot = randomOne(tokenId);
string memory o=string(abi.encodePacked(uint256(bot.scare).toString(),co1,uint256(bot.fur).toString(),co1,uint256(bot.buttons).toString(),co1));
return string(abi.encodePacked(o,uint256(bot.eyes).toString(),co1,uint256(bot.earring).toString(),co1,uint256(bot.bg).toString()));
}
function genEye(string memory a,string memory b,uint8 h) internal view returns (string memory) {
string memory out = '';
if (h>4 && h<10) { out = string(abi.encodePacked(sl1,a,zz)); }
if (h>10 && h<16) { out = string(abi.encodePacked(sl2,a,zz)); }
if (h>16) { out = string(abi.encodePacked(out,ey1,b,ey2,b,zz)); }
return out;
}
function genEarring(uint8 h) internal view returns (string memory) {
if (h==0) {
return '';
}
if (h<3) {
if (h>1) {
return string(abi.encodePacked(ea1,ea2,ea4));
}
return string(abi.encodePacked(ea1,ea3,ea4));
}
if (h>3) {
if (h>5) {
return string(abi.encodePacked(ea5,ea6,zz));
}
if (h>4) {
return string(abi.encodePacked(ea5,ea2,zz));
}
return string(abi.encodePacked(ea5,ea3,zz));
}
return cross;
}
function genSVG(Bot memory bot) internal view returns (string memory) {
string memory a=fur1[bot.fur];
string memory b=fur2[bot.fur];
string memory scarest='';
string memory butst='';
if (bot.buttons>0) {
butst=string(abi.encodePacked(but1,buttons1[bot.buttons-1],but2,buttons2[bot.buttons-1],zz));
}
if (bot.scare>0) {
scarest=string(abi.encodePacked(hh1,scar1[bot.scare-1],hh2,scar2[bot.scare-1],zz));
}
string memory output = string(abi.encodePacked(z[0],background[bot.bg],z[1],b,z[2]));
output = string(abi.encodePacked(output,b,z[3],b,z[4],a,z[5],b,z[6]));
output = string(abi.encodePacked(output,b,z[7],a,z[8],b,z[9],eyes[bot.eyes],z[10]));
output = string(abi.encodePacked(output,eyes[bot.eyes],z[11],genEye(a,b,bot.eyes)));
return string(abi.encodePacked(output,genEarring(bot.earring),scarest,butst,z[12]));
}
function tokenURI(uint256 tokenId) override public view returns (string memory) {
Bot memory bot = randomOne(tokenId);
return string(abi.encodePacked(rl4,Base64.encode(bytes(string(abi.encodePacked(rl1,tokenId.toString(),getTraits(bot),Base64.encode(bytes(genSVG(bot))),rl3))))));
}
function claim(uint256 numberOfTokens) public payable nonReentrant {
require(saleIsActive, "Sale not active now.");
require(numClaimed >= 0 && numClaimed < 9500, "invalid claim");
require(numberOfTokens <= 10, "You can only adopt 10 Bots at a time");
require(mintPrice * numberOfTokens <= msg.value, "Ether value sent is not correct");
for(uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = numClaimed + 1;
if (mintIndex <= 9500) {
_safeMint(msg.sender, mintIndex);
numClaimed += 1;
}
}
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner {
require(tokenId > 9500 && tokenId < 10001, "invalid claim");
_safeMint(owner(), tokenId);
}
function setMintPrice(uint256 newPrice) public onlyOwner {
mintPrice = newPrice;
}
function withdraw(uint256 amount) public onlyOwner {
require(address(this).balance >= amount, "Insufficient balance");
uint256 totalShares = 100;
for (uint256 i = 0; i < 2; i++) {
uint256 payment = amount * _shares[i] / totalShares;
Address.sendValue(payable(_shareholders[i]), payment);
emit PaymentReleased(_shareholders[i], payment);
}
}
constructor() payable ERC721("OnChainBots", "BOTS") Ownable() {
_shareholders[0] = 0x3f758b112dFE9157988BF0e194A8f5c4f0Acc684; // theaibutcher
_shareholders[1] = 0xCE63810B999Deb7123D431893a297E2C558C16a9; // investor
_shares[0] = 60;
_shares[1] = 40;
}
}
//Made in Patliputra
|
return comma separated traits in order: scare, fur, buttons, eyes, earring, mouth, background
|
function getAttributes(uint256 tokenId) public view returns (string memory) {
Bot memory bot = randomOne(tokenId);
string memory o=string(abi.encodePacked(uint256(bot.scare).toString(),co1,uint256(bot.fur).toString(),co1,uint256(bot.buttons).toString(),co1));
return string(abi.encodePacked(o,uint256(bot.eyes).toString(),co1,uint256(bot.earring).toString(),co1,uint256(bot.bg).toString()));
}
| 5,825,961 |
/*
https://powerpool.finance/
wrrrw r wrr
ppwr rrr wppr0 prwwwrp prwwwrp wr0
rr 0rrrwrrprpwp0 pp pr prrrr0 pp 0r prrrr0 0rwrrr pp pr prrrr0 prrrr0 r0
rrp pr wr00rrp prwww0 pp wr pp w00r prwwwpr 0rw prwww0 pp wr pp wr r0
r0rprprwrrrp pr0 pp wr pr pp rwwr wr 0r pp wr pr wr pr r0
prwr wrr0wpwr 00 www0 0w0ww www0 0w 00 www0 www0 0www0
wrr ww0rrrr
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/IMigrator.sol
pragma solidity 0.6.12;
interface IMigrator {
// Perform LP token migration from legacy UniswapV2 to PowerSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// PowerSwap must mint EXACTLY the same amount of PowerSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token, uint8 poolType) external returns (IERC20);
}
// File: contracts/Checkpoints.sol
pragma solidity 0.6.12;
contract Checkpoints {
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @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 An event thats emitted when a delegate account's vote balance changes
event CheckpointBalanceChanged(address indexed delegate, uint previousBalance, uint newBalance);
constructor() public {
}
/**
* @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];
}
/// @dev The exact copy from CVP token
/**
* @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;
}
/// @dev The exact copy from CVP token
/**
* @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, "Checkpoints::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;
}
/**
* @notice Writes checkpoint number, old and new balance to checkpoint for account address
* @param account The address to write balance
* @param balance New account balance
*/
function _writeBalance(address account, uint96 balance) internal {
uint32 srcRepNum = numCheckpoints[account];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[account][srcRepNum - 1].votes : 0;
uint96 srcRepNew = safe96(balance, "Checkpoints::_writeBalance: vote amount overflow");
_writeCheckpoint(account, srcRepNum, srcRepOld, srcRepNew);
}
/// @dev A copy from CVP token, only the event name changed
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Checkpoints::_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 CheckpointBalanceChanged(delegatee, oldVotes, newVotes);
}
/// @dev The exact copy from CVP token
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
/// @dev The exact copy from CVP token
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
/// @dev The exact copy from CVP token
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
/// @dev The exact copy from CVP token
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
}
// File: contracts/LPMining.sol
pragma solidity 0.6.12;
// Note that LPMining is ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract
// and the community can show to govern itself.
contract LPMining is Ownable, Checkpoints {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of CVPs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCvpPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accCvpPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CVPs to distribute per block.
uint256 lastRewardBlock; // Last block number that CVPs distribution occurs.
uint256 accCvpPerShare; // Accumulated CVPs per share, times 1e12. See below.
bool votesEnabled; // Pool enabled to write votes
uint8 poolType; // Pool type (1 For Uniswap, 2 for Balancer)
}
// The CVP TOKEN!
IERC20 public cvp;
// Reservoir address.
address public reservoir;
// CVP tokens reward per block.
uint256 public cvpPerBlock;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigrator public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Pid of each pool by its address
mapping(address => uint256) public poolPidByAddress;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when CVP mining starts.
uint256 public startBlock;
event AddLpToken(address indexed lpToken, uint256 indexed pid, uint256 allocPoint);
event SetLpToken(address indexed lpToken, uint256 indexed pid, uint256 allocPoint);
event SetMigrator(address indexed migrator);
event SetCvpPerBlock(uint256 cvpPerBlock);
event MigrateLpToken(address indexed oldLpToken, address indexed newLpToken, uint256 indexed pid);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event CheckpointPoolVotes(address indexed user, uint256 indexed pid, uint256 votes, uint256 price);
event CheckpointTotalVotes(address indexed user, uint256 votes);
constructor(
IERC20 _cvp,
address _reservoir,
uint256 _cvpPerBlock,
uint256 _startBlock
) public {
cvp = _cvp;
reservoir = _reservoir;
cvpPerBlock = _cvpPerBlock;
startBlock = _startBlock;
emit SetCvpPerBlock(_cvpPerBlock);
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, uint8 _poolType, bool _votesEnabled, bool _withUpdate) public onlyOwner {
require(!isLpTokenAdded(_lpToken), "add: Lp token already added");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
uint256 pid = poolInfo.length;
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCvpPerShare: 0,
votesEnabled: _votesEnabled,
poolType: _poolType
}));
poolPidByAddress[address(_lpToken)] = pid;
emit AddLpToken(address(_lpToken), pid, _allocPoint);
}
// Update the given pool's CVP allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, uint8 _poolType, bool _votesEnabled, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].votesEnabled = _votesEnabled;
poolInfo[_pid].poolType = _poolType;
emit SetLpToken(address(poolInfo[_pid].lpToken), _pid, _allocPoint);
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigrator _migrator) public onlyOwner {
migrator = _migrator;
emit SetMigrator(address(_migrator));
}
// Set CVP reward per block. Can only be called by the owner.
function setCvpPerBlock(uint256 _cvpPerBlock) public onlyOwner {
cvpPerBlock = _cvpPerBlock;
emit SetCvpPerBlock(_cvpPerBlock);
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken, pool.poolType);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
delete poolPidByAddress[address(lpToken)];
poolPidByAddress[address(newLpToken)] = _pid;
emit MigrateLpToken(address(lpToken), address(newLpToken), _pid);
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return _to.sub(_from);
}
// View function to see pending CVPs on frontend.
function pendingCvp(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCvpPerShare = pool.accCvpPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cvpReward = multiplier.mul(cvpPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accCvpPerShare = accCvpPerShare.add(cvpReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCvpPerShare).div(1e12).sub(user.rewardDebt);
}
// Return bool - is Lp Token added or not
function isLpTokenAdded(IERC20 _lpToken) public view returns (bool) {
uint256 pid = poolPidByAddress[address(_lpToken)];
return poolInfo.length > pid && address(poolInfo[pid].lpToken) == address(_lpToken);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cvpReward = multiplier.mul(cvpPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
cvp.transferFrom(reservoir, address(this), cvpReward);
pool.accCvpPerShare = pool.accCvpPerShare.add(cvpReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to LPMining for CVP allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accCvpPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeCvpTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCvpPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
checkpointVotes(msg.sender);
}
// Withdraw LP tokens from LPMining.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCvpPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeCvpTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accCvpPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
checkpointVotes(msg.sender);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
checkpointVotes(msg.sender);
}
// Write votes at current block
function checkpointVotes(address _user) public {
uint256 length = poolInfo.length;
uint256 totalVotesBalance = 0;
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
uint256 userLpTokenBalance = userInfo[pid][_user].amount;
if (userLpTokenBalance == 0 || !pool.votesEnabled) {
continue;
}
uint256 lpTokenTotalSupply = pool.lpToken.totalSupply();
if (lpTokenTotalSupply == 0) {
continue;
}
uint256 lpCvpBalance = cvp.balanceOf(address(pool.lpToken));
uint256 lpCvpPrice = lpCvpBalance.mul(1e12).div(lpTokenTotalSupply);
uint256 lpVotesBalance = userLpTokenBalance.mul(lpCvpPrice).div(1e12);
totalVotesBalance = totalVotesBalance.add(lpVotesBalance);
emit CheckpointPoolVotes(_user, pid, lpVotesBalance, lpCvpPrice);
}
emit CheckpointTotalVotes(_user, totalVotesBalance);
_writeBalance(_user, safe96(totalVotesBalance, "LPMining::checkpointVotes: Amount overflow"));
}
// Safe cvp transfer function, just in case if rounding error causes pool to not have enough CVPs.
function safeCvpTransfer(address _to, uint256 _amount) internal {
uint256 cvpBal = cvp.balanceOf(address(this));
if (_amount > cvpBal) {
cvp.transfer(_to, cvpBal);
} else {
cvp.transfer(_to, _amount);
}
}
}
|
Add a new lp to the pool. Can only be called by the owner.
|
function add(uint256 _allocPoint, IERC20 _lpToken, uint8 _poolType, bool _votesEnabled, bool _withUpdate) public onlyOwner {
require(!isLpTokenAdded(_lpToken), "add: Lp token already added");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
uint256 pid = poolInfo.length;
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCvpPerShare: 0,
votesEnabled: _votesEnabled,
poolType: _poolType
}));
poolPidByAddress[address(_lpToken)] = pid;
emit AddLpToken(address(_lpToken), pid, _allocPoint);
}
| 5,948,524 |
pragma solidity ^0.4.24;
contract SafeMath {
function safeMul(uint a, uint b) pure internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) pure internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) pure internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
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;
/// @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);
}
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(uint error);
enum Error {
NO_ERROR,
INVALIDE_ADMIN,
WITHDRAW_TOKEN_AMOUNT_ERROR,
WITHDRAW_TOKEN_TRANSER_ERROR,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TRANSFER_FROM_ERROR,
LENDER_INSUFFICIENT_BORROW_ALLOWANCE,
LENDER_INSUFFICIENT_BORROWER_BALANCE,
LENDER_TRANSFER_FROM_BORROW_ERROR,
LENDER_INSUFFICIENT_ADMIN_ALLOWANCE,
LENDER_INSUFFICIENT_ADMIN_BALANCE,
LENDER_TRANSFER_FROM_ADMIN_ERROR,
CALL_MARGIN_ALLOWANCE_ERROR,
CALL_MARGIN_BALANCE_ERROR,
CALL_MARGIN_TRANSFER_ERROR,
REPAY_ALLOWANCE_ERROR,
REPAY_BALANCE_ERROR,
REPAY_TX_ERROR,
FORCE_REPAY_ALLOWANCE_ERROR,
FORCE_REPAY_BALANCE_ERROR,
FORCE_REPAY_TX_ERROR,
CLOSE_POSITION_ALLOWANCE_ERROR,
CLOSE_POSITION_TX_ERROR,
CLOSE_POSITION_MUST_ADMIN_BEFORE_DEADLINE,
CLOSE_POSITION_MUST_ADMIN_OR_LENDER_AFTER_DEADLINE,
LENDER_TEST_TRANSFER_ADMIN_ERROR,
LENDER_TEST_TRANSFER_BORROWR_ERROR,
LENDER_TEST_TRANSFERFROM_ADMIN_ERROR,
LENDER_TEST_TRANSFERFROM_BORROWR_ERROR,
SEND_TOKEN_AMOUNT_ERROR,
SEND_TOKEN_TRANSER_ERROR
}
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err) internal returns (uint) {
emit Failure(uint(err));
return uint(err);
}
}
library ERC20AsmFn {
function isContract(address addr) internal {
assembly {
if iszero(extcodesize(addr)) { revert(0, 0) }
}
}
function handleReturnData() internal returns (bool result) {
assembly {
switch returndatasize()
case 0 { // not a std erc20
result := 1
}
case 32 { // std erc20
returndatacopy(0, 0, 32)
result := mload(0)
}
default { // anything else, should revert for safety
revert(0, 0)
}
}
}
function asmTransfer(address _erc20Addr, address _to, uint256 _value) internal returns (bool result) {
// Must be a contract addr first!
isContract(_erc20Addr);
// call return false when something wrong
require(_erc20Addr.call(bytes4(keccak256("transfer(address,uint256)")), _to, _value), "asmTransfer error");
// handle returndata
return handleReturnData();
}
function asmTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal returns (bool result) {
// Must be a contract addr first!
isContract(_erc20Addr);
// call return false when something wrong
require(_erc20Addr.call(bytes4(keccak256("transferFrom(address,address,uint256)")), _from, _to, _value), "asmTransferFrom error");
// handle returndata
return handleReturnData();
}
// function asmApprove(address _erc20Addr, address _spender, uint256 _value) internal returns (bool result) {
// // Must be a contract addr first!
// isContract(_erc20Addr);
// // call return false when something wrong
// require(_erc20Addr.call(bytes4(keccak256("approve(address,uint256)")), _spender, _value), "asmApprove error");
// // handle returndata
// return handleReturnData();
// }
}
contract TheForceLending is SafeMath, ErrorReporter {
using ERC20AsmFn for EIP20Interface;
enum OrderState {
ORDER_STATUS_PENDING,
ORDER_STATUS_ACCEPTED
}
struct Order_t {
bytes32 partner_id;
uint deadline;
OrderState state;
address borrower;
address lender;
uint lending_cycle;
address token_get;
uint amount_get;
address token_pledge;//tokenGive
uint amount_pledge;//amountGive
uint _nonce;
uint pledge_rate;
uint interest_rate;
uint fee_rate;
}
address public admin; //the admin address
address public offcialFeeAccount; //the account that will receive fees
mapping (bytes32 => address) public partnerAccounts;// bytes32-> address, eg: platformA->0xa{40}, platfromB->0xb{40}
mapping (bytes32 => mapping (address => mapping (address => uint))) public partnerTokens;// platform->tokenContract->address->balance
mapping (bytes32 => mapping (address => mapping (bytes32 => Order_t))) public partnerOrderBook;// platform->address->hash->order_t
event Borrow(bytes32 partnerId,
address tokenGet,
uint amountGet,
address tokenGive,
uint amountGive,
uint nonce,
uint lendingCycle,
uint pledgeRate,
uint interestRate,
uint feeRate,
address user,
bytes32 hash,
uint status);
event Lend(bytes32 partnerId, address borrower, bytes32 txId, address token, uint amount, address give, uint status);//txId为借款单txId
event CancelOrder(bytes32 partnerId, address borrower, bytes32 txId, address by, uint status);//取消借款单,只能被borrower或者合约取消
event Callmargin(bytes32 partnerId, address borrower, bytes32 txId, address token, uint amount, address by, uint status);
event Repay(bytes32 partnerId, address borrower, bytes32 txId, address token, uint amount, address by, uint status);
event Closepstion(bytes32 partnerId, address borrower, bytes32 txId, address token, address by, uint status);
event Forcerepay(bytes32 partnerId, address borrower, bytes32 txId, address token, address by, uint status);
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
event Send(address token, address user, address to, uint amount, uint balance);
constructor(address admin_, address offcialFeeAccount_) public {
admin = admin_;
offcialFeeAccount = offcialFeeAccount_;
}
function() public payable {
revert("fallback can't be payable");
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin can do this!");
_;
}
function changeAdmin(address admin_) public onlyAdmin {
admin = admin_;
}
function changeFeeAccount(address offcialFeeAccount_) public onlyAdmin {
offcialFeeAccount = offcialFeeAccount_;
}
//增
function addPartner(bytes32 partnerId, address partner) public onlyAdmin {
require(partnerAccounts[partnerId] == address(0), "already exists!");
partnerAccounts[partnerId] = partner;
}
//删
function delPartner(bytes32 partnerId) public onlyAdmin {
delete partnerAccounts[partnerId];
}
//改
function modPartner(bytes32 partnerId, address partner) public onlyAdmin {
require(partnerAccounts[partnerId] != address(0), "not exists!");
partnerAccounts[partnerId] = partner;
}
//查
function getPartner(bytes32 partnerId) public view returns (address) {
return partnerAccounts[partnerId];
}
function depositToken(bytes32 partnerId, address token, uint amount) internal returns (uint){
//remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf.
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
if (token == 0) revert("invalid token address!");
if (EIP20Interface(token).allowance(msg.sender, address(this)) < amount) {
return fail(Error.TOKEN_INSUFFICIENT_ALLOWANCE);
}
if (EIP20Interface(token).balanceOf(msg.sender) < amount) {
return fail(Error.TOKEN_INSUFFICIENT_ALLOWANCE);
}
if (!EIP20Interface(token).asmTransferFrom(msg.sender, address(this), amount)) {
return fail(Error.TRANSFER_FROM_ERROR);
}
partnerTokens[partnerId][token][msg.sender] = safeAdd(partnerTokens[partnerId][token][msg.sender], amount);
return 0;
}
function withdrawToken(bytes32 partnerId, address token, uint amount) internal returns (uint) {
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
if (token == 0) revert("invalid token address");
if (partnerTokens[partnerId][token][msg.sender] < amount) {
return fail(Error.WITHDRAW_TOKEN_AMOUNT_ERROR);
}
partnerTokens[partnerId][token][msg.sender] = safeSub(partnerTokens[partnerId][token][msg.sender], amount);
if (!EIP20Interface(token).asmTransfer(msg.sender, amount)) {
return fail(Error.WITHDRAW_TOKEN_TRANSER_ERROR);
}
return 0;
}
function sendToken(bytes32 partnerId, address token, address to, uint amount) internal returns (uint) {
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
if (token==0 || to == 0 || amount == 0) revert("invalid token address or amount");
if (partnerTokens[partnerId][token][to] < amount) {
return fail(Error.SEND_TOKEN_AMOUNT_ERROR);
}
partnerTokens[partnerId][token][to] = safeSub(partnerTokens[partnerId][token][to], amount);
if (!EIP20Interface(token).asmTransfer(to, amount)) {
return fail(Error.SEND_TOKEN_TRANSER_ERROR);
}
return 0;
}
function balanceOf(bytes32 partnerId, address token, address user) public view returns (uint) {
return partnerTokens[partnerId][token][user];
}
function borrow(bytes32 partnerId,//平台标记
address tokenGet, //借出币种地址
uint amountGet, //借出币种数量
address tokenGive, //抵押币种地址
uint amountGive,//抵押币种数量
uint nonce,
uint lendingCycle,
uint pledgeRate,
uint interestRate,
uint feeRate) public returns (bytes32 txId){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
bytes32 txid = hash(partnerId, tokenGet, amountGet, tokenGive, amountGive, nonce, lendingCycle, pledgeRate, interestRate, feeRate);
uint status = 0;
partnerOrderBook[partnerId][msg.sender][txid] = Order_t({
partner_id: partnerId,
deadline: 0,
state: OrderState.ORDER_STATUS_PENDING,
borrower: msg.sender,
lender: address(0),
lending_cycle: lendingCycle,
token_get: tokenGet,
amount_get: amountGet,
token_pledge: tokenGive,
amount_pledge: amountGive,
_nonce: nonce,
pledge_rate: pledgeRate,
interest_rate: interestRate,
fee_rate: feeRate
});
status = depositToken(partnerId, tokenGive, amountGive);
emit Borrow(partnerId, tokenGet, amountGet, tokenGive, amountGive, nonce, lendingCycle, pledgeRate, interestRate, feeRate, msg.sender, txid, status);
return txid;
}
//A借款,B出借,A到账数量为申请数量,无砍头息,B出借的数量包括A的申请数量+手续费(项目方手续费+平台合作方手续费,手续费可能为0)
function lend(bytes32 partnerId, address borrower, bytes32 hash, address token, uint lenderAmount, uint offcialFeeAmount, uint partnerFeeAmount) public returns (uint) {
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");//order not found
require(partnerOrderBook[partnerId][borrower][hash].borrower != msg.sender, "cannot lend to self");//cannot lend to self
require(partnerOrderBook[partnerId][borrower][hash].token_get == token, "attempt to use an invalid type of token");//attempt to use an invalid type of token
require(partnerOrderBook[partnerId][borrower][hash].amount_get == lenderAmount - offcialFeeAmount - partnerFeeAmount, "amount_get != amount - offcialFeeAmount - partnerFeeAmount");//单个出借金额不足,后续可以考虑多个出借人,现在只考虑一个出借人
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_PENDING, "state != OrderState.ORDER_STATUS_PENDING");
uint status = 0;
if (EIP20Interface(token).allowance(msg.sender, address(this)) < lenderAmount) {
status = uint(Error.TOKEN_INSUFFICIENT_ALLOWANCE);
}
if (status == 0 && EIP20Interface(token).balanceOf(msg.sender) < lenderAmount) {
status = uint(Error.LENDER_INSUFFICIENT_BORROWER_BALANCE);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, partnerOrderBook[partnerId][borrower][hash].borrower, partnerOrderBook[partnerId][borrower][hash].amount_get)) {
status = uint(Error.LENDER_TRANSFER_FROM_BORROW_ERROR);
}
if (offcialFeeAmount != 0) {
if (status == 0 && EIP20Interface(token).allowance(msg.sender, address(this)) < offcialFeeAmount) {
status = uint(Error.LENDER_INSUFFICIENT_ADMIN_ALLOWANCE);
}
if (status == 0 && EIP20Interface(token).balanceOf(msg.sender) < offcialFeeAmount) {
status = uint(Error.LENDER_INSUFFICIENT_ADMIN_BALANCE);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, offcialFeeAccount, offcialFeeAmount)) {
status = uint(Error.LENDER_TRANSFER_FROM_ADMIN_ERROR);
}
}
if (partnerFeeAmount != 0) {
if (status == 0 && EIP20Interface(token).allowance(msg.sender, address(this)) < partnerFeeAmount) {
status = uint(Error.LENDER_INSUFFICIENT_ADMIN_ALLOWANCE);
}
if (status == 0 && EIP20Interface(token).balanceOf(msg.sender) < partnerFeeAmount) {
status = uint(Error.LENDER_INSUFFICIENT_ADMIN_BALANCE);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, partnerAccounts[partnerId], partnerFeeAmount)) {
status = uint(Error.LENDER_TRANSFER_FROM_ADMIN_ERROR);
}
}
if (status == 0) {
partnerOrderBook[partnerId][borrower][hash].deadline = now + partnerOrderBook[partnerId][borrower][hash].lending_cycle * (1 minutes);
partnerOrderBook[partnerId][borrower][hash].lender = msg.sender;
partnerOrderBook[partnerId][borrower][hash].state = OrderState.ORDER_STATUS_ACCEPTED;
}
emit Lend(partnerId, borrower, hash, token, lenderAmount, msg.sender, status);
return 0;
}
function cancelOrder(bytes32 partnerId, address borrower, bytes32 hash) public {
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");//order not found
require(partnerOrderBook[partnerId][borrower][hash].borrower == msg.sender || msg.sender == admin,
"only borrower or admin can do this operation");//only borrower or contract can do this operation
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_PENDING, "state != OrderState.ORDER_STATUS_PENDING");
uint status = 0;
status = sendToken(partnerId, partnerOrderBook[partnerId][borrower][hash].token_pledge, partnerOrderBook[partnerId][borrower][hash].borrower, partnerOrderBook[partnerId][borrower][hash].amount_pledge);
if (status == 0) {
delete partnerOrderBook[partnerId][borrower][hash];
}
emit CancelOrder(partnerId, borrower, hash, msg.sender, status);
}
function callmargin(bytes32 partnerId, address borrower, bytes32 hash, address token, uint amount) public returns (uint){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");
require(amount > 0, "amount must >0");
require(token != address(0), "invalid token");
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_ACCEPTED, "state != OrderState.ORDER_STATUS_ACCEPTED");
require(partnerOrderBook[partnerId][borrower][hash].token_pledge == token, "invalid pledge token");
uint status = 0;
if (status == 0 && EIP20Interface(token).allowance(msg.sender, address(this)) < amount) {
status = uint(Error.CALL_MARGIN_ALLOWANCE_ERROR);
}
if (status == 0) {
partnerOrderBook[partnerId][borrower][hash].amount_pledge += amount;
partnerTokens[partnerId][token][borrower] = safeAdd(partnerTokens[partnerId][token][borrower], amount);
}
if (status == 0 && EIP20Interface(token).balanceOf(msg.sender) < amount) {
status = uint(Error.CALL_MARGIN_BALANCE_ERROR);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, address(this), amount)) {
status = uint(Error.CALL_MARGIN_TRANSFER_ERROR);
}
emit Callmargin(partnerId, borrower, hash, token, amount, msg.sender, status);
return 0;
}
//A还款,需要支付本金+利息给出借方,给项目方和平台合作方手续费
function repay(bytes32 partnerId, address borrower, bytes32 hash, address token, uint repayAmount, uint lenderAmount, uint offcialFeeAmount, uint partnerFeeAmount) public returns (uint){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_ACCEPTED, "state != OrderState.ORDER_STATUS_ACCEPTED");
require(token != address(0), "invalid token");
require(token == partnerOrderBook[partnerId][borrower][hash].token_get, "invalid repay token");
//还款数量,为借款数量加上利息加上项目方手续费+合作方手续费
require(repayAmount == lenderAmount + offcialFeeAmount + partnerFeeAmount, "invalid repay amount");
require(lenderAmount >= partnerOrderBook[partnerId][borrower][hash].amount_get, "invalid lender amount");
require(msg.sender == partnerOrderBook[partnerId][borrower][hash].borrower, "invalid repayer, must be borrower");
uint status = 0;
//允许contract花费借款者的所借的token+利息token
if (status == 0 && EIP20Interface(token).allowance(msg.sender, address(this)) < repayAmount) {
status = uint(Error.REPAY_ALLOWANCE_ERROR);
}
if (status == 0 && EIP20Interface(token).balanceOf(msg.sender) < repayAmount) {
status = uint(Error.REPAY_BALANCE_ERROR);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, partnerOrderBook[partnerId][borrower][hash].lender, lenderAmount)) {
status = uint(Error.REPAY_TX_ERROR);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, offcialFeeAccount, offcialFeeAmount)) {
status = uint(Error.REPAY_TX_ERROR);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, partnerAccounts[partnerId], partnerFeeAmount)) {
status = uint(Error.REPAY_TX_ERROR);
}
if (status == 0) {
status = withdrawToken(partnerId, partnerOrderBook[partnerId][borrower][hash].token_pledge, partnerOrderBook[partnerId][borrower][hash].amount_pledge);
}
if (status == 0) {
delete partnerOrderBook[partnerId][borrower][hash];
}
emit Repay(partnerId, borrower, hash, token, repayAmount, msg.sender, status);
return status;
}
//逾期强制归还,由合约管理者调用,非borrower,非lender调用,borrower需要支付抵押资产给出借人(本金+利息),平台合作方(手续费)和项目方(手续费),如果还有剩余,剩余部分归还给A
function forcerepay(bytes32 partnerId, address borrower, bytes32 hash, address token, uint lenderAmount, uint offcialFeeAmount, uint partnerFeeAmount) public returns (uint){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");
require(token != address(0), "invalid forcerepay token address");
require(token == partnerOrderBook[partnerId][borrower][hash].token_pledge, "invalid forcerepay token");
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_ACCEPTED, "state != OrderState.ORDER_STATUS_ACCEPTED");
require(msg.sender == admin, "forcerepay must be admin");
require(now > partnerOrderBook[partnerId][borrower][hash].deadline, "cannot forcerepay before deadline");
uint status = 0;
//合约管理员发送抵押资产到出借人,数量由上层传入
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], lenderAmount);
if (!EIP20Interface(token).asmTransfer(partnerOrderBook[partnerId][borrower][hash].lender, lenderAmount)) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
}
//合约管理员发送抵押资产到平台合作方,数量由上层传入
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], partnerFeeAmount);
if (!EIP20Interface(token).asmTransfer(partnerAccounts[partnerId], partnerFeeAmount)) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
}
//合约管理员发送抵押资产到项目方,数量由上层传入
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], offcialFeeAmount);
if (!EIP20Interface(token).asmTransfer(offcialFeeAccount, offcialFeeAmount)) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
}
//合约管理员发送剩余抵押资产到借款方,数量由上层传入
if (partnerTokens[partnerId][token][borrower] > 0) {
if (!EIP20Interface(token).asmTransfer(borrower, partnerTokens[partnerId][token][borrower])) {
status = uint(Error.FORCE_REPAY_TX_ERROR);
} else {
partnerTokens[partnerId][token][borrower] = 0;
}
}
if (status == 0) {
delete partnerOrderBook[partnerId][borrower][hash];
}
emit Forcerepay(partnerId, borrower, hash, token, msg.sender, status);
return status;
}
//价格波动平仓,borrower需要支付抵押资产给出借人(本金+利息),项目方(手续费)和平台合作方(手续费),如果还有剩余,剩余部分归还给A
function closepstion(bytes32 partnerId, address borrower, bytes32 hash, address token, uint lenderAmount, uint offcialFeeAmount, uint partnerFeeAmount) public returns (uint){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");
require(token != address(0), "invalid token");
require(token == partnerOrderBook[partnerId][borrower][hash].token_pledge, "invalid token");
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_ACCEPTED, "state != OrderState.ORDER_STATUS_ACCEPTED");
require(msg.sender == admin, "closepstion must be admin");
uint status = 0;
//未逾期
if (partnerOrderBook[partnerId][borrower][hash].deadline > now) {
if (msg.sender != admin) {
//only admin of this contract can do this operation before deadline
status = uint(Error.CLOSE_POSITION_MUST_ADMIN_BEFORE_DEADLINE);
}
} else {
if (!(msg.sender == admin || msg.sender == partnerOrderBook[partnerId][borrower][hash].lender)) {
//only lender or admin of this contract can do this operation
status = uint(Error.CLOSE_POSITION_MUST_ADMIN_OR_LENDER_AFTER_DEADLINE);
}
}
if (status == 0) {
//合约管理员发送抵押资产到出借人,数量由上层传入
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], lenderAmount);
if (!EIP20Interface(token).asmTransfer(partnerOrderBook[partnerId][borrower][hash].lender, lenderAmount)) {
status = uint(Error.CLOSE_POSITION_TX_ERROR);
}
//合约管理员发送抵押资产到平台合作方,数量由上层传入
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], partnerFeeAmount);
if (!EIP20Interface(token).asmTransfer(partnerAccounts[partnerId], partnerFeeAmount)) {
status = uint(Error.CLOSE_POSITION_TX_ERROR);
}
//合约管理员发送抵押资产到项目方,数量由上层传入
partnerTokens[partnerId][token][borrower] = safeSub(partnerTokens[partnerId][token][borrower], offcialFeeAmount);
if (!EIP20Interface(token).asmTransfer(offcialFeeAccount, offcialFeeAmount)) {
status = uint(Error.CLOSE_POSITION_TX_ERROR);
}
//合约管理员发送剩余抵押资产到借款方,数量由上层传入
if (partnerTokens[partnerId][token][borrower] > 0) {
if (!EIP20Interface(token).asmTransfer(borrower, partnerTokens[partnerId][token][borrower])) {
status = uint(Error.CLOSE_POSITION_TX_ERROR);
} else {
partnerTokens[partnerId][token][borrower] = 0;
}
}
if (status == 0) {
delete partnerOrderBook[partnerId][borrower][hash];
}
}
emit Closepstion(partnerId, borrower, hash, token, address(this), status);
return status;
}
//ADDITIONAL HELPERS ADDED FOR TESTING
function hash(
bytes32 partnerId,
address tokenGet,
uint amountGet,
address tokenGive,
uint amountGive,
uint nonce,
uint lendingCycle,
uint pledgeRate,
uint interestRate,
uint feeRate
)
public
view
returns (bytes32)
{
//return sha256(this, tokenGet, amountGet, tokenGive, amountGive, nonce, lendingCycle, pledgeRate, interestRate, feeRate);
return sha256(abi.encodePacked(address(this), partnerId, tokenGet, amountGet, tokenGive, amountGive, nonce, lendingCycle, pledgeRate, interestRate, feeRate));
}
}
|
A还款,需要支付本金+利息给出借方,给项目方和平台合作方手续费还款数量,为借款数量加上利息加上项目方手续费+合作方手续费允许contract花费借款者的所借的token+利息token
|
function repay(bytes32 partnerId, address borrower, bytes32 hash, address token, uint repayAmount, uint lenderAmount, uint offcialFeeAmount, uint partnerFeeAmount) public returns (uint){
require(partnerAccounts[partnerId] != address(0), "parnerId must add first");
require(partnerOrderBook[partnerId][borrower][hash].borrower != address(0), "order not found");
require(partnerOrderBook[partnerId][borrower][hash].state == OrderState.ORDER_STATUS_ACCEPTED, "state != OrderState.ORDER_STATUS_ACCEPTED");
require(token != address(0), "invalid token");
require(token == partnerOrderBook[partnerId][borrower][hash].token_get, "invalid repay token");
require(repayAmount == lenderAmount + offcialFeeAmount + partnerFeeAmount, "invalid repay amount");
require(lenderAmount >= partnerOrderBook[partnerId][borrower][hash].amount_get, "invalid lender amount");
require(msg.sender == partnerOrderBook[partnerId][borrower][hash].borrower, "invalid repayer, must be borrower");
uint status = 0;
if (status == 0 && EIP20Interface(token).allowance(msg.sender, address(this)) < repayAmount) {
status = uint(Error.REPAY_ALLOWANCE_ERROR);
}
if (status == 0 && EIP20Interface(token).balanceOf(msg.sender) < repayAmount) {
status = uint(Error.REPAY_BALANCE_ERROR);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, partnerOrderBook[partnerId][borrower][hash].lender, lenderAmount)) {
status = uint(Error.REPAY_TX_ERROR);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, offcialFeeAccount, offcialFeeAmount)) {
status = uint(Error.REPAY_TX_ERROR);
}
if (status == 0 && !EIP20Interface(token).asmTransferFrom(msg.sender, partnerAccounts[partnerId], partnerFeeAmount)) {
status = uint(Error.REPAY_TX_ERROR);
}
if (status == 0) {
status = withdrawToken(partnerId, partnerOrderBook[partnerId][borrower][hash].token_pledge, partnerOrderBook[partnerId][borrower][hash].amount_pledge);
}
if (status == 0) {
delete partnerOrderBook[partnerId][borrower][hash];
}
emit Repay(partnerId, borrower, hash, token, repayAmount, msg.sender, status);
return status;
}
| 12,533,670 |
./full_match/7700/0x93124c923dA389Bc0f13840fB822Ce715ca67ED6/sources/contracts/bridge/MiniChefV2.sol
|
Deposit LP tokens to MCV2 for SYNAPSE allocation. pid The index of the pool. See `poolInfo`. amount LP token amount to deposit. to The receiver of `amount` deposit benefit. Effects Interactions
|
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION));
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSynapseReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
| 4,655,932 |
./full_match/80001/0xf2F9Dc580289FC127D88f6A6FeF19b0e3c99BBCd/sources/contracts/lib/SettlementTokenMath.sol
|
returns number converted between specified decimals
|
function convertTokenDecimals(
uint256 amount,
uint8 fromDecimals,
uint8 toDecimals
) internal pure returns (uint256) {
return
fromDecimals >= toDecimals
? amount.div(10**(fromDecimals - toDecimals))
: amount.mul(10**(toDecimals - fromDecimals));
}
| 9,454,115 |
// File: contracts/zeppelin-solidity/ownership/Ownable.sol
pragma solidity ^0.4.24;
/**
* @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;
}
}
// File: contracts/token/Managed.sol
pragma solidity ^0.4.24;
contract Managed is Ownable {
mapping (address => bool) public managers;
modifier onlyManager () {
require(isManager(), "Only managers may perform this action");
_;
}
modifier onlyManagerOrOwner () {
require(
checkManagerStatus(msg.sender) || msg.sender == owner,
"Only managers or owners may perform this action"
);
_;
}
function checkManagerStatus (address managerAddress) public view returns (bool) {
return managers[managerAddress];
}
function isManager () public view returns (bool) {
return checkManagerStatus(msg.sender);
}
function addManager (address managerAddress) public onlyOwner {
managers[managerAddress] = true;
}
function removeManager (address managerAddress) public onlyOwner {
managers[managerAddress] = false;
}
}
// File: contracts/token/ManagedWhitelist.sol
pragma solidity ^0.4.24;
contract ManagedWhitelist is Managed {
// CORE - addresses that are controller by Civil Foundation, Civil Media, or Civil Newsrooms
mapping (address => bool) public coreList;
// CIVILIAN - addresses that have completed the tutorial
mapping (address => bool) public civilianList;
// UNLOCKED - addresses that have completed "proof of use" requirements
mapping (address => bool) public unlockedList;
// VERIFIED - addresses that have completed KYC verification
mapping (address => bool) public verifiedList;
// STOREFRONT - addresses that will sell tokens on behalf of the Civil Foundation. these addresses can only transfer to VERIFIED users
mapping (address => bool) public storefrontList;
// NEWSROOM - multisig addresses created by the NewsroomFactory
mapping (address => bool) public newsroomMultisigList;
// addToCore allows a manager to add an address to the CORE list
function addToCore (address operator) public onlyManagerOrOwner {
coreList[operator] = true;
}
// removeFromCore allows a manager to remove an address frin the CORE list
function removeFromCore (address operator) public onlyManagerOrOwner {
coreList[operator] = false;
}
// addToCivilians allows a manager to add an address to the CORE list
function addToCivilians (address operator) public onlyManagerOrOwner {
civilianList[operator] = true;
}
// removeFromCivilians allows a manager to remove an address from the CORE list
function removeFromCivilians (address operator) public onlyManagerOrOwner {
civilianList[operator] = false;
}
// addToUnlocked allows a manager to add an address to the UNLOCKED list
function addToUnlocked (address operator) public onlyManagerOrOwner {
unlockedList[operator] = true;
}
// removeFromUnlocked allows a manager to remove an address from the UNLOCKED list
function removeFromUnlocked (address operator) public onlyManagerOrOwner {
unlockedList[operator] = false;
}
// addToVerified allows a manager to add an address to the VERIFIED list
function addToVerified (address operator) public onlyManagerOrOwner {
verifiedList[operator] = true;
}
// removeFromVerified allows a manager to remove an address from the VERIFIED list
function removeFromVerified (address operator) public onlyManagerOrOwner {
verifiedList[operator] = false;
}
// addToStorefront allows a manager to add an address to the STOREFRONT list
function addToStorefront (address operator) public onlyManagerOrOwner {
storefrontList[operator] = true;
}
// removeFromStorefront allows a manager to remove an address from the STOREFRONT list
function removeFromStorefront (address operator) public onlyManagerOrOwner {
storefrontList[operator] = false;
}
// addToNewsroomMultisigs allows a manager to remove an address from the STOREFRONT list
function addToNewsroomMultisigs (address operator) public onlyManagerOrOwner {
newsroomMultisigList[operator] = true;
}
// removeFromNewsroomMultisigs allows a manager to remove an address from the STOREFRONT list
function removeFromNewsroomMultisigs (address operator) public onlyManagerOrOwner {
newsroomMultisigList[operator] = false;
}
function checkProofOfUse (address operator) public {
}
}
// File: contracts/token/ERC1404/ERC1404.sol
pragma solidity ^0.4.24;
contract ERC1404 {
/// @notice Detects if a transfer will be reverted and if so returns an appropriate reference code
/// @param from Sending address
/// @param to Receiving address
/// @param value Amount of tokens being transferred
/// @return Code by which to reference message for rejection reasoning
/// @dev Overwrite with your custom transfer restriction logic
function detectTransferRestriction (address from, address to, uint256 value) public view returns (uint8);
/// @notice Returns a human-readable message for a given restriction code
/// @param restrictionCode Identifier for looking up a message
/// @return Text showing the restriction's reasoning
/// @dev Overwrite with your custom message and restrictionCode handling
function messageForTransferRestriction (uint8 restrictionCode) public view returns (string);
}
// File: contracts/token/ERC1404/MessagesAndCodes.sol
pragma solidity ^0.4.24;
library MessagesAndCodes {
string public constant EMPTY_MESSAGE_ERROR = "Message cannot be empty string";
string public constant CODE_RESERVED_ERROR = "Given code is already pointing to a message";
string public constant CODE_UNASSIGNED_ERROR = "Given code does not point to a message";
struct Data {
mapping (uint8 => string) messages;
uint8[] codes;
}
function messageIsEmpty (string _message)
internal
pure
returns (bool isEmpty)
{
isEmpty = bytes(_message).length == 0;
}
function messageExists (Data storage self, uint8 _code)
internal
view
returns (bool exists)
{
exists = bytes(self.messages[_code]).length > 0;
}
function addMessage (Data storage self, uint8 _code, string _message)
public
returns (uint8 code)
{
require(!messageIsEmpty(_message), EMPTY_MESSAGE_ERROR);
require(!messageExists(self, _code), CODE_RESERVED_ERROR);
// enter message at code and push code onto storage
self.messages[_code] = _message;
self.codes.push(_code);
code = _code;
}
function autoAddMessage (Data storage self, string _message)
public
returns (uint8 code)
{
require(!messageIsEmpty(_message), EMPTY_MESSAGE_ERROR);
// find next available code to store the message at
code = 0;
while (messageExists(self, code)) {
code++;
}
// add message at the auto-generated code
addMessage(self, code, _message);
}
function removeMessage (Data storage self, uint8 _code)
public
returns (uint8 code)
{
require(messageExists(self, _code), CODE_UNASSIGNED_ERROR);
// find index of code
uint8 indexOfCode = 0;
while (self.codes[indexOfCode] != _code) {
indexOfCode++;
}
// remove code from storage by shifting codes in array
for (uint8 i = indexOfCode; i < self.codes.length - 1; i++) {
self.codes[i] = self.codes[i + 1];
}
self.codes.length--;
// remove message from storage
self.messages[_code] = "";
code = _code;
}
function updateMessage (Data storage self, uint8 _code, string _message)
public
returns (uint8 code)
{
require(!messageIsEmpty(_message), EMPTY_MESSAGE_ERROR);
require(messageExists(self, _code), CODE_UNASSIGNED_ERROR);
// update message at code
self.messages[_code] = _message;
code = _code;
}
}
// File: contracts/multisig/Factory.sol
pragma solidity ^0.4.19;
contract Factory {
/*
* Events
*/
event ContractInstantiation(address sender, address instantiation);
/*
* Storage
*/
mapping(address => bool) public isInstantiation;
mapping(address => address[]) public instantiations;
/*
* Public functions
*/
/// @dev Returns number of instantiations by creator.
/// @param creator Contract creator.
/// @return Returns number of instantiations by creator.
function getInstantiationCount(address creator)
public
view
returns (uint)
{
return instantiations[creator].length;
}
/*
* Internal functions
*/
/// @dev Registers contract in factory registry.
/// @param instantiation Address of contract instantiation.
function register(address instantiation)
internal
{
isInstantiation[instantiation] = true;
instantiations[msg.sender].push(instantiation);
emit ContractInstantiation(msg.sender, instantiation);
}
}
// File: contracts/interfaces/IMultiSigWalletFactory.sol
pragma solidity ^0.4.19;
interface IMultiSigWalletFactory {
function create(address[] _owners, uint _required) public returns (address wallet);
}
// File: contracts/newsroom/ACL.sol
pragma solidity ^0.4.19;
/**
@title String-based Access Control List
@author The Civil Media Company
@dev The owner of this smart-contract overrides any role requirement in the requireRole modifier,
and so it is important to use the modifier instead of checking hasRole when creating actual requirements.
The internal functions are not secured in any way and should be extended in the deriving contracts to define
requirements that suit that specific domain.
*/
contract ACL is Ownable {
event RoleAdded(address indexed granter, address indexed grantee, string role);
event RoleRemoved(address indexed granter, address indexed grantee, string role);
mapping(string => RoleData) private roles;
modifier requireRole(string role) {
require(isOwner(msg.sender) || hasRole(msg.sender, role));
_;
}
function ACL() Ownable() public {
}
/**
@notice Returns whether a specific addres has a role. Keep in mind that the owner can override role checks
@param user The address for which role check is done
@param role A constant name of the role being checked
*/
function hasRole(address user, string role) public view returns (bool) {
return roles[role].actors[user];
}
/**
@notice Returns if the specified address is owner of this smart-contract and thus can override any role checks
@param user The checked address
*/
function isOwner(address user) public view returns (bool) {
return user == owner;
}
function _addRole(address grantee, string role) internal {
roles[role].actors[grantee] = true;
emit RoleAdded(msg.sender, grantee, role);
}
function _removeRole(address grantee, string role) internal {
delete roles[role].actors[grantee];
emit RoleRemoved(msg.sender, grantee, role);
}
struct RoleData {
mapping(address => bool) actors;
}
}
// File: contracts/zeppelin-solidity/ECRecovery.sol
pragma solidity ^0.4.24;
/**
* @title Elliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param _hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param _sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 _hash, bytes _sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (_sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
v := byte(0, mload(add(_sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(_hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
function toEthSignedMessageHash(bytes32 _hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)
);
}
}
// File: contracts/newsroom/Newsroom.sol
pragma solidity ^0.4.19;
/**
@title Newsroom - Smart-contract allowing for Newsroom-like goverance and content publishing
@dev The content number 0 is created automatically and it's use is reserved for the Newsroom charter / about page
Roles that are currently supported are:
- "editor" -> which can publish content, update revisions and add/remove more editors
To post cryptographicaly pre-approved content on the Newsroom, the author's signature must be included and
"Signed"-suffix functions used. Here are the steps to generate authors signature:
1. Take the address of this newsroom and the contentHash as bytes32 and tightly pack them
2. Calculate the keccak256 of tightly packed of above
3. Take the keccak and prepend it with the standard "Ethereum signed message" preffix (see ECRecovery and Ethereum's JSON PRC).
a. Note - if you're using Ethereum's node instead of manual private key signing, that message shall be prepended by the Node itself
4. Take a keccak256 of that signed messaged
5. Verification can be done by using EC recovery algorithm using the authors signature
The verification can be seen in the internal `verifyRevisionsSignature` function.
The signing can be seen in (at)joincivil/utils package, function prepareNewsroomMessage function (and web3.eth.sign() it afterwards)
*/
contract Newsroom is ACL {
using ECRecovery for bytes32;
event ContentPublished(address indexed editor, uint indexed contentId, string uri);
event RevisionSigned(uint indexed contentId, uint indexed revisionId, address indexed author);
event RevisionUpdated(address indexed editor, uint indexed contentId, uint indexed revisionId, string uri);
event NameChanged(string newName);
string private constant ROLE_EDITOR = "editor";
mapping(uint => Content) private contents;
/*
Maps the revision hash to original contentId where it was first used.
This is used to prevent replay attacks in which a bad actor reuses an already used signature to sign a new revision of new content.
New revisions with the same contentID can reuse signatures by design -> this is to allow the Editors to change the canonical URL (eg, website change).
The end-client of those smart-contracts MUST (RFC-Like) verify the content to it's hash and the the hash to the signature.
*/
mapping(bytes32 => UsedSignature) private usedSignatures;
/**
@notice The number of different contents in this Newsroom, indexed in <0, contentCount) (exclusive) range
*/
uint public contentCount;
/**
@notice User readable name of this Newsroom
*/
string public name;
function Newsroom(string newsroomName, string charterUri, bytes32 charterHash) ACL() public {
setName(newsroomName);
publishContent(charterUri, charterHash, address(0), "");
}
/**
@notice Gets the latest revision of the content at id contentId
*/
function getContent(uint contentId) external view returns (bytes32 contentHash, string uri, uint timestamp, address author, bytes signature) {
return getRevision(contentId, contents[contentId].revisions.length - 1);
}
/**
@notice Gets a specific revision of the content. Each revision increases the ID from the previous one
@param contentId Which content to get
@param revisionId Which revision in that get content to get
*/
function getRevision(
uint contentId,
uint revisionId
) public view returns (bytes32 contentHash, string uri, uint timestamp, address author, bytes signature)
{
Content storage content = contents[contentId];
require(content.revisions.length > revisionId);
Revision storage revision = content.revisions[revisionId];
return (revision.contentHash, revision.uri, revision.timestamp, content.author, revision.signature);
}
/**
@return Number of revisions for a this content, 0 if never published
*/
function revisionCount(uint contentId) external view returns (uint) {
return contents[contentId].revisions.length;
}
/**
@notice Returns if the latest revision of the content at ID has the author's signature associated with it
*/
function isContentSigned(uint contentId) public view returns (bool) {
return isRevisionSigned(contentId, contents[contentId].revisions.length - 1);
}
/**
@notice Returns if that specific revision of the content has the author's signature
*/
function isRevisionSigned(uint contentId, uint revisionId) public view returns (bool) {
Revision[] storage revisions = contents[contentId].revisions;
require(revisions.length > revisionId);
return revisions[revisionId].signature.length != 0;
}
/**
@notice Changes the user-readable name of this contract.
This function can be only called by the owner of the Newsroom
*/
function setName(string newName) public onlyOwner() {
require(bytes(newName).length > 0);
name = newName;
emit NameChanged(name);
}
/**
@notice Adds a string-based role to the specific address, requires ROLE_EDITOR to use
*/
function addRole(address who, string role) external requireRole(ROLE_EDITOR) {
_addRole(who, role);
}
function addEditor(address who) external requireRole(ROLE_EDITOR) {
_addRole(who, ROLE_EDITOR);
}
/**
@notice Removes a string-based role from the specific address, requires ROLE_EDITOR to use
*/
function removeRole(address who, string role) external requireRole(ROLE_EDITOR) {
_removeRole(who, role);
}
/**
@notice Saves the content's URI and it's hash into this Newsroom, this creates a new Content and Revision number 0.
This function requires ROLE_EDITOR or owner to use.
The content can be cryptographicaly secured / approved by author as per signing procedure
@param contentUri Canonical URI to access the content. The client should then verify that the content has the same hash
@param contentHash Keccak256 hash of the content that is linked
@param author Author that cryptographically signs the content. Null if not signed
@param signature Cryptographic signature of the author. Empty if not signed
@return Content ID of the newly published content
@dev Emits `ContentPublished`, `RevisionUpdated` and optionaly `ContentSigned` events
*/
function publishContent(
string contentUri,
bytes32 contentHash,
address author,
bytes signature
) public requireRole(ROLE_EDITOR) returns (uint)
{
uint contentId = contentCount;
contentCount++;
require((author == address(0) && signature.length == 0) || (author != address(0) && signature.length != 0));
contents[contentId].author = author;
pushRevision(contentId, contentUri, contentHash, signature);
emit ContentPublished(msg.sender, contentId, contentUri);
return contentId;
}
/**
@notice Updates the existing content with a new revision, the content id stays the same while revision id increases afterwards
Requires that the content was first published
This function can be only called by ROLE_EDITOR or the owner.
The new revision can be left unsigned, even if the previous revisions were signed.
If the new revision is also signed, it has to be approved by the same author that has signed the first revision.
No signing can be done for articles that were published without any cryptographic author in the first place
@param signature Signature that cryptographically approves this revision. Empty if not approved
@return Newest revision id
@dev Emits `RevisionUpdated` event
*/
function updateRevision(uint contentId, string contentUri, bytes32 contentHash, bytes signature) external requireRole(ROLE_EDITOR) {
pushRevision(contentId, contentUri, contentHash, signature);
}
/**
@notice Allows to backsign a revision by the author. This is indented when an author didn't have time to access
to their private key but after time they do.
The author must be the same as the one during publishing.
If there was no author during publishing this functions allows to update the null author to a real one.
Once done, the author can't be changed afterwards
@dev Emits `RevisionSigned` event
*/
function signRevision(uint contentId, uint revisionId, address author, bytes signature) external requireRole(ROLE_EDITOR) {
require(contentId < contentCount);
Content storage content = contents[contentId];
require(content.author == address(0) || content.author == author);
require(content.revisions.length > revisionId);
if (contentId == 0) {
require(isOwner(msg.sender));
}
content.author = author;
Revision storage revision = content.revisions[revisionId];
revision.signature = signature;
require(verifyRevisionSignature(author, contentId, revision));
emit RevisionSigned(contentId, revisionId, author);
}
function verifyRevisionSignature(address author, uint contentId, Revision storage revision) internal returns (bool isSigned) {
if (author == address(0) || revision.signature.length == 0) {
require(revision.signature.length == 0);
return false;
} else {
// The url is is not used in the cryptography by design,
// the rationale is that the Author can approve the content and the Editor might need to set the url
// after the fact, or things like DNS change, meaning there would be a question of canonical url for that article
//
// The end-client of this smart-contract MUST (RFC-like) compare the authenticity of the content behind the URL with the hash of the revision
bytes32 hashedMessage = keccak256(
address(this),
revision.contentHash
).toEthSignedMessageHash();
require(hashedMessage.recover(revision.signature) == author);
// Prevent replay attacks
UsedSignature storage lastUsed = usedSignatures[hashedMessage];
require(lastUsed.wasUsed == false || lastUsed.contentId == contentId);
lastUsed.wasUsed = true;
lastUsed.contentId = contentId;
return true;
}
}
function pushRevision(uint contentId, string contentUri, bytes32 contentHash, bytes signature) internal returns (uint) {
require(contentId < contentCount);
if (contentId == 0) {
require(isOwner(msg.sender));
}
Content storage content = contents[contentId];
uint revisionId = content.revisions.length;
content.revisions.push(Revision(
contentHash,
contentUri,
now,
signature
));
if (verifyRevisionSignature(content.author, contentId, content.revisions[revisionId])) {
emit RevisionSigned(contentId, revisionId, content.author);
}
emit RevisionUpdated(msg.sender, contentId, revisionId, contentUri);
}
struct Content {
Revision[] revisions;
address author;
}
struct Revision {
bytes32 contentHash;
string uri;
uint timestamp;
bytes signature;
}
// Since all uints are 0x0 by default, we require additional bool to confirm that the contentID is not equal to content with actualy ID 0x0
struct UsedSignature {
bool wasUsed;
uint contentId;
}
}
// File: contracts/newsroom/NewsroomFactory.sol
pragma solidity ^0.4.19;
// TODO(ritave): Think of a way to not require contracts out of package
/**
@title Newsroom with Board of Directors factory
@notice This smart-contract creates the full multi-smart-contract structure of a Newsroom in a single transaction
After creation the Newsroom is owned by the Board of Directors which is represented by a multisig-gnosis-based wallet
*/
contract NewsroomFactory is Factory {
IMultiSigWalletFactory public multisigFactory;
mapping (address => address) public multisigNewsrooms;
function NewsroomFactory(address multisigFactoryAddr) public {
multisigFactory = IMultiSigWalletFactory(multisigFactoryAddr);
}
/**
@notice Creates a fully-set-up newsroom, a multisig wallet and transfers it's ownership straight to the wallet at hand
*/
function create(string name, string charterUri, bytes32 charterHash, address[] initialOwners, uint initialRequired)
public
returns (Newsroom newsroom)
{
address wallet = multisigFactory.create(initialOwners, initialRequired);
newsroom = new Newsroom(name, charterUri, charterHash);
newsroom.addEditor(msg.sender);
newsroom.transferOwnership(wallet);
multisigNewsrooms[wallet] = newsroom;
register(newsroom);
}
}
// File: contracts/proof-of-use/telemetry/TokenTelemetryI.sol
pragma solidity ^0.4.23;
interface TokenTelemetryI {
function onRequestVotingRights(address user, uint tokenAmount) external;
}
// File: contracts/token/CivilTokenController.sol
pragma solidity ^0.4.24;
contract CivilTokenController is ManagedWhitelist, ERC1404, TokenTelemetryI {
using MessagesAndCodes for MessagesAndCodes.Data;
MessagesAndCodes.Data internal messagesAndCodes;
uint8 public constant SUCCESS_CODE = 0;
string public constant SUCCESS_MESSAGE = "SUCCESS";
uint8 public constant MUST_BE_A_CIVILIAN_CODE = 1;
string public constant MUST_BE_A_CIVILIAN_ERROR = "MUST_BE_A_CIVILIAN";
uint8 public constant MUST_BE_UNLOCKED_CODE = 2;
string public constant MUST_BE_UNLOCKED_ERROR = "MUST_BE_UNLOCKED";
uint8 public constant MUST_BE_VERIFIED_CODE = 3;
string public constant MUST_BE_VERIFIED_ERROR = "MUST_BE_VERIFIED";
constructor () public {
messagesAndCodes.addMessage(SUCCESS_CODE, SUCCESS_MESSAGE);
messagesAndCodes.addMessage(MUST_BE_A_CIVILIAN_CODE, MUST_BE_A_CIVILIAN_ERROR);
messagesAndCodes.addMessage(MUST_BE_UNLOCKED_CODE, MUST_BE_UNLOCKED_ERROR);
messagesAndCodes.addMessage(MUST_BE_VERIFIED_CODE, MUST_BE_VERIFIED_ERROR);
}
function detectTransferRestriction (address from, address to, uint value)
public
view
returns (uint8)
{
// FROM is core or users that have proved use
if (coreList[from] || unlockedList[from]) {
return SUCCESS_CODE;
} else if (storefrontList[from]) { // FROM is a storefront wallet
// allow if this is going to a verified user or a core address
if (verifiedList[to] || coreList[to]) {
return SUCCESS_CODE;
} else {
// Storefront cannot transfer to wallets that have not been KYCed
return MUST_BE_VERIFIED_CODE;
}
} else if (newsroomMultisigList[from]) { // FROM is a newsroom multisig
// TO is CORE or CIVILIAN
if ( coreList[to] || civilianList[to]) {
return SUCCESS_CODE;
} else {
return MUST_BE_UNLOCKED_CODE;
}
} else if (civilianList[from]) { // FROM is a civilian
// FROM is sending TO a core address or a newsroom
if (coreList[to] || newsroomMultisigList[to]) {
return SUCCESS_CODE;
} else {
// otherwise fail
return MUST_BE_UNLOCKED_CODE;
}
} else {
// reject if FROM is not a civilian
return MUST_BE_A_CIVILIAN_CODE;
}
}
function messageForTransferRestriction (uint8 restrictionCode)
public
view
returns (string message)
{
message = messagesAndCodes.messages[restrictionCode];
}
function onRequestVotingRights(address user, uint tokenAmount) external {
addToUnlocked(user);
}
}
// File: contracts/zeppelin-solidity/token/ERC20/IERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/zeppelin-solidity/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: contracts/zeppelin-solidity/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
}
}
// File: contracts/zeppelin-solidity/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.4.24;
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string name, string symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/token/CVLToken.sol
pragma solidity ^0.4.24;
/// @title Extendable reference implementation for the ERC-1404 token
/// @dev Inherit from this contract to implement your own ERC-1404 token
contract CVLToken is ERC20, ERC20Detailed, Ownable, ERC1404 {
ERC1404 public controller;
constructor (uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
ERC1404 _controller
) public ERC20Detailed(_tokenName, _tokenSymbol, _decimalUnits) {
require(address(_controller) != address(0), "controller not provided");
controller = _controller;
_mint(msg.sender, _initialAmount); // Give the creator all initial tokens
}
modifier onlyOwner () {
require(msg.sender == owner, "not owner");
_;
}
function changeController(ERC1404 _controller) public onlyOwner {
require(address(_controller) != address(0), "controller not provided");
controller = _controller;
}
modifier notRestricted (address from, address to, uint256 value) {
require(controller.detectTransferRestriction(from, to, value) == 0, "token transfer restricted");
_;
}
function transfer (address to, uint256 value)
public
notRestricted(msg.sender, to, value)
returns (bool success)
{
success = super.transfer(to, value);
}
function transferFrom (address from, address to, uint256 value)
public
notRestricted(from, to, value)
returns (bool success)
{
success = super.transferFrom(from, to, value);
}
function detectTransferRestriction (address from, address to, uint256 value) public view returns (uint8) {
return controller.detectTransferRestriction(from, to, value);
}
function messageForTransferRestriction (uint8 restrictionCode) public view returns (string) {
return controller.messageForTransferRestriction(restrictionCode);
}
}
|
removeFromCore allows a manager to remove an address frin the CORE list
|
function removeFromCore (address operator) public onlyManagerOrOwner {
coreList[operator] = false;
}
| 2,539,986 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../Bdx/BDXShares.sol";
import "./Vesting.sol";
import "./StakingRewards.sol";
contract StakingRewardsDistribution is OwnableUpgradeable {
using SafeERC20Upgradeable for BDXShares;
uint256 public TOTAL_BDX_SUPPLY;
uint256 public constant HUNDRED_PERCENT = 100;
uint256 public constant MAX_REWARD_FEE = 1e12;
// BDX minting schedule
// They sum up to 50% of TOTAL_BDX_SUPPLY
// as this much is reserved for liquidity mining rewards
uint256 public constant BDX_MINTING_SCHEDULE_PRECISON = 1000;
uint256 public BDX_MINTING_SCHEDULE_YEAR_1;
uint256 public BDX_MINTING_SCHEDULE_YEAR_2;
uint256 public BDX_MINTING_SCHEDULE_YEAR_3;
uint256 public BDX_MINTING_SCHEDULE_YEAR_4;
uint256 public BDX_MINTING_SCHEDULE_YEAR_5;
uint256 public EndOfYear_1;
uint256 public EndOfYear_2;
uint256 public EndOfYear_3;
uint256 public EndOfYear_4;
uint256 public EndOfYear_5;
uint256 public vestingRewardRatio_percent;
uint256 public rewardFee_d12;
BDXShares public rewardsToken;
Vesting public vesting;
address public treasury;
mapping(address => uint256) public stakingRewardsWeights;
address[] public stakingRewardsAddresses;
uint256 public stakingRewardsWeightsTotal;
function initialize(
address _rewardsToken,
address _vesting,
address _treasury,
uint256 _vestingRewardRatio_percent
) external initializer {
require(_rewardsToken != address(0), "Rewards address cannot be 0");
require(_vesting != address(0), "Vesting address cannot be 0");
require(_treasury != address(0), "Treasury address cannot be 0");
require(_vestingRewardRatio_percent <= 100, "VestingRewardRatio_percent must be <= 100");
__Ownable_init();
rewardsToken = BDXShares(_rewardsToken);
vesting = Vesting(_vesting);
treasury = _treasury;
TOTAL_BDX_SUPPLY = rewardsToken.MAX_TOTAL_SUPPLY();
BDX_MINTING_SCHEDULE_YEAR_1 = (TOTAL_BDX_SUPPLY * 200) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_2 = (TOTAL_BDX_SUPPLY * 125) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_3 = (TOTAL_BDX_SUPPLY * 100) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_4 = (TOTAL_BDX_SUPPLY * 50) / BDX_MINTING_SCHEDULE_PRECISON;
BDX_MINTING_SCHEDULE_YEAR_5 = (TOTAL_BDX_SUPPLY * 25) / BDX_MINTING_SCHEDULE_PRECISON;
EndOfYear_1 = block.timestamp + 365 days;
EndOfYear_2 = block.timestamp + 2 * 365 days;
EndOfYear_3 = block.timestamp + 3 * 365 days;
EndOfYear_4 = block.timestamp + 4 * 365 days;
EndOfYear_5 = block.timestamp + 5 * 365 days;
vestingRewardRatio_percent = _vestingRewardRatio_percent;
rewardFee_d12 = 1e11; // 10%
}
// Precision 1e18 for compatibility with ERC20 token
function getRewardRatePerSecond(address _stakingRewardsAddress) external view returns (uint256) {
uint256 yearSchedule = 0;
if (block.timestamp < EndOfYear_1) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_1;
} else if (block.timestamp < EndOfYear_2) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_2;
} else if (block.timestamp < EndOfYear_3) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_3;
} else if (block.timestamp < EndOfYear_4) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_4;
} else if (block.timestamp < EndOfYear_5) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_5;
} else {
yearSchedule = 0;
}
uint256 bdxPerSecond = (yearSchedule * stakingRewardsWeights[_stakingRewardsAddress]) / (365 * 24 * 60 * 60) / stakingRewardsWeightsTotal;
return bdxPerSecond;
}
function registerPools(address[] calldata _stakingRewardsAddresses, uint256[] calldata _stakingRewardsWeights) external onlyOwner {
require(_stakingRewardsAddresses.length == _stakingRewardsWeights.length, "Pools addresses and weights lengths should be the same");
for (uint256 i = 0; i < _stakingRewardsAddresses.length; i++) {
if (stakingRewardsWeights[_stakingRewardsAddresses[i]] == 0) {
// to avoid duplicates
stakingRewardsAddresses.push(_stakingRewardsAddresses[i]);
}
stakingRewardsWeightsTotal -= stakingRewardsWeights[_stakingRewardsAddresses[i]]; // to support override
stakingRewardsWeights[_stakingRewardsAddresses[i]] = _stakingRewardsWeights[i];
stakingRewardsWeightsTotal += _stakingRewardsWeights[i];
emit PoolRegistered(_stakingRewardsAddresses[i], _stakingRewardsWeights[i]);
}
}
function unregisterPool(
address pool,
uint256 from,
uint256 to
) external onlyOwner {
to = to < stakingRewardsAddresses.length ? to : stakingRewardsAddresses.length;
stakingRewardsWeightsTotal -= stakingRewardsWeights[pool];
stakingRewardsWeights[pool] = 0;
for (uint256 i = from; i < to; i++) {
if (stakingRewardsAddresses[i] == pool) {
stakingRewardsAddresses[i] = stakingRewardsAddresses[stakingRewardsAddresses.length - 1];
stakingRewardsAddresses.pop();
emit PoolRemoved(pool);
return;
}
}
}
function collectAllRewards(uint256 from, uint256 to) external {
to = to < stakingRewardsAddresses.length ? to : stakingRewardsAddresses.length;
uint256 totalFee;
uint256 totalRewardToRelease;
uint256 totalRewardToVest;
for (uint256 i = from; i < to; i++) {
StakingRewards stakingRewards = StakingRewards(stakingRewardsAddresses[i]);
stakingRewards.updateUserReward(msg.sender);
uint256 poolReward = stakingRewards.rewards(msg.sender);
if (poolReward > 0) {
uint256 rewardFee = (poolReward * rewardFee_d12) / MAX_REWARD_FEE;
uint256 userReward = poolReward - rewardFee;
uint256 immediatelyReleasedReward = calculateImmediateReward(userReward);
uint256 vestedReward = userReward - immediatelyReleasedReward;
totalFee = totalFee + rewardFee;
totalRewardToRelease = totalRewardToRelease + immediatelyReleasedReward;
totalRewardToVest = totalRewardToVest + vestedReward;
stakingRewards.releaseReward(msg.sender, immediatelyReleasedReward, vestedReward);
}
}
if (totalRewardToRelease > 0 || totalRewardToVest > 0) {
releaseReward(msg.sender, totalRewardToRelease, totalRewardToVest);
rewardsToken.safeTransfer(treasury, totalFee);
}
}
function setVestingRewardRatio(uint256 _vestingRewardRatio) external onlyOwner {
require(_vestingRewardRatio <= 100, "VestingRewardRatio_percent must be <= 100");
vestingRewardRatio_percent = _vestingRewardRatio;
emit VestingRewardRatioSet(_vestingRewardRatio);
}
function calculateImmediateReward(uint256 reward) private view returns (uint256) {
return (reward * (HUNDRED_PERCENT - vestingRewardRatio_percent)) / HUNDRED_PERCENT;
}
function releaseReward(
address to,
uint256 rewardToRelease,
uint256 rewardToVest
) private {
rewardsToken.approve(address(vesting), rewardToVest);
vesting.schedule(to, rewardToVest);
rewardsToken.safeTransfer(to, rewardToRelease);
}
function setTreasury(address _treasury) external onlyOwner {
treasury = _treasury;
emit TreasuryChanged(_treasury);
}
function setVesting(address _vesting) external onlyOwner {
vesting = Vesting(_vesting);
emit VestingChanged(_vesting);
}
function setRewardFee_d12(uint256 _rewardFee_d12) external onlyOwner {
require(_rewardFee_d12 <= MAX_REWARD_FEE, "Reward fee cannot exceed 100%");
rewardFee_d12 = _rewardFee_d12;
emit RewardFeeChanged(_rewardFee_d12);
}
modifier onlyStakingRewards() {
require(stakingRewardsWeights[msg.sender] > 0, "Only registered staking rewards contracts allowed");
_;
}
// ---------- EVENTS ----------
event PoolRemoved(address indexed pool);
event PoolRegistered(address indexed stakingRewardsAddress, uint256 indexed stakingRewardsWeight);
event VestingRewardRatioSet(uint256 vestingRewardRatio_percent);
event TreasuryChanged(address newTreasury);
event VestingChanged(address newVesting);
event RewardFeeChanged(uint256 newRewardFee_d12);
}
|
Precision 1e18 for compatibility with ERC20 token
|
function getRewardRatePerSecond(address _stakingRewardsAddress) external view returns (uint256) {
uint256 yearSchedule = 0;
if (block.timestamp < EndOfYear_1) {
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_1;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_2;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_3;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_4;
yearSchedule = BDX_MINTING_SCHEDULE_YEAR_5;
yearSchedule = 0;
}
uint256 bdxPerSecond = (yearSchedule * stakingRewardsWeights[_stakingRewardsAddress]) / (365 * 24 * 60 * 60) / stakingRewardsWeightsTotal;
return bdxPerSecond;
}
| 2,575,788 |
/* SPDX-License-Identifier: MIT
Please go trough the Readme file.
*/
pragma solidity 0.8.10;
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
contract NFTContract is OwnableUpgradeable, ERC721EnumerableUpgradeable{
using StringsUpgradeable for uint256;
address public devs;
uint256 public cost;
uint public maxSupply;
uint whitelistLock;
uint preSaleEnd;
bool collectionIsReavealed;
uint launchBlock;
bool isRevealed;
string public unRevealedURI;
string public collection;
/**
whitelist to be use once with no more than 500 addresses
*/
address[] public whitelist;
/*
Fees per Nft.
nftId => asset => amount
this ways fees can be paid in any assets
*/
// only one nft per account
mapping(address => bool) public mintedPresale;
mapping(address => uint) public minted;
mapping(uint => string) private botUri;
function initialize(
address devs_,
uint256 price_,
uint256 maxSupply_,
uint launchBlock_,
uint presaleLen_,
uint devsQty,
string memory name_,
string memory symbol_,
string memory unRevealedUri_,
string memory collectionData_
)public initializer {
__ERC721_init(name_, symbol_);
__Ownable_init();
devs = devs_;
cost = price_;
maxSupply = maxSupply_;
launchBlock = launchBlock_;
preSaleEnd = launchBlock + presaleLen_;
unRevealedURI = unRevealedUri_;
collection = collectionData_;
mintDevsNft(devsQty);
}
function mint(uint256 _qty, address _to) external payable {
require(totalSupply() < maxSupply,"Sold Out");
require(_qty <= 5,"5 MAX");
require(maxSupply >= totalSupply()+_qty, "Not enough left");
require(block.number > launchBlock,"To soon!");
uint256 yourPrice;
if( block.number < preSaleEnd ){
require(!mintedPresale[msg.sender],"Already minted presale");
require(isWhitelist(msg.sender),"Must be white listed");
require(_qty == 1,"Only one in presale");
yourPrice = cost/4*3 + _qty;
mintedPresale[msg.sender] = true;
}
else{
require(minted[msg.sender] < 5,"Maximum reached");
yourPrice = cost * _qty;
minted[msg.sender] +=_qty;
}
require(msg.value == yourPrice,"Price not right");
payDevs();
for(uint i = 0 ; i<_qty;i++){
_safeMint(_to, totalSupply()+1);
}
}
///@notice Fill the whitelist with no more than 500 address
///@dev to call once only. will lock after
function fillWhitelist(address[] memory accounts) external onlyOwner{
require(whitelist.length <= 500,"To many whitelisted");
whitelistLock =1;
whitelist = accounts;
}
///@notice check if an account is whitelisted.
///@dev if we dont want contract to mint we should use tx.origin
function isWhitelist(address _account) public view returns(bool isWhiteListed) {
for(uint256 i = 0; i < whitelist.length;i++){
if(_account == whitelist[i]){
return true;
}
}
return false;
}
///@notice Fill the whitelist with no more than 500 address
///@param _uri ipfs foolder hash
///@dev to call once only. will lock after
function reveal(string memory _uri) external onlyOwner{
unRevealedURI = _uri;
}
/// @notice Return the token uri that was randomly atributed to that toke id
/// @param _id the token id
function tokenURI(uint256 _id) public view virtual override returns (string memory) {
return string(abi.encodePacked('https://ipfs.io/ipfs/', unRevealedURI,'/', _id.toString(),'.json'));
}
/// @notice For Opensea Royalties
function contractURI() public view returns (string memory) {
return string(abi.encodePacked('https://ipfs.io/ipfs/', collection ));
}
function updateURI(string memory _ipfshash) external onlyOwner{
collection = string(abi.encodePacked(_ipfshash));
}
/// @notice For Opensea Royalties
/// @param _qty the quantity to mint
/// @dev called upon deployment to resrve _qty
function mintDevsNft(uint256 _qty) internal {
for(uint i =0; i<_qty; i++){
_safeMint(devs,totalSupply()+1);
}
minted[devs] = _qty;
}
/// @notice For Opensea Royalties
/// @dev called upon deployment to resrve _qty
function payDevs() internal {
(bool success, ) = payable(devs).call{
value: address(this).balance
}("");
require(success);
}
receive() external payable{
// allow contract to receive ETH
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
// 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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(ERC721Upgradeable.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(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.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 {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/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
// 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 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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^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
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// 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 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);
}
|
Fill the whitelist with no more than 500 address _uri ipfs foolder hash to call once only. will lock after
|
function reveal(string memory _uri) external onlyOwner{
unRevealedURI = _uri;
}
| 205,233 |
./full_match/1/0x3CF684928c05549d8417f207aCc109D34310B52b/sources/SlouguiInu.sol
|
Mapping of ether shares of the contract. Withdraw your share.
|
function withdraw() public {
uint share = shares[msg.sender];
shares[msg.sender] = 0;
msg.sender.transfer(share);
}
| 17,070,271 |
./full_match/1/0x5D8d9F5b96f4438195BE9b99eee6118Ed4304286/sources/contracts/Blacksmith.sol
|
add a new pool for shield mining
|
function addPool(address _lpToken, uint256 _weight) public override onlyOwner {
Pool memory pool = pools[_lpToken];
require(pool.lastUpdatedAt == 0, "Blacksmith: pool exists");
pools[_lpToken] = Pool({
weight: _weight,
accRewardsPerToken: 0,
lastUpdatedAt: block.timestamp
});
totalWeight = totalWeight.add(_weight);
poolList.push(_lpToken);
}
| 2,907,506 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import {AddressAliasHelper} from '../../standards/AddressAliasHelper.sol';
import {Lib_OVMCodec} from '../../libraries/codec/Lib_OVMCodec.sol';
import {Lib_AddressResolver} from '../../libraries/resolver/Lib_AddressResolver.sol';
/* Interface Imports */
import {ICanonicalTransactionChain} from './ICanonicalTransactionChain.sol';
import {IChainStorageContainer} from './IChainStorageContainer.sol';
/**
* @title CanonicalTransactionChain
* @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions
* which must be applied to the rollup state. It defines the ordering of rollup transactions by
* writing them to the 'CTC:batches' instance of the Chain Storage Container.
* The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the
* Sequencer will eventually append it to the rollup state.
*
* Runtime target: EVM
*/
contract CanonicalTransactionChain is
ICanonicalTransactionChain,
Lib_AddressResolver
{
/*************
* Constants *
*************/
// L2 tx gas-related
uint256 public constant MIN_ROLLUP_TX_GAS = 100000;
uint256 public constant MAX_ROLLUP_TX_SIZE = 50000;
// The approximate cost of calling the enqueue function
uint256 public enqueueGasCost;
// The ratio of the cost of L1 gas to the cost of L2 gas
uint256 public l2GasDiscountDivisor;
// The amount of L2 gas which can be forwarded to L2 without spam prevention via 'gas burn'.
// Calculated as the product of l2GasDiscountDivisor * enqueueGasCost.
// See comments in enqueue() for further detail.
uint256 public enqueueL2GasPrepaid;
// Encoding-related (all in bytes)
uint256 internal constant BATCH_CONTEXT_SIZE = 16;
uint256 internal constant BATCH_CONTEXT_LENGTH_POS = 12;
uint256 internal constant BATCH_CONTEXT_START_POS = 15;
uint256 internal constant TX_DATA_HEADER_SIZE = 3;
uint256 internal constant BYTES_TILL_TX_DATA = 65;
/*************
* Variables *
*************/
uint256 public maxTransactionGasLimit;
/***************
* Queue State *
***************/
uint40 private _nextQueueIndex; // index of the first queue element not yet included
Lib_OVMCodec.QueueElement[] queueElements;
/***************
* Constructor *
***************/
constructor(
address _libAddressManager,
uint256 _maxTransactionGasLimit,
uint256 _l2GasDiscountDivisor,
uint256 _enqueueGasCost
) Lib_AddressResolver(_libAddressManager) {
maxTransactionGasLimit = _maxTransactionGasLimit;
l2GasDiscountDivisor = _l2GasDiscountDivisor;
enqueueGasCost = _enqueueGasCost;
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
}
/**********************
* Function Modifiers *
**********************/
/**
* Modifier to enforce that, if configured, only the Burn Admin may
* successfully call a method.
*/
modifier onlyBurnAdmin() {
require(
msg.sender == libAddressManager.owner(),
'Only callable by the Burn Admin.'
);
_;
}
/*******************************
* Authorized Setter Functions *
*******************************/
/**
* Allows the Burn Admin to update the parameters which determine the amount of gas to burn.
* The value of enqueueL2GasPrepaid is immediately updated as well.
*/
function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost)
external
onlyBurnAdmin
{
enqueueGasCost = _enqueueGasCost;
l2GasDiscountDivisor = _l2GasDiscountDivisor;
// See the comment in enqueue() for the rationale behind this formula.
enqueueL2GasPrepaid = _l2GasDiscountDivisor * _enqueueGasCost;
emit L2GasParamsUpdated(
l2GasDiscountDivisor,
enqueueGasCost,
enqueueL2GasPrepaid
);
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches() public view returns (IChainStorageContainer) {
return IChainStorageContainer(resolve('ChainStorageContainer-CTC-batches'));
}
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue() public view returns (IChainStorageContainer) {
return IChainStorageContainer(resolve('ChainStorageContainer-CTC-queue'));
}
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() public view returns (uint256 _totalElements) {
(uint40 totalElements, , , ) = _getBatchExtraData();
return uint256(totalElements);
}
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() public view returns (uint256 _totalBatches) {
return batches().length();
}
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex() public view returns (uint40) {
return _nextQueueIndex;
}
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp() public view returns (uint40) {
(, , uint40 lastTimestamp, ) = _getBatchExtraData();
return lastTimestamp;
}
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber() public view returns (uint40) {
(, , , uint40 lastBlockNumber) = _getBatchExtraData();
return lastBlockNumber;
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(uint256 _index)
public
view
returns (Lib_OVMCodec.QueueElement memory _element)
{
return queueElements[_index];
}
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements() public view returns (uint40) {
return uint40(queueElements.length) - _nextQueueIndex;
}
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength() public view returns (uint40) {
return uint40(queueElements.length);
}
/**
* Adds a transaction to the queue.
* @param _target Target L2 contract to send the transaction to.
* @param _gasLimit Gas limit for the enqueued L2 transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
) external {
require(
_data.length <= MAX_ROLLUP_TX_SIZE,
'Transaction data size exceeds maximum for rollup transaction.'
);
require(
_gasLimit <= maxTransactionGasLimit,
'Transaction gas limit exceeds maximum for rollup transaction.'
);
require(
_gasLimit >= MIN_ROLLUP_TX_GAS,
'Transaction gas limit too low to enqueue.'
);
// Transactions submitted to the queue lack a method for paying gas fees to the Sequencer.
// So we need to prevent spam attacks by ensuring that the cost of enqueueing a transaction
// from L1 to L2 is not underpriced. For transaction with a high L2 gas limit, we do this by
// burning some extra gas on L1. Of course there is also some intrinsic cost to enqueueing a
// transaction, so we want to make sure not to over-charge (by burning too much L1 gas).
// Therefore, we define 'enqueueL2GasPrepaid' as the L2 gas limit above which we must burn
// additional gas on L1. This threshold is the product of two inputs:
// 1. enqueueGasCost: the base cost of calling this function.
// 2. l2GasDiscountDivisor: the ratio between the cost of gas on L1 and L2. This is a
// positive integer, meaning we assume L2 gas is always less costly.
// The calculation below for gasToConsume can be seen as converting the difference (between
// the specified L2 gas limit and the prepaid L2 gas limit) to an L1 gas amount.
if (_gasLimit > enqueueL2GasPrepaid) {
uint256 gasToConsume = (_gasLimit - enqueueL2GasPrepaid) /
l2GasDiscountDivisor;
uint256 startingGas = gasleft();
// Although this check is not necessary (burn below will run out of gas if not true), it
// gives the user an explicit reason as to why the enqueue attempt failed.
require(
startingGas > gasToConsume,
'Insufficient gas for L2 rate limiting burn.'
);
uint256 i;
while (startingGas - gasleft() < gasToConsume) {
i++;
}
}
// Apply an aliasing unless msg.sender == tx.origin. This prevents an attack in which a
// contract on L1 has the same address as a contract on L2 but doesn't have the same code.
// We can safely ignore this for EOAs because they're guaranteed to have the same "code"
// (i.e. no code at all). This also makes it possible for users to interact with contracts
// on L2 even when the Sequencer is down.
address sender;
if (msg.sender == tx.origin) {
sender = msg.sender;
} else {
sender = AddressAliasHelper.applyL1ToL2Alias(msg.sender);
}
bytes32 transactionHash = keccak256(
abi.encode(sender, _target, _gasLimit, _data)
);
queueElements.push(
Lib_OVMCodec.QueueElement({
transactionHash: transactionHash,
timestamp: uint40(block.timestamp),
blockNumber: uint40(block.number)
})
);
uint256 queueIndex = queueElements.length - 1;
emit TransactionEnqueued(
sender,
_target,
_gasLimit,
_data,
queueIndex,
block.timestamp
);
}
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch() external {
uint40 shouldStartAtElement;
uint24 totalElementsToAppend;
uint24 numContexts;
assembly {
shouldStartAtElement := shr(216, calldataload(4))
totalElementsToAppend := shr(232, calldataload(9))
numContexts := shr(232, calldataload(12))
}
require(
shouldStartAtElement == getTotalElements(),
'Actual batch start index does not match expected start index.'
);
require(
msg.sender == resolve('OVM_Sequencer'),
'Function can only be called by the Sequencer.'
);
uint40 nextTransactionPtr = uint40(
BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts
);
require(
msg.data.length >= nextTransactionPtr,
'Not enough BatchContexts provided.'
);
// Counter for number of sequencer transactions appended so far.
uint32 numSequencerTransactions = 0;
// Cache the _nextQueueIndex storage variable to a temporary stack variable.
// This is safe as long as nothing reads or writes to the storage variable
// until it is updated by the temp variable.
uint40 nextQueueIndex = _nextQueueIndex;
BatchContext memory curContext;
for (uint32 i = 0; i < numContexts; i++) {
BatchContext memory nextContext = _getBatchContext(i);
// Now we can update our current context.
curContext = nextContext;
// Process sequencer transactions first.
numSequencerTransactions += uint32(curContext.numSequencedTransactions);
// Now process any subsequent queue transactions.
nextQueueIndex += uint40(curContext.numSubsequentQueueTransactions);
}
require(
nextQueueIndex <= queueElements.length,
'Attempted to append more elements than are available in the queue.'
);
// Generate the required metadata that we need to append this batch
uint40 numQueuedTransactions = totalElementsToAppend -
numSequencerTransactions;
uint40 blockTimestamp;
uint40 blockNumber;
if (curContext.numSubsequentQueueTransactions == 0) {
// The last element is a sequencer tx, therefore pull timestamp and block number from
// the last context.
blockTimestamp = uint40(curContext.timestamp);
blockNumber = uint40(curContext.blockNumber);
} else {
// The last element is a queue tx, therefore pull timestamp and block number from the
// queue element.
// curContext.numSubsequentQueueTransactions > 0 which means that we've processed at
// least one queue element. We increment nextQueueIndex after processing each queue
// element, so the index of the last element we processed is nextQueueIndex - 1.
Lib_OVMCodec.QueueElement memory lastElement = queueElements[
nextQueueIndex - 1
];
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
}
// Cache the previous blockhash to ensure all transaction data can be retrieved efficiently.
_appendBatch(
blockhash(block.number - 1),
totalElementsToAppend,
numQueuedTransactions,
blockTimestamp,
blockNumber
);
emit SequencerBatchAppended(
nextQueueIndex - numQueuedTransactions,
numQueuedTransactions,
getTotalElements()
);
// Update the _nextQueueIndex storage variable.
_nextQueueIndex = nextQueueIndex;
}
/**********************
* Internal Functions *
**********************/
/**
* Returns the BatchContext located at a particular index.
* @param _index The index of the BatchContext
* @return The BatchContext at the specified index.
*/
function _getBatchContext(uint256 _index)
internal
pure
returns (BatchContext memory)
{
uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE;
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 ctxTimestamp;
uint256 ctxBlockNumber;
assembly {
numSequencedTransactions := shr(232, calldataload(contextPtr))
numSubsequentQueueTransactions := shr(
232,
calldataload(add(contextPtr, 3))
)
ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))
ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))
}
return
BatchContext({
numSequencedTransactions: numSequencedTransactions,
numSubsequentQueueTransactions: numSubsequentQueueTransactions,
timestamp: ctxTimestamp,
blockNumber: ctxBlockNumber
});
}
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Index of the next queue element.
*/
function _getBatchExtraData()
internal
view
returns (
uint40,
uint40,
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata();
uint40 totalElements;
uint40 nextQueueIndex;
uint40 lastTimestamp;
uint40 lastBlockNumber;
// solhint-disable max-line-length
assembly {
extraData := shr(40, extraData)
totalElements := and(
extraData,
0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF
)
nextQueueIndex := shr(
40,
and(
extraData,
0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000
)
)
lastTimestamp := shr(
80,
and(
extraData,
0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000
)
)
lastBlockNumber := shr(
120,
and(
extraData,
0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000
)
)
}
// solhint-enable max-line-length
return (totalElements, nextQueueIndex, lastTimestamp, lastBlockNumber);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _nextQueueIdx Index of the next queue element.
* @param _timestamp Timestamp for the last batch.
* @param _blockNumber Block number of the last batch.
* @return Encoded batch context.
*/
function _makeBatchExtraData(
uint40 _totalElements,
uint40 _nextQueueIdx,
uint40 _timestamp,
uint40 _blockNumber
) internal pure returns (bytes27) {
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _nextQueueIdx))
extraData := or(extraData, shl(80, _timestamp))
extraData := or(extraData, shl(120, _blockNumber))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Inserts a batch into the chain of batches.
* @param _transactionRoot Root of the transaction tree for this batch.
* @param _batchSize Number of elements in the batch.
* @param _numQueuedTransactions Number of queue transactions in the batch.
* @param _timestamp The latest batch timestamp.
* @param _blockNumber The latest batch blockNumber.
*/
function _appendBatch(
bytes32 _transactionRoot,
uint256 _batchSize,
uint256 _numQueuedTransactions,
uint40 _timestamp,
uint40 _blockNumber
) internal {
IChainStorageContainer batchesRef = batches();
(uint40 totalElements, uint40 nextQueueIndex, , ) = _getBatchExtraData();
Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec
.ChainBatchHeader({
batchIndex: batchesRef.length(),
batchRoot: _transactionRoot,
batchSize: _batchSize,
prevTotalElements: totalElements,
extraData: hex''
});
emit TransactionBatchAppended(
header.batchIndex,
header.batchRoot,
header.batchSize,
header.prevTotalElements,
header.extraData
);
bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);
bytes27 latestBatchContext = _makeBatchExtraData(
totalElements + uint40(header.batchSize),
nextQueueIndex + uint40(_numQueuedTransactions),
_timestamp,
_blockNumber
);
batchesRef.push(batchHeaderHash, latestBatchContext);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.8.7;
library AddressAliasHelper {
uint160 constant offset = uint160(0x1111000000000000000000000000000000001111);
/// @notice Utility function that converts the address in the L1 that submitted a tx to
/// the inbox to the msg.sender viewed in the L2
/// @param l1Address the address in the L1 that triggered the tx to L2
/// @return l2Address L2 address as viewed in msg.sender
function applyL1ToL2Alias(address l1Address)
internal
pure
returns (address l2Address)
{
unchecked {
l2Address = address(uint160(l1Address) + offset);
}
}
/// @notice Utility function that converts the msg.sender viewed in the L2 to the
/// address in the L1 that submitted a tx to the inbox
/// @param l2Address L2 address as viewed in msg.sender
/// @return l1Address the address in the L1 that triggered the tx to L2
function undoL1ToL2Alias(address l2Address)
internal
pure
returns (address l1Address)
{
unchecked {
l1Address = address(uint160(l2Address) - offset);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import {Lib_RLPReader} from '../rlp/Lib_RLPReader.sol';
import {Lib_RLPWriter} from '../rlp/Lib_RLPWriter.sol';
import {Lib_BytesUtils} from '../utils/Lib_BytesUtils.sol';
import {Lib_Bytes32Utils} from '../utils/Lib_Bytes32Utils.sol';
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(Transaction memory _transaction)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(Transaction memory _transaction)
internal
pure
returns (bytes32)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(bytes memory _encoded)
internal
pure
returns (EVMAccount memory)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(
_encoded
);
return
EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(Lib_OVMCodec.ChainBatchHeader memory _batchHeader)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Library Imports */
import {Lib_AddressManager} from './Lib_AddressManager.sol';
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(address _libAddressManager) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(string memory _name) public view returns (address) {
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.9.0;
/* Library Imports */
import {Lib_OVMCodec} from '../../libraries/codec/Lib_OVMCodec.sol';
/* Interface Imports */
import {IChainStorageContainer} from './IChainStorageContainer.sol';
/**
* @title ICanonicalTransactionChain
*/
interface ICanonicalTransactionChain {
/**********
* Events *
**********/
event L2GasParamsUpdated(
uint256 l2GasDiscountDivisor,
uint256 enqueueGasCost,
uint256 enqueueL2GasPrepaid
);
event TransactionEnqueued(
address indexed _l1TxOrigin,
address indexed _target,
uint256 _gasLimit,
bytes _data,
uint256 indexed _queueIndex,
uint256 _timestamp
);
event QueueBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event SequencerBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event TransactionBatchAppended(
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
/***********
* Structs *
***********/
struct BatchContext {
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 timestamp;
uint256 blockNumber;
}
/*******************************
* Authorized Setter Functions *
*******************************/
/**
* Allows the Burn Admin to update the parameters which determine the amount of gas to burn.
* The value of enqueueL2GasPrepaid is immediately updated as well.
*/
function setGasParams(uint256 _l2GasDiscountDivisor, uint256 _enqueueGasCost)
external;
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches() external view returns (IChainStorageContainer);
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue() external view returns (IChainStorageContainer);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements() external view returns (uint256 _totalElements);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches() external view returns (uint256 _totalBatches);
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex() external view returns (uint40);
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(uint256 _index)
external
view
returns (Lib_OVMCodec.QueueElement memory _element);
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp() external view returns (uint40);
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber() external view returns (uint40);
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements() external view returns (uint40);
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength() external view returns (uint40);
/**
* Adds a transaction to the queue.
* @param _target Target contract to send the transaction to.
* @param _gasLimit Gas limit for the given transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
) external;
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch(
// uint40 _shouldStartAtElement,
// uint24 _totalElementsToAppend,
// BatchContext[] _contexts,
// bytes[] _transactionDataFields
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.9.0;
/**
* @title IChainStorageContainer
*/
interface IChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(bytes27 _globalMetadata) external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata() external view returns (bytes27);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length() external view returns (uint256);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(bytes32 _object) external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(bytes32 _object, bytes27 _globalMetadata) external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(uint256 _index) external view returns (bytes32);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(uint256 _index) external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(uint256 _index, bytes27 _globalMetadata)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 internal constant MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(bytes memory _in) internal pure returns (RLPItem memory) {
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({length: _in.length, ptr: ptr});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(RLPItem memory _in)
internal
pure
returns (RLPItem[] memory)
{
(uint256 listOffset, , RLPItemType itemType) = _decodeLength(_in);
require(itemType == RLPItemType.LIST_ITEM, 'Invalid RLP list value.');
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
'Provided RLP list exceeds max list length.'
);
(uint256 itemOffset, uint256 itemLength, ) = _decodeLength(
RLPItem({length: _in.length - offset, ptr: _in.ptr + offset})
);
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(bytes memory _in) internal pure returns (RLPItem[] memory) {
return readList(toRLPItem(_in));
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(RLPItem memory _in) internal pure returns (bytes memory) {
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, 'Invalid RLP bytes value.');
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(bytes memory _in) internal pure returns (bytes memory) {
return readBytes(toRLPItem(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(RLPItem memory _in)
internal
pure
returns (string memory)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(bytes memory _in) internal pure returns (string memory) {
return readString(toRLPItem(_in));
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(RLPItem memory _in) internal pure returns (bytes32) {
require(_in.length <= 33, 'Invalid RLP bytes32 value.');
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(itemType == RLPItemType.DATA_ITEM, 'Invalid RLP bytes32 value.');
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(bytes memory _in) internal pure returns (bytes32) {
return readBytes32(toRLPItem(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(RLPItem memory _in) internal pure returns (uint256) {
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(bytes memory _in) internal pure returns (uint256) {
return readUint256(toRLPItem(_in));
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(RLPItem memory _in) internal pure returns (bool) {
require(_in.length == 1, 'Invalid RLP boolean value.');
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
'Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1'
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(bytes memory _in) internal pure returns (bool) {
return readBool(toRLPItem(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(RLPItem memory _in) internal pure returns (address) {
if (_in.length == 1) {
return address(0);
}
require(_in.length == 21, 'Invalid RLP address value.');
return address(uint160(readUint256(_in)));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(bytes memory _in) internal pure returns (address) {
return readAddress(toRLPItem(_in));
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(RLPItem memory _in)
internal
pure
returns (bytes memory)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(RLPItem memory _in)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(_in.length > 0, 'RLP item cannot be null.');
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(_in.length > strLen, 'Invalid RLP short string.');
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(_in.length > lenOfStrLen, 'Invalid RLP long string length.');
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)))
}
require(_in.length > lenOfStrLen + strLen, 'Invalid RLP long string.');
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(_in.length > listLen, 'Invalid RLP short list.');
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(_in.length > lenOfListLen, 'Invalid RLP long list length.');
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)))
}
require(_in.length > lenOfListLen + listLen, 'Invalid RLP long list.');
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
) private pure returns (bytes memory) {
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask;
unchecked {
mask = 256**(32 - (_length % 32)) - 1;
}
assembly {
mstore(dest, or(and(mload(src), not(mask)), and(mload(dest), mask)))
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(RLPItem memory _in) private pure returns (bytes memory) {
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(bytes memory _in) internal pure returns (bytes memory) {
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(bytes[] memory _in) internal pure returns (bytes memory) {
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(string memory _in) internal pure returns (bytes memory) {
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(address _in) internal pure returns (bytes memory) {
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(uint256 _in) internal pure returns (bytes memory) {
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(bool _in) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(uint256 _len, uint256 _offset)
private
pure
returns (bytes memory)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = bytes1(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes1(uint8(lenLen) + uint8(_offset) + 55);
for (i = 1; i <= lenLen; i++) {
encoded[i] = bytes1(uint8((_len / (256**(lenLen - i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(uint256 _x) private pure returns (bytes memory) {
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
) private pure {
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask;
unchecked {
mask = 256**(32 - len) - 1;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly {
flattenedPtr := add(flattened, 0x20)
}
for (i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly {
listPtr := add(item, 0x20)
}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(
add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))),
_start
)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(bytes memory _bytes, uint256 _start)
internal
pure
returns (bytes memory)
{
if (_start >= _bytes.length) {
return bytes('');
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32(bytes memory _bytes) internal pure returns (bytes32) {
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes, (bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(bytes memory _bytes) internal pure returns (uint256) {
return uint256(toBytes32(_bytes));
}
function toNibbles(bytes memory _bytes) internal pure returns (bytes memory) {
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(bytes memory _bytes)
internal
pure
returns (bytes memory)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(bytes memory _bytes, bytes memory _other)
internal
pure
returns (bool)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(bytes32 _in) internal pure returns (bool) {
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(bool _in) internal pure returns (bytes32) {
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(bytes32 _in) internal pure returns (address) {
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(address _in) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_in)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* External Imports */
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string indexed _name,
address _newAddress,
address _oldAddress
);
/*************
* Variables *
*************/
mapping(bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(string memory _name, address _address)
external
onlyOwner
{
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(_name, _address, oldAddress);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(string memory _name) external view returns (address) {
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(string memory _name) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_name));
}
}
// 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;
/**
* @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;
}
}
|
Decodes an RLP-encoded account state into a useful struct. _encoded RLP-encoded account state. return Account state struct./
|
function decodeEVMAccount(bytes memory _encoded)
internal
pure
returns (EVMAccount memory)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(
_encoded
);
return
EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
| 1,596,348 |
./full_match/1/0x40430D7F790aea066574d998C8904e263Ab8AEd3/sources/@manifoldxyz/creator-core-solidity/contracts/extensions/CreatorExtensionBasic.sol
|
See {IERC165-supportsInterface}./
|
function supportsInterface(bytes4 interfaceId) public view virtual override(AdminControl, CreatorExtension, IERC165) returns (bool) {
return interfaceId == type(ICreatorExtensionBasic).interfaceId
|| super.supportsInterface(interfaceId);
}
| 2,972,820 |
./full_match/3/0xcfA9223DD9849975C286462850641A0bb5ED547b/sources/browser/The_AIM.sol
|
Tax fee liquidity fee liquidity fee
|
function collectFee(address account, uint256 amount, uint256 rate) private returns (uint256) {
uint256 transferAmount = amount;
if(_taxFee != 0){
uint256 taxFee = amount.mul(_taxFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(taxFee);
_reflectionTotal = _reflectionTotal.sub(taxFee.mul(rate));
_taxFeeTotal = _taxFeeTotal.add(taxFee);
emit RewardsDistributed(taxFee);
}
if(_liquidityFee != 0){
uint256 liquidityFee = amount.mul(_liquidityFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(liquidityFee);
_reflectionBalance[address(this)] = _reflectionBalance[address(this)].add(liquidityFee.mul(rate));
_liquidityFeeTotal = _liquidityFeeTotal.add(liquidityFee);
emit Transfer(account,address(this),liquidityFee);
}
if(_devFee != 0){
uint256 devFee = amount.mul(_devFee).div(10**(_feeDecimal + 2));
transferAmount = transferAmount.sub(devFee);
_reflectionBalance[devAddress] = _reflectionBalance[devAddress].add(devFee.mul(rate));
_devFeeTotal = _devFeeTotal.add(devFee);
emit Transfer(account,devAddress,devFee);
}
return transferAmount;
}
| 8,104,505 |
pragma solidity ^0.4.2;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint256 _totalSupply;
function totalSupply() constant returns (uint256 totalSupply);
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value
&& _value > 0
&& balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(address _from,address _to, uint256 _amount) returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
return true;
} else {
return false;
}
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function totalSupply() constant returns (uint256 totalSupply) {
totalSupply = _totalSupply;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @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() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve 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 returns (bool) {
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract NatCoin is MintableToken {
string public constant name = "NATCOIN";
string public constant symbol = "NTC";
uint256 public constant decimals = 18;
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end block, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end block where investments are allowed (both inclusive)
uint256 public startBlock;
uint256 public endBlock;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startBlock, uint256 _endBlock, uint256 _rate, address _wallet) {
require(_startBlock >= block.number);
require(_endBlock >= _startBlock);
require(_rate > 0);
require(_wallet != 0x0);
token = createTokenContract();
startBlock = _startBlock;
endBlock = _endBlock;
rate = _rate;
wallet = _wallet;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
uint256 current = block.number;
bool withinPeriod = current >= startBlock && current <= endBlock;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return block.number > endBlock;
}
}
contract NatCoinCrowdsale is Crowdsale, Ownable {
uint256 public icoSupply;
uint256 public reserveSupply;
uint256 public paymentSupply;
uint256 public coreSupply;
uint256 public reveralSupply;
uint256 public usedIcoSupply;
uint256 public usedReserveSupply;
uint256 public usedPaymentSupply;
uint256 public usedCoreSupply;
uint256 public usedReveralSupply;
function getIcoSupply() public returns(uint256) { return icoSupply; }
function getReserveSupply() public returns(uint256) { return reserveSupply; }
function getPaymentSupply() public returns(uint256) { return paymentSupply; }
function getCoreSupply() public returns(uint256) { return coreSupply; }
function getReveralSupply() public returns(uint256) { return reveralSupply; }
function getUsedReserveSupply() public returns(uint256) { return usedReserveSupply; }
function getUsedPaymentSupply() public returns(uint256) { return usedPaymentSupply; }
function getUsedCoreSupply() public returns(uint256) { return usedCoreSupply; }
function getUsedReveralSupply() public returns(uint256) { return usedReveralSupply; }
NatCoin natcoinTokenContract;
function NatCoinCrowdsale(uint256 _startBlock, uint256 _endBlock, uint256 _rate, address _wallet) Crowdsale(_startBlock, _endBlock, _rate, _wallet) {
icoSupply = 5000000 * 10**17;
reserveSupply = 8000000 * 10**17;
paymentSupply = 11000000 * 10**17;
coreSupply = 10500000 * 10**17;
reveralSupply = 500000 * 10**17;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific MintableToken token.
function createTokenContract() internal returns (MintableToken) {
return new NatCoin();
}
function claimReservedTokens(address _to, uint256 _amount) payable onlyOwner {
if (_amount > reserveSupply - usedReserveSupply) revert();
token.mint(_to, _amount);
reserveSupply += _amount;
}
function claimPaymentTokens(address _to, uint256 _amount) payable onlyOwner {
if (_amount > paymentSupply - usedPaymentSupply) revert();
token.mint(_to, _amount);
paymentSupply += _amount;
}
function claimCoreTokens(address _to, uint256 _amount) payable onlyOwner {
if (_amount > coreSupply - usedCoreSupply) revert();
natcoinTokenContract.mint(_to, _amount);
coreSupply += _amount;
}
function claimReveralTokens(address _to, uint256 _amount) payable onlyOwner {
if (_amount > reveralSupply - usedReveralSupply) revert();
natcoinTokenContract.mint(_to, _amount);
reveralSupply += _amount;
}
}
|
Function to mint tokens _to The address that will recieve the minted tokens. _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 returns (bool) {
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
| 2,483,702 |
./partial_match/1/0xb639D208Bcf0589D54FaC24E655C79EC529762B8/sources/lib/gho-core/src/contracts/facilitators/flashMinter/GhoFlashMinter.sol
|
@inheritdoc IGhoFlashMinter
|
function updateFee(uint256 newFee) external override onlyPoolAdmin {
_updateFee(newFee);
}
| 15,469,780 |
// TELEGRAM : https://t.me/meguminkittyerc20
// WEBSITE : https://www.meguminkitty.fun/
// TWITTER : https://twitter.com/MeguminKitty
//SPDX-License-Identifier: Unlicensed
pragma solidity ^0.7.4;
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;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address _owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* Allows for contract ownership along with multi-address authorization
*/
abstract contract Auth {
address internal owner;
mapping (address => bool) internal authorizations;
constructor(address _owner) {
owner = _owner;
authorizations[_owner] = true;
}
/**
* Function modifier to require caller to be contract owner
*/
modifier onlyOwner() {
require(isOwner(msg.sender), "!OWNER"); _;
}
/**
* Function modifier to require caller to be authorized
*/
modifier authorized() {
require(isAuthorized(msg.sender), "!AUTHORIZED"); _;
}
/**
* Authorize address. Owner only
*/
function authorize(address adr) public onlyOwner {
authorizations[adr] = true;
}
/**
* Remove address' authorization. Owner only
*/
function unauthorize(address adr) public onlyOwner {
authorizations[adr] = false;
}
/**
* Check if address is owner
*/
function isOwner(address account) public view returns (bool) {
return account == owner;
}
/**
* Return address' authorization status
*/
function isAuthorized(address adr) public view returns (bool) {
return authorizations[adr];
}
/**
* Transfer ownership to new address. Caller must be owner. Leaves old owner authorized
*/
function transferOwnership(address payable adr) public onlyOwner {
owner = adr;
authorizations[adr] = true;
emit OwnershipTransferred(adr);
}
event OwnershipTransferred(address owner);
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IUniswapV2Router {
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 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;
}
interface IDividendDistributor {
function setDistributionCriteria(uint256 _minPeriod, uint256 _minDistribution) external;
function setShare(address shareholder, uint256 amount) external;
function deposit() external payable;
function process(uint256 gas) external;
}
contract DividendDistributor is IDividendDistributor {
using SafeMath for uint256;
address _token;
struct Share {
uint256 amount;
uint256 totalExcluded;
uint256 totalRealised;
}
address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // 0xc778417e063141139fce010982780140aa0cd5ab ropsten
IUniswapV2Router router; // 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 MAINNET WETH
address[] shareholders;
mapping (address => uint256) shareholderIndexes;
mapping (address => uint256) shareholderClaims;
mapping (address => Share) public shares;
uint256 public totalShares;
uint256 public totalDividends;
uint256 public totalDistributed;
uint256 public dividendsPerShare;
uint256 public dividendsPerShareAccuracyFactor = 10 ** 36;
uint256 public minPeriod = 24 hours;
uint256 public minDistribution = 1 * (10 ** 18) / (100); // Minimum sending is 0.01 ETH
uint256 currentIndex;
bool initialized;
modifier initialization() {
require(!initialized);
_;
initialized = true;
}
modifier onlyToken() {
require(msg.sender == _token); _;
}
constructor (address _router) {
router = _router != address(0)
? IUniswapV2Router(_router)
: IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
_token = msg.sender;
}
function setDistributionCriteria(uint256 _minPeriod, uint256 _minDistribution) external override onlyToken {
minPeriod = _minPeriod;
minDistribution = _minDistribution;
}
function setShare(address shareholder, uint256 amount) external override onlyToken {
if(shares[shareholder].amount > 0){
distributeDividend(shareholder);
}
if(amount > 0 && shares[shareholder].amount == 0){
addShareholder(shareholder);
}else if(amount == 0 && shares[shareholder].amount > 0){
removeShareholder(shareholder);
}
totalShares = totalShares.sub(shares[shareholder].amount).add(amount);
shares[shareholder].amount = amount;
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
}
function deposit() external payable override onlyToken {
totalDividends = totalDividends.add(msg.value);
dividendsPerShare = dividendsPerShare.add(dividendsPerShareAccuracyFactor.mul(msg.value).div(totalShares));
}
function process(uint256 gas) external override onlyToken {
uint256 shareholderCount = shareholders.length;
if(shareholderCount == 0) { return; }
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
while(gasUsed < gas && iterations < shareholderCount) {
if(currentIndex >= shareholderCount){
currentIndex = 0;
}
if(shouldDistribute(shareholders[currentIndex])){
distributeDividend(shareholders[currentIndex]);
}
gasUsed = gasUsed.add(gasLeft.sub(gasleft()));
gasLeft = gasleft();
currentIndex++;
iterations++;
}
}
function shouldDistribute(address shareholder) internal view returns (bool) {
return shareholderClaims[shareholder] + minPeriod < block.timestamp
&& getUnpaidEarnings(shareholder) > minDistribution;
}
function TimeLeftToDistribute(address shareholder) public view returns (uint256) {
uint256 timeleft;
if (shareholderClaims[shareholder] + minPeriod > block.timestamp) {
timeleft = shareholderClaims[shareholder] + minPeriod - block.timestamp;
} else {
timeleft = 0;
}
return timeleft;
}
function distributeDividend(address shareholder) public payable {
if(shares[shareholder].amount == 0){ return; }
uint256 amount = getUnpaidEarnings(shareholder);
if(amount > 0){
totalDistributed = totalDistributed.add(amount);
payable(shareholder).transfer(amount);
shareholderClaims[shareholder] = block.timestamp;
shares[shareholder].totalRealised = shares[shareholder].totalRealised.add(amount);
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
}
}
function claimDividend() external {
distributeDividend(msg.sender);
}
function getUnpaidEarnings(address shareholder) public view returns (uint256) {
if(shares[shareholder].amount == 0){ return 0; }
uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount);
uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded;
if(shareholderTotalDividends <= shareholderTotalExcluded){ return 0; }
return shareholderTotalDividends.sub(shareholderTotalExcluded);
}
function getCumulativeDividends(uint256 share) internal view returns (uint256) {
return share.mul(dividendsPerShare).div(dividendsPerShareAccuracyFactor);
}
function addShareholder(address shareholder) internal {
shareholderIndexes[shareholder] = shareholders.length;
shareholders.push(shareholder);
}
function removeShareholder(address shareholder) internal {
shareholders[shareholderIndexes[shareholder]] = shareholders[shareholders.length-1];
shareholderIndexes[shareholders[shareholders.length-1]] = shareholderIndexes[shareholder];
shareholders.pop();
}
}
contract KittyMegumin is IERC20, Auth {
using SafeMath for uint256;
address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address DEAD = 0x000000000000000000000000000000000000dEaD;
address ZERO = 0x0000000000000000000000000000000000000000;
string constant _name = "Megumin Kitty";
string constant _symbol = "$MEGUMIN";
uint8 constant _decimals = 18;
uint256 _totalSupply = 100_000_000_000_000 * (10 ** _decimals);
uint256 public _maxBuyTxAmount = _totalSupply * 1/100;
uint256 public _maxSellTxAmount = _maxBuyTxAmount;
uint256 public _maxWalletAmount = _maxBuyTxAmount;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
mapping (address => bool) public automatedMarketMakerPairs;
mapping (address => uint256) private _buyMap;
mapping (address => bool) public isFeeExempt;
mapping (address => bool) public isMaxWalletExempt;
mapping (address => bool) public isTxLimitExempt;
mapping (address => bool) public isDividendExempt;
uint256 public reflectionFee = 200;
uint256 public marketingFee = 800;
uint256 public liquidityFee = 100;
uint256 public devFee = 150;
// 25% fee
uint256 public constant AD_24HR_reflectionFee = 400;
uint256 public constant AD_24HR_marketingFee = 1800; // 18%
uint256 public constant AD_24HR_liquidityFee = 100;
uint256 public constant AD_24HR_devFee = 200; // 2%
uint256 public totalFee = reflectionFee.add(marketingFee).add(liquidityFee).add(devFee);
uint256 public AD_24HR_totalFee = AD_24HR_reflectionFee.add(AD_24HR_marketingFee).add(AD_24HR_liquidityFee).add(AD_24HR_devFee);
address public marketingFeeReceiver;
address public devFeeReceiver;
address public liquidityFeeReceiver;
IUniswapV2Router public router;
address public pair;
event SwapETHForTokens(
uint256 amountIn,
address[] path
);
event SwapTokensForETH(
uint256 amountIn,
address[] path
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
DividendDistributor public distributor;
uint256 distributorGas = 500000;
bool public swapEnabled = true;
uint256 public swapThreshold = _totalSupply / 20000; // 0.005%
bool inSwap;
modifier swapping() { inSwap = true; _; inSwap = false; }
bool public tradingOn = false;
constructor () Auth(msg.sender) {
router = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
_allowances[address(this)][address(router)] = uint256(-1);
pair = IUniswapV2Factory(router.factory()).createPair(WETH, address(this));
distributor = new DividendDistributor(address(router));
isFeeExempt[msg.sender] = true;
isFeeExempt[address(this)] = true;
isFeeExempt[DEAD] = true;
isFeeExempt[marketingFeeReceiver] = true;
isTxLimitExempt[msg.sender] = true;
isTxLimitExempt[address(this)] = true;
isTxLimitExempt[DEAD] = true;
isTxLimitExempt[marketingFeeReceiver] = true;
isMaxWalletExempt[msg.sender] = true;
isMaxWalletExempt[pair] = true;
isMaxWalletExempt[address(this)] = true;
isMaxWalletExempt[DEAD] = true;
isMaxWalletExempt[marketingFeeReceiver] = true;
isDividendExempt[pair] = true;
isDividendExempt[address(this)] = true;
isDividendExempt[DEAD] = true;
isDividendExempt[marketingFeeReceiver] = true;
marketingFeeReceiver = 0x8A722DE0803e0048E807A0BEe0f0a179d7EDB4c3;
devFeeReceiver = 0x4cFB05091aEBbDF0a74F5d843a9D6E988FC563a2;
liquidityFeeReceiver = msg.sender;
automatedMarketMakerPairs[pair] = true;
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
receive() external payable { }
function getUnpaidEarnings(address shareholder) public view returns (uint256) {
return distributor.getUnpaidEarnings(shareholder);
}
function claimDividend() public {
distributor.claimDividend();
}
function TimeLeftToDistribute(address shareholder) public view returns (uint256) {
return distributor.TimeLeftToDistribute(shareholder);
}
function totalShares() public view returns (uint256) {
return distributor.totalShares();
}
function totalDividends() public view returns (uint256) {
return distributor.totalDividends();
}
function totalDistributed() public view returns (uint256) {
return distributor.totalDistributed();
}
function dividendsPerShare() public view returns (uint256) {
return distributor.dividendsPerShare();
}
function minDistribution() public view returns (uint256) {
return distributor.minDistribution();
}
// making functions to get distributor info for website
function totalSupply() external view override returns (uint256) { return _totalSupply; }
function decimals() external pure override returns (uint8) { return _decimals; }
function symbol() external pure override returns (string memory) { return _symbol; }
function name() external pure override returns (string memory) { return _name; }
function getOwner() external view override returns (address) { return owner; }
function balanceOf(address account) public view override returns (uint256) { return _balances[account]; }
function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; }
function approve(address spender, uint256 amount) public override returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function approveMax(address spender) external returns (bool) {
return approve(spender, uint256(-1));
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
return _transferFrom(msg.sender, recipient, amount);
}
// Turn on trading (it can't be turend off again)
function enableTrading() public onlyOwner {
if (!tradingOn) {
tradingOn = true;
}
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if(_allowances[sender][msg.sender] != uint256(-1)){
_allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance");
}
return _transferFrom(sender, recipient, amount);
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if (sender != owner && recipient != owner) {
require(tradingOn, "Trading is not turned on yet");
}
if(inSwap){ return _basicTransfer(sender, recipient, amount); }
checkTxLimit(sender, recipient, amount);
if(shouldSwapBack()){ swapBack(); }
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
uint256 amountReceived = shouldTakeFee(sender) ? takeFee(sender, amount) : amount;
_balances[recipient] = _balances[recipient].add(amountReceived);
if(!isDividendExempt[sender]){ try distributor.setShare(sender, _balances[sender]) {} catch {} }
if(!isDividendExempt[recipient]){ try distributor.setShare(recipient, _balances[recipient]) {} catch {} }
try distributor.process(distributorGas) {} catch {}
if (_isBuy(sender) && _buyMap[recipient] == 0) {
_buyMap[recipient] = block.timestamp;
}
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
_balances[recipient] = _balances[recipient].add(amount);
checkWalletLimit(recipient);
emit Transfer(sender, recipient, amount);
return true;
}
function checkTxLimit(address sender, address recipient, uint256 amount) internal view {
if (automatedMarketMakerPairs[sender]) {
if (!isTxLimitExempt[recipient]) {
require(amount <= _maxBuyTxAmount, "TX Limit Exceeded");
}
if (!isMaxWalletExempt[recipient]) {
require((_balances[recipient] + amount) <= _maxWalletAmount, "Wallet Amount Limit Exceeded");
}
} else if (automatedMarketMakerPairs[recipient]) {
if (!isTxLimitExempt[sender]) {
require(amount <= _maxSellTxAmount);
}
}
}
function checkWalletLimit(address recipient) internal view {
require(_balances[recipient] <= _maxWalletAmount || isMaxWalletExempt[recipient], "Wallet Amount Limit Exceeded");
}
function shouldTakeFee(address sender) internal view returns (bool) {
return !isFeeExempt[sender];
}
function _isBuy(address _sender) private view returns (bool) {
return _sender == pair;
}
function originalPurchase(address account) public view returns (uint256) {
return _buyMap[account];
}
// -----------------------------------------------------------------------------------
function takeFee(address sender, uint256 amount) internal returns (uint256) {
// ADD ANTI DUMP
uint256 feeAmount;
if (originalPurchase(sender) !=0 &&
((originalPurchase(sender) + (10 minutes)) >= block.timestamp)) {
feeAmount = amount.mul(AD_24HR_totalFee).div(10000);
_balances[address(this)] = _balances[address(this)].add(feeAmount);
emit Transfer(sender, address(this), feeAmount);
}
else {
feeAmount = amount.mul(totalFee).div(10000);
_balances[address(this)] = _balances[address(this)].add(feeAmount);
emit Transfer(sender, address(this), feeAmount);
}
return amount.sub(feeAmount);
}
function shouldSwapBack() internal view returns (bool) {
return msg.sender != pair
&& !inSwap
&& swapEnabled
&& _balances[address(this)] >= swapThreshold;
}
function swapBack() internal swapping {
uint256 amountToSwap = _balances[address(this)];
uint256 amountReflection = amountToSwap.mul(reflectionFee).div(totalFee);
uint256 amountMarketing = amountToSwap.mul(marketingFee).div(totalFee);
uint256 amountDev = amountToSwap.mul(devFee).div(totalFee);
uint256 amountLiquidity = amountToSwap.mul(liquidityFee).div(totalFee);
swapAndSendToMarketing(amountMarketing);
swapAndSendToRef(amountReflection);
swapAndLiquify(amountLiquidity);
swapAndSendToDev(amountDev);
}
// -----------------------------------------------------------------------------------
function swapAndSendToMarketing(uint256 tokens) private {
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(tokens);
uint256 newETHBalance = address(this).balance.sub(initialETHBalance);
payable(marketingFeeReceiver).transfer(newETHBalance);
}
function swapAndSendToDev(uint256 tokens) private {
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(tokens);
uint256 newETHBalance = address(this).balance.sub(initialETHBalance);
payable(devFeeReceiver).transfer(newETHBalance);
}
function swapAndSendToRef(uint256 tokens) private {
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(tokens);
uint256 newETHBalance = address(this).balance.sub(initialETHBalance);
try distributor.deposit{value: newETHBalance}() {} catch {}
}
function swapAndLiquify(uint256 tokens) private {
// split the contract balance into halves
uint256 half = tokens.div(2);
uint256 otherhalf = tokens.sub(half);
uint256 initialBalance = address(this).balance;
swapTokensForEth(half);
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherhalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherhalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
// make the swap
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
emit SwapTokensForETH(tokenAmount, path);
}
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private {
router.addLiquidityETH{value: bnbAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
liquidityFeeReceiver,
block.timestamp
);
}
function setTx_Wallet_Limits(uint256 maxBuyTxAmount, uint256 maxSellTxAmount, uint256 maxWalletAmt) external authorized {
require(maxBuyTxAmount >= 500000, "Maxbuy cant be below 0.5%");
require(maxSellTxAmount >= 500000, "Maxsell cant be below 0.5%");
_maxBuyTxAmount = maxBuyTxAmount * (10 ** _decimals);
_maxSellTxAmount = maxSellTxAmount * (10 ** _decimals);
_maxWalletAmount = maxWalletAmt * (10 ** _decimals);
}
function setIsDividendExempt(address holder, bool exempt) external authorized {
require(holder != address(this) && holder != pair);
isDividendExempt[holder] = exempt;
if(exempt){
distributor.setShare(holder, 0);
}else{
distributor.setShare(holder, _balances[holder]);
}
}
function setIsFeeExempt(address holder, bool exempt) external authorized {
isFeeExempt[holder] = exempt;
}
function setIsTxLimitExempt(address holder, bool exempt) external authorized {
isTxLimitExempt[holder] = exempt;
}
function setIsMaxWalletExempt(address holder, bool exempt) external authorized {
isMaxWalletExempt[holder] = exempt;
}
function setFees(uint256 _reflectionFee, uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external authorized {
reflectionFee = _reflectionFee;
marketingFee = _marketingFee;
liquidityFee = _liquidityFee;
devFee = _devFee;
totalFee = _reflectionFee.add(_marketingFee).add(_liquidityFee).add(_devFee);
}
function setWalletFeeReceivers(address _marketingFeeReceiver, address _devFeeReceiver) external authorized {
marketingFeeReceiver = _marketingFeeReceiver;
devFeeReceiver = _devFeeReceiver;
}
function setSwapBackSettings(bool _enabled, uint256 _amount) external authorized {
swapEnabled = _enabled;
swapThreshold = _amount * (10 ** _decimals);
}
function setDistributionCriteria(uint256 _minPeriod, uint256 _minDistribution) external authorized {
distributor.setDistributionCriteria(_minPeriod, _minDistribution);
}
function setDistributorSettings(uint256 gas) external authorized {
require(gas < 750000);
distributorGas = gas;
}
function getCirculatingSupply() public view returns (uint256) {
return _totalSupply.sub(balanceOf(DEAD)).sub(balanceOf(ZERO));
}
function setAutomatedMarketMakerPair(address _pair, bool value) public onlyOwner {
require(_pair != pair, "The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(_pair, value);
isMaxWalletExempt[pair] = true;
isDividendExempt[pair] = true;
}
function _setAutomatedMarketMakerPair(address _pair, bool value) private {
require(automatedMarketMakerPairs[_pair] != value, "Automated market maker pair is already set to that value");
automatedMarketMakerPairs[_pair] = value;
if(value) {
isDividendExempt[_pair] = true;
}
emit SetAutomatedMarketMakerPair(_pair, value);
}
// will only be used if the factory fucks up on launch and calculates the wrong pair.
function setpair(address _pair) public onlyOwner {
automatedMarketMakerPairs[_pair] = true;
isMaxWalletExempt[_pair] = true;
isDividendExempt[_pair] = true;
pair = _pair;
}
}
|
split the contract balance into halves add liquidity to uniswap
|
function swapAndLiquify(uint256 tokens) private {
uint256 half = tokens.div(2);
uint256 otherhalf = tokens.sub(half);
uint256 initialBalance = address(this).balance;
swapTokensForEth(half);
uint256 newBalance = address(this).balance.sub(initialBalance);
addLiquidity(otherhalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherhalf);
}
| 5,709,226 |
./partial_match/1/0xB649392D041297E75fD02fEb25E0C4C74EA8aF05/sources/LAMP.sol
|
Transfer tokens from one address to another. Note that while this function emits an Approval event, this is not required as per the specification, and other compliant implementations may not emit the event. from address The address which you want to send tokens from to address The address which you want to transfer to value uint256 the amount of tokens to be transferred/
|
function transferFrom(address from, address to, uint256 value) public returns (bool)
{
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
| 2,628,189 |
./full_match/43113/0xAcfe8d495E16DB307D8731e23FEa6f36e961F756/sources/GraveDigger.sol
|
No need to update leaderboard! Updates related player information on leaderboard! No need to update leaderboard!
|
function updateLeaderboard(Player memory player) private {
uint256 score = player.score;
uint256 leaderboardLength = leaderboard.length;
if(leaderboardLength == 0) {
return;
}
uint256 i = 0;
for(i; i < leaderboardLength; i++) {
if(leaderboard[i].account == player.account) {
break;
}
}
if(i >= 0 && i < leaderboardLength) {
leaderboard[i] = player;
}
i = 0;
if(leaderboardLength < 2) {
return;
}
for(i; i < leaderboardLength; i++) {
if(leaderboard[i].score < score) {
break;
}
}
for(uint256 j = leaderboardLength - 1; j > i; j--) {
leaderboard[j] = leaderboard[j - 1];
}
leaderboard[i] = player;
}
| 7,176,440 |
pragma solidity ^0.4.15;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
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 constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/*
* Contract that is working with ERC223 tokens
* This is an implementation of ContractReceiver provided here:
* https://github.com/Dexaran/ERC223-token-standard/blob/Recommended/Receiver_Interface.sol
*/
contract ContractReceiver {
function tokenFallback(address _from, uint _value, bytes _data);
}
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount)
returns(bool);
}
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController {
controller = _newController;
}
}
/// @title SpecToken - Crowdfunding code for the Spectre.ai Token Sale
/// @author Parthasarathy Ramanujam
contract SpectreSubscriberToken is StandardToken, Pausable, TokenController {
using SafeMath for uint;
string public constant name = "SPECTRE SUBSCRIBER TOKEN";
string public constant symbol = "SXS";
uint256 public constant decimals = 18;
uint256 constant public TOKENS_AVAILABLE = 240000000 * 10**decimals;
uint256 constant public BONUS_SLAB = 100000000 * 10**decimals;
uint256 constant public MIN_CAP = 5000000 * 10**decimals;
uint256 constant public MIN_FUND_AMOUNT = 1 ether;
uint256 constant public TOKEN_PRICE = 0.0005 ether;
uint256 constant public WHITELIST_PERIOD = 3 days;
address public specWallet;
address public specDWallet;
address public specUWallet;
bool public refundable = false;
bool public configured = false;
bool public tokenAddressesSet = false;
//presale start and end blocks
uint256 public presaleStart;
uint256 public presaleEnd;
//main sale start and end blocks
uint256 public saleStart;
uint256 public saleEnd;
//discount end block for main sale
uint256 public discountSaleEnd;
//whitelisting
mapping(address => uint256) public whitelist;
uint256 constant D160 = 0x0010000000000000000000000000000000000000000;
//bonus earned
mapping(address => uint256) public bonus;
event Refund(address indexed _to, uint256 _value);
event ContractFunded(address indexed _from, uint256 _value, uint256 _total);
event Refundable();
event WhiteListSet(address indexed _subscriber, uint256 _value);
event OwnerTransfer(address indexed _from, address indexed _to, uint256 _value);
modifier isRefundable() {
require(refundable);
_;
}
modifier isNotRefundable() {
require(!refundable);
_;
}
modifier isTransferable() {
require(tokenAddressesSet);
require(getNow() > saleEnd);
require(totalSupply >= MIN_CAP);
_;
}
modifier onlyWalletOrOwner() {
require(msg.sender == owner || msg.sender == specWallet);
_;
}
//@notice function to initilaize the token contract
//@notice _specWallet - The wallet that receives the proceeds from the token sale
//@notice _specDWallet - Wallet that would receive tokens chosen for dividend
//@notice _specUWallet - Wallet that would receive tokens chosen for utility
function SpectreSubscriberToken(address _specWallet) {
require(_specWallet != address(0));
specWallet = _specWallet;
pause();
}
//@notice Fallback function that accepts the ether and allocates tokens to
//the msg.sender corresponding to msg.value
function() payable whenNotPaused public {
require(msg.value >= MIN_FUND_AMOUNT);
if(getNow() >= presaleStart && getNow() <= presaleEnd) {
purchasePresale();
} else if (getNow() >= saleStart && getNow() <= saleEnd) {
purchase();
} else {
revert();
}
}
//@notice function to be used for presale purchase
function purchasePresale() internal {
//Only check whitelist for the first 3 days of presale
if (getNow() < (presaleStart + WHITELIST_PERIOD)) {
require(whitelist[msg.sender] > 0);
//Accept if the subsciber 95% to 120% of whitelisted amount
uint256 minAllowed = whitelist[msg.sender].mul(95).div(100);
uint256 maxAllowed = whitelist[msg.sender].mul(120).div(100);
require(msg.value >= minAllowed && msg.value <= maxAllowed);
//remove the address from whitelist
whitelist[msg.sender] = 0;
}
uint256 numTokens = msg.value.mul(10**decimals).div(TOKEN_PRICE);
uint256 bonusTokens = 0;
if(totalSupply < BONUS_SLAB) {
//Any portion of tokens less than BONUS_SLAB are eligable for 33% bonus, otherwise 22% bonus
uint256 remainingBonusSlabTokens = SafeMath.sub(BONUS_SLAB, totalSupply);
uint256 bonusSlabTokens = Math.min256(remainingBonusSlabTokens, numTokens);
uint256 nonBonusSlabTokens = SafeMath.sub(numTokens, bonusSlabTokens);
bonusTokens = bonusSlabTokens.mul(33).div(100);
bonusTokens = bonusTokens.add(nonBonusSlabTokens.mul(22).div(100));
} else {
//calculate 22% bonus for tokens purchased on presale
bonusTokens = numTokens.mul(22).div(100);
}
//
numTokens = numTokens.add(bonusTokens);
bonus[msg.sender] = bonus[msg.sender].add(bonusTokens);
//transfer money to Spectre MultisigWallet (could be msg.value)
specWallet.transfer(msg.value);
totalSupply = totalSupply.add(numTokens);
require(totalSupply <= TOKENS_AVAILABLE);
balances[msg.sender] = balances[msg.sender].add(numTokens);
//fire the event notifying the transfer of tokens
Transfer(0, msg.sender, numTokens);
}
//@notice function to be used for mainsale purchase
function purchase() internal {
uint256 numTokens = msg.value.mul(10**decimals).div(TOKEN_PRICE);
uint256 bonusTokens = 0;
if(getNow() <= discountSaleEnd) {
//calculate 11% bonus for tokens purchased on discount period
bonusTokens = numTokens.mul(11).div(100);
}
numTokens = numTokens.add(bonusTokens);
bonus[msg.sender] = bonus[msg.sender].add(bonusTokens);
//transfer money to Spectre MultisigWallet
specWallet.transfer(msg.value);
totalSupply = totalSupply.add(numTokens);
require(totalSupply <= TOKENS_AVAILABLE);
balances[msg.sender] = balances[msg.sender].add(numTokens);
//fire the event notifying the transfer of tokens
Transfer(0, msg.sender, numTokens);
}
//@notice Function reports the number of tokens available for sale
function numberOfTokensLeft() constant returns (uint256) {
return TOKENS_AVAILABLE.sub(totalSupply);
}
//Override unpause function to only allow once configured
function unpause() onlyOwner whenPaused public {
require(configured);
paused = false;
Unpause();
}
//@notice Function to configure contract addresses
//@param `_specUWallet` - address of Utility contract
//@param `_specDWallet` - address of Dividend contract
function setTokenAddresses(address _specUWallet, address _specDWallet) onlyOwner public {
require(!tokenAddressesSet);
require(_specDWallet != address(0));
require(_specUWallet != address(0));
require(isContract(_specDWallet));
require(isContract(_specUWallet));
specUWallet = _specUWallet;
specDWallet = _specDWallet;
tokenAddressesSet = true;
if (configured) {
unpause();
}
}
//@notice Function to configure contract parameters
//@param `_startPresaleBlock` - block from when presale begins.
//@param `_endPresaleBlock` - block from when presale ends.
//@param `_saleStart` - block from when main sale begins.
//@param `_saleEnd` - block from when main sale ends.
//@param `_discountEnd` - block from when the discounts would end.
//@notice Can be called only when funding is not active and only by the owner
function configure(uint256 _presaleStart, uint256 _presaleEnd, uint256 _saleStart, uint256 _saleEnd, uint256 _discountSaleEnd) onlyOwner public {
require(!configured);
require(_presaleStart > getNow());
require(_presaleEnd > _presaleStart);
require(_saleStart > _presaleEnd);
require(_saleEnd > _saleStart);
require(_discountSaleEnd > _saleStart && _discountSaleEnd <= _saleEnd);
presaleStart = _presaleStart;
presaleEnd = _presaleEnd;
saleStart = _saleStart;
saleEnd = _saleEnd;
discountSaleEnd = _discountSaleEnd;
configured = true;
if (tokenAddressesSet) {
unpause();
}
}
//@notice Function that can be called by purchasers to refund
//@notice Used only in case the ICO isn't successful.
function refund() isRefundable public {
require(balances[msg.sender] > 0);
uint256 tokenValue = balances[msg.sender].sub(bonus[msg.sender]);
balances[msg.sender] = 0;
tokenValue = tokenValue.mul(TOKEN_PRICE).div(10**decimals);
//transfer to the requesters wallet
msg.sender.transfer(tokenValue);
Refund(msg.sender, tokenValue);
}
function withdrawEther() public isNotRefundable onlyOwner {
//In case ether is sent, even though not refundable
msg.sender.transfer(this.balance);
}
//@notice Function used for funding in case of refund.
//@notice Can be called only by the Owner or Wallet
function fundContract() public payable onlyWalletOrOwner {
//does nothing just accepts and stores the ether
ContractFunded(msg.sender, msg.value, this.balance);
}
function setRefundable() onlyOwner {
require(this.balance > 0);
require(getNow() > saleEnd);
require(totalSupply < MIN_CAP);
Refundable();
refundable = true;
}
//@notice Standard function transfer similar to ERC20 transfer with no _data .
//@notice Added due to backwards compatibility reasons .
function transfer(address _to, uint256 _value) isTransferable returns (bool success) {
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
require(_to == specDWallet || _to == specUWallet);
require(isContract(_to));
bytes memory empty;
return transferToContract(msg.sender, _to, _value, empty);
}
//@notice assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
uint256 length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//@notice function that is called when transaction target is a contract
function transferToContract(address _from, address _to, uint256 _value, bytes _data) internal returns (bool success) {
require(balanceOf(_from) >= _value);
balances[_from] = balanceOf(_from).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(_from, _value, _data);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another - needed for owner transfers
* @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 isTransferable returns (bool) {
require(_to == specDWallet || _to == specUWallet);
require(isContract(_to));
//owner can transfer tokens on behalf of users after 28 days
if (msg.sender == owner && getNow() > saleEnd + 28 days) {
OwnerTransfer(_from, _to, _value);
} else {
uint256 _allowance = allowed[_from][msg.sender];
allowed[_from][msg.sender] = _allowance.sub(_value);
}
//Now make the transfer
bytes memory empty;
return transferToContract(_from, _to, _value, empty);
}
//@notice function that is used for whitelisting an address
function setWhiteList(address _subscriber, uint256 _amount) public onlyOwner {
require(_subscriber != address(0));
require(_amount != 0);
whitelist[_subscriber] = _amount;
WhiteListSet(_subscriber, _amount);
}
// data is an array of uint256s. Each uint256 represents a address and amount.
// The 160 LSB is the address that wants to be added
// The 96 MSB is the amount of to be set for the whitelist for that address
function multiSetWhiteList(uint256[] data) public onlyOwner {
for (uint256 i = 0; i < data.length; i++) {
address addr = address(data[i] & (D160 - 1));
uint256 amount = data[i] / D160;
setWhiteList(addr, amount);
}
}
/////////////////
// TokenController interface
/////////////////
/// @notice `proxyPayment()` returns false, meaning ether is not accepted at
/// the token address, only the address of FiinuCrowdSale
/// @param _owner The address that will hold the newly created tokens
function proxyPayment(address _owner) payable returns(bool) {
return false;
}
/// @notice Notifies the controller about a transfer, for this Campaign all
/// transfers are allowed by default and no extra notifications are needed
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) returns(bool) {
return true;
}
/// @notice Notifies the controller about an approval, for this Campaign all
/// approvals are allowed by default and no extra notifications are needed
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount)
returns(bool)
{
return true;
}
function getNow() constant internal returns (uint256) {
return now;
}
}
|
function to be used for presale purchaseOnly check whitelist for the first 3 days of presaleAccept if the subsciber 95% to 120% of whitelisted amountremove the address from whitelistAny portion of tokens less than BONUS_SLAB are eligable for 33% bonus, otherwise 22% bonuscalculate 22% bonus for tokens purchased on presale
|
function purchasePresale() internal {
if (getNow() < (presaleStart + WHITELIST_PERIOD)) {
require(whitelist[msg.sender] > 0);
uint256 minAllowed = whitelist[msg.sender].mul(95).div(100);
uint256 maxAllowed = whitelist[msg.sender].mul(120).div(100);
require(msg.value >= minAllowed && msg.value <= maxAllowed);
whitelist[msg.sender] = 0;
}
uint256 numTokens = msg.value.mul(10**decimals).div(TOKEN_PRICE);
uint256 bonusTokens = 0;
if(totalSupply < BONUS_SLAB) {
uint256 remainingBonusSlabTokens = SafeMath.sub(BONUS_SLAB, totalSupply);
uint256 bonusSlabTokens = Math.min256(remainingBonusSlabTokens, numTokens);
uint256 nonBonusSlabTokens = SafeMath.sub(numTokens, bonusSlabTokens);
bonusTokens = bonusSlabTokens.mul(33).div(100);
bonusTokens = bonusTokens.add(nonBonusSlabTokens.mul(22).div(100));
bonusTokens = numTokens.mul(22).div(100);
}
bonus[msg.sender] = bonus[msg.sender].add(bonusTokens);
totalSupply = totalSupply.add(numTokens);
require(totalSupply <= TOKENS_AVAILABLE);
balances[msg.sender] = balances[msg.sender].add(numTokens);
}
| 6,478,081 |
//////// This is the official eUSD smart contract.
//// The eUSD token contract utilizes the eFIAT protocol - a not-for-profit,
//// fully transparent, publicly auditable protocol designed to migrate fiat
//// currencies to the Ethereum blockchain without banks, escrow accounts or reserves.
//// The eFIAT protocol relies on Proof of Burn, meaning any eUSD can only
//// be created by burning Ether at market value. Because Ether is denominated also
//// in USD value, the burning of Ether can be regarded as burning of US Dollars,
//// where Ether serves only as the medium of value transfer and verifiable proof
//// that actual value has ben permanently migrated and not replicated. This means
//// eUSD can never be used to redeem any Ether burned in the eUSD creation process!
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.4.24;
/**
* @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.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title 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;
}
}
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
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);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract Oracle {
function callOracle(address _src, uint256 _amount) public;
}
/**
* @title eUSD
*/
contract eUSD is Ownable, ERC20 {
using SafeMath for uint256;
string public name = "ETHUSD";
string public symbol = "EUSD";
uint8 public decimals = 18;
uint256 totalSupply_;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) internal allowed;
Oracle oracle;
event Mint(address indexed to, uint256 amount);
/**
* @dev fallback function which receives ether and sends it to oracle
**/
function () payable public {
require(address(oracle) != address(0));
require(msg.value >= 20 finney); //0.02 ETH
address(oracle).transfer(address(this).balance);
oracle.callOracle(msg.sender, msg.value);
}
/**
* @dev set new oracle address
* @param _oracle The new oracle contract address.
*/
function setOracle(address _oracle) public onlyOwner {
oracle = Oracle(_oracle);
}
/**
* @dev callback function - oracle sends amount of eUSD tokens to mint
* @param _src Mint eUSD tokens to address.
* @param _amount Amount of minted eUSD tokens
*/
function calculatedTokens(address _src, uint256 _amount) public {
require(msg.sender == address(oracle));
mint(_src, _amount);
}
/**
* @dev transfer eUSD token for a specified address
* @param _to The address to transfer to.
* @param _value The amount of eUSD tokens to be spent.
*/
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 Transfer eUSD 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 eUSD 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 eUSD 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.
* @param _spender The address which will spend the funds.
* @param _value The amount of eUSD 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 Increase the amount of eUSD 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)
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of eUSD 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 eUSD 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 eUSD 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;
}
/**
* @dev Function to mint eUSD tokens
* @param _to The address that will receive minted eUSD tokens.
* @param _amount The amount of eUSD tokens to mint.
*/
function mint(address _to, uint256 _amount) private 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 Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @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.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
}
|
fallback function which receives ether and sends it to oracle/
|
function () payable public {
require(address(oracle) != address(0));
address(oracle).transfer(address(this).balance);
oracle.callOracle(msg.sender, msg.value);
}
| 6,447,184 |
./partial_match/1/0x367C0cAdb8Cfa6a2BfF2a673ed7e7AE1EacB1Bd1/sources/FixLP.sol
|
This will return the WBNB address on BSC.
|
function WETH() external pure returns (address);
| 4,298,477 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "hardhat/console.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./BullsToTheMoonInterface.sol";
/**
* @notice ENS registry to get chainlink resolver
*/
interface ENS {
function resolver(bytes32) external view returns (Resolver);
}
/**
* @notice Chainlink resolver to get price feed proxy
*/
interface Resolver {
function addr(bytes32) external view returns (address);
}
/**
* @title Bulls (dynamic NFTs) that grow with rising price
* @author Justa Liang
*/
contract BullsToTheMoon is ERC721Enumerable, BullsToTheMoonInterface {
/// @notice Counter of bullId
uint public counter;
/// @notice ENS interface (fixed address)
ENS public ens;
/// @dev Bull's state
struct Bull {
address proxy; // which proxy of Chainlink price feed
bool closed; // position closed
int latestPrice; // latest updated price from Chainlink
int roi; // return on investment
}
/// @dev Bull's profile for viewing
struct BullProfile {
address proxy;
bool closed;
int latestPrice;
int roi;
string uri;
}
/// @dev Bull's state stored on-chain
mapping(uint => Bull) public bullStateOf;
/// @notice Emit when a bull's state changes
event BullState(
uint indexed bullId,
address indexed proxy,
bool indexed closed,
int latestPrice,
int roi
);
/**
* @dev Set name, symbol, and addresses of interactive contracts
*/
constructor(address ensRegistryAddr)
ERC721("BullsToTheMoon", "B2M")
{
counter = 0;
ens = ENS(ensRegistryAddr);
}
/**
* @dev Check the owner
*/
modifier checkOwner(uint bullId) {
require(
_isApprovedOrOwner(_msgSender(), bullId),
"wrong owner"
);
_;
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function open(uint bullId) override external checkOwner(bullId) {
Bull storage target = bullStateOf[bullId];
require(
target.closed,
"bull already opened"
);
// get current price
AggregatorV3Interface pricefeed = AggregatorV3Interface(target.proxy);
(,int currPrice,,,) = pricefeed.latestRoundData();
// update on-chain data
target.latestPrice = currPrice;
target.closed = false;
// emit bull state
emit BullState(bullId, target.proxy, false, currPrice, target.roi);
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function close(uint bullId) override external checkOwner(bullId) {
Bull storage target = bullStateOf[bullId];
require(
!target.closed,
"bull already closed"
);
// get current price
AggregatorV3Interface pricefeed = AggregatorV3Interface(target.proxy);
(,int currPrice,,,) = pricefeed.latestRoundData();
// update on-chain data
target.roi = currPrice*(10000+target.roi)/target.latestPrice-10000;
target.closed = true;
// emit bull state
emit BullState(bullId, target.proxy, true, currPrice, target.roi);
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function breed(bytes32 namehash) override external returns (uint) {
address proxyAddr = _resolve(namehash);
require(
proxyAddr != address(0),
"invalid proxy"
);
// get current price
AggregatorV3Interface pricefeed = AggregatorV3Interface(proxyAddr);
(,int currPrice,,,) = pricefeed.latestRoundData();
// mint bull and store its state on chain
uint newId = counter;
_safeMint(_msgSender(), newId);
bullStateOf[newId] = Bull(proxyAddr, false, currPrice, 0);
emit BullState(newId, proxyAddr, false, currPrice, 0);
counter++;
return newId;
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function regretOpen(uint bullId) override external checkOwner(bullId) {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function regretClose(uint bullId) override external checkOwner(bullId) {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function occupy(uint bullId, uint fieldId) override external checkOwner(bullId) {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function vote(uint proposalId, uint fieldCount) override external {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function propose(string memory proposedBaseURI) override external {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function startVote() override external {
}
/**
* @notice See ../BullsToTheMoonInterface.sol
*/
function endVote() override external {
}
/**
* @dev Resolve ENS-namehash to Chainlink price feed proxy
*/
function _resolve(bytes32 node) internal view returns (address) {
Resolver resolver = ens.resolver(node);
return resolver.addr(node);
}
}
|
See ../BullsToTheMoonInterface.sol/
|
function startVote() override external {
}
| 926,548 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
// ========== External imports ==========
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/BitMapsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
// ========== Internal imports ==========
import { IDropERC721 } from "../interfaces/drop/IDropERC721.sol";
import { ITWFee } from "../interfaces/ITWFee.sol";
import "../openzeppelin-presets/metatx/ERC2771ContextUpgradeable.sol";
import "../lib/CurrencyTransferLib.sol";
import "../lib/FeeType.sol";
import "../lib/MerkleProof.sol";
contract DropERC721 is
Initializable,
ReentrancyGuardUpgradeable,
ERC2771ContextUpgradeable,
MulticallUpgradeable,
AccessControlEnumerableUpgradeable,
ERC721EnumerableUpgradeable,
IDropERC721
{
using BitMapsUpgradeable for BitMapsUpgradeable.BitMap;
using StringsUpgradeable for uint256;
/*///////////////////////////////////////////////////////////////
State variables
//////////////////////////////////////////////////////////////*/
bytes32 private constant MODULE_TYPE = bytes32("DropERC721");
uint256 private constant VERSION = 2;
/// @dev Only transfers to or from TRANSFER_ROLE holders are valid, when transfers are restricted.
bytes32 private constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
/// @dev Only MINTER_ROLE holders can lazy mint NFTs.
bytes32 private constant MINTER_ROLE = keccak256("MINTER_ROLE");
/// @dev Max bps in the thirdweb system.
uint256 private constant MAX_BPS = 10_000;
/// @dev The thirdweb contract with fee related information.
ITWFee public immutable thirdwebFee;
/// @dev Owner of the contract (purpose: OpenSea compatibility)
address private _owner;
/// @dev The next token ID of the NFT to "lazy mint".
uint256 public nextTokenIdToMint;
/// @dev The next token ID of the NFT that can be claimed.
uint256 public nextTokenIdToClaim;
/// @dev The address that receives all primary sales value.
address public primarySaleRecipient;
/// @dev The max number of NFTs a wallet can claim.
uint256 public maxWalletClaimCount;
/// @dev Global max total supply of NFTs.
uint256 public maxTotalSupply;
/// @dev The address that receives all platform fees from all sales.
address private platformFeeRecipient;
/// @dev The % of primary sales collected as platform fees.
uint16 private platformFeeBps;
/// @dev The (default) address that receives all royalty value.
address private royaltyRecipient;
/// @dev The (default) % of a sale to take as royalty (in basis points).
uint16 private royaltyBps;
/// @dev Contract level metadata.
string public contractURI;
/// @dev Largest tokenId of each batch of tokens with the same baseURI
uint256[] public baseURIIndices;
/// @dev The set of all claim conditions, at any given moment.
ClaimConditionList public claimCondition;
/*///////////////////////////////////////////////////////////////
Mappings
//////////////////////////////////////////////////////////////*/
/**
* @dev Mapping from 'Largest tokenId of a batch of tokens with the same baseURI'
* to base URI for the respective batch of tokens.
**/
mapping(uint256 => string) private baseURI;
/**
* @dev Mapping from 'Largest tokenId of a batch of 'delayed-reveal' tokens with
* the same baseURI' to encrypted base URI for the respective batch of tokens.
**/
mapping(uint256 => bytes) public encryptedBaseURI;
/// @dev Mapping from address => total number of NFTs a wallet has claimed.
mapping(address => uint256) public walletClaimCount;
/// @dev Token ID => royalty recipient and bps for token
mapping(uint256 => RoyaltyInfo) private royaltyInfoForToken;
/*///////////////////////////////////////////////////////////////
Constructor + initializer logic
//////////////////////////////////////////////////////////////*/
constructor(address _thirdwebFee) initializer {
thirdwebFee = ITWFee(_thirdwebFee);
}
/// @dev Initiliazes the contract, like a constructor.
function initialize(
address _defaultAdmin,
string memory _name,
string memory _symbol,
string memory _contractURI,
address[] memory _trustedForwarders,
address _saleRecipient,
address _royaltyRecipient,
uint128 _royaltyBps,
uint128 _platformFeeBps,
address _platformFeeRecipient
) external initializer {
// Initialize inherited contracts, most base-like -> most derived.
__ReentrancyGuard_init();
__ERC2771Context_init(_trustedForwarders);
__ERC721_init(_name, _symbol);
// Initialize this contract's state.
royaltyRecipient = _royaltyRecipient;
royaltyBps = uint16(_royaltyBps);
platformFeeRecipient = _platformFeeRecipient;
platformFeeBps = uint16(_platformFeeBps);
primarySaleRecipient = _saleRecipient;
contractURI = _contractURI;
_owner = _defaultAdmin;
_setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin);
_setupRole(MINTER_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, _defaultAdmin);
_setupRole(TRANSFER_ROLE, address(0));
}
/*///////////////////////////////////////////////////////////////
Generic contract logic
//////////////////////////////////////////////////////////////*/
/// @dev Returns the type of the contract.
function contractType() external pure returns (bytes32) {
return MODULE_TYPE;
}
/// @dev Returns the version of the contract.
function contractVersion() external pure returns (uint8) {
return uint8(VERSION);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return hasRole(DEFAULT_ADMIN_ROLE, _owner) ? _owner : address(0);
}
/*///////////////////////////////////////////////////////////////
ERC 165 / 721 / 2981 logic
//////////////////////////////////////////////////////////////*/
/// @dev Returns the URI for a given tokenId.
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
for (uint256 i = 0; i < baseURIIndices.length; i += 1) {
if (_tokenId < baseURIIndices[i]) {
if (encryptedBaseURI[baseURIIndices[i]].length != 0) {
return string(abi.encodePacked(baseURI[baseURIIndices[i]], "0"));
} else {
return string(abi.encodePacked(baseURI[baseURIIndices[i]], _tokenId.toString()));
}
}
}
return "";
}
/// @dev See ERC 165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721EnumerableUpgradeable, AccessControlEnumerableUpgradeable, IERC165Upgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId) || type(IERC2981Upgradeable).interfaceId == interfaceId;
}
/// @dev Returns the royalty recipient and amount, given a tokenId and sale price.
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
virtual
returns (address receiver, uint256 royaltyAmount)
{
(address recipient, uint256 bps) = getRoyaltyInfoForToken(tokenId);
receiver = recipient;
royaltyAmount = (salePrice * bps) / MAX_BPS;
}
/*///////////////////////////////////////////////////////////////
Minting + delayed-reveal logic
//////////////////////////////////////////////////////////////*/
/**
* @dev Lets an account with `MINTER_ROLE` lazy mint 'n' NFTs.
* The URIs for each token is the provided `_baseURIForTokens` + `{tokenId}`.
*/
function lazyMint(
uint256 _amount,
string calldata _baseURIForTokens,
bytes calldata _encryptedBaseURI
) external onlyRole(MINTER_ROLE) {
uint256 startId = nextTokenIdToMint;
uint256 baseURIIndex = startId + _amount;
nextTokenIdToMint = baseURIIndex;
baseURI[baseURIIndex] = _baseURIForTokens;
baseURIIndices.push(baseURIIndex);
if (_encryptedBaseURI.length != 0) {
encryptedBaseURI[baseURIIndex] = _encryptedBaseURI;
}
emit TokensLazyMinted(startId, startId + _amount - 1, _baseURIForTokens, _encryptedBaseURI);
}
/// @dev Lets an account with `MINTER_ROLE` reveal the URI for a batch of 'delayed-reveal' NFTs.
function reveal(uint256 index, bytes calldata _key)
external
onlyRole(MINTER_ROLE)
returns (string memory revealedURI)
{
require(index < baseURIIndices.length, "invalid index.");
uint256 _index = baseURIIndices[index];
bytes memory encryptedURI = encryptedBaseURI[_index];
require(encryptedURI.length != 0, "nothing to reveal.");
revealedURI = string(encryptDecrypt(encryptedURI, _key));
baseURI[_index] = revealedURI;
delete encryptedBaseURI[_index];
emit NFTRevealed(_index, revealedURI);
return revealedURI;
}
/// @dev See: https://ethereum.stackexchange.com/questions/69825/decrypt-message-on-chain
function encryptDecrypt(bytes memory data, bytes calldata key) public pure returns (bytes memory result) {
// Store data length on stack for later use
uint256 length = data.length;
// solhint-disable-next-line no-inline-assembly
assembly {
// Set result to free memory pointer
result := mload(0x40)
// Increase free memory pointer by lenght + 32
mstore(0x40, add(add(result, length), 32))
// Set result length
mstore(result, length)
}
// Iterate over the data stepping by 32 bytes
for (uint256 i = 0; i < length; i += 32) {
// Generate hash of the key and offset
bytes32 hash = keccak256(abi.encodePacked(key, i));
bytes32 chunk;
// solhint-disable-next-line no-inline-assembly
assembly {
// Read 32-bytes data chunk
chunk := mload(add(data, add(i, 32)))
}
// XOR the chunk with hash
chunk ^= hash;
// solhint-disable-next-line no-inline-assembly
assembly {
// Write 32-byte encrypted chunk
mstore(add(result, add(i, 32)), chunk)
}
}
}
/*///////////////////////////////////////////////////////////////
Claim logic
//////////////////////////////////////////////////////////////*/
/// @dev Lets an account claim NFTs.
function claim(
address _receiver,
uint256 _quantity,
address _currency,
uint256 _pricePerToken,
bytes32[] calldata _proofs,
uint256 _proofMaxQuantityPerTransaction
) external payable nonReentrant {
uint256 tokenIdToClaim = nextTokenIdToClaim;
// Get the claim conditions.
uint256 activeConditionId = getActiveClaimConditionId();
/**
* We make allowlist checks (i.e. verifyClaimMerkleProof) before verifying the claim's general
* validity (i.e. verifyClaim) because we give precedence to the check of allow list quantity
* restriction over the check of the general claim condition's quantityLimitPerTransaction
* restriction.
*/
// Verify inclusion in allowlist.
(bool validMerkleProof, uint256 merkleProofIndex) = verifyClaimMerkleProof(
activeConditionId,
_msgSender(),
_quantity,
_proofs,
_proofMaxQuantityPerTransaction
);
// Verify claim validity. If not valid, revert.
bool toVerifyMaxQuantityPerTransaction = _proofMaxQuantityPerTransaction == 0;
verifyClaim(
activeConditionId,
_msgSender(),
_quantity,
_currency,
_pricePerToken,
toVerifyMaxQuantityPerTransaction
);
if (validMerkleProof && _proofMaxQuantityPerTransaction > 0) {
/**
* Mark the claimer's use of their position in the allowlist. A spot in an allowlist
* can be used only once.
*/
claimCondition.limitMerkleProofClaim[activeConditionId].set(merkleProofIndex);
}
// If there's a price, collect price.
collectClaimPrice(_quantity, _currency, _pricePerToken);
// Mint the relevant NFTs to claimer.
transferClaimedTokens(_receiver, activeConditionId, _quantity);
emit TokensClaimed(activeConditionId, _msgSender(), _receiver, tokenIdToClaim, _quantity);
}
/// @dev Lets a contract admin (account with `DEFAULT_ADMIN_ROLE`) set claim conditions.
function setClaimConditions(ClaimCondition[] calldata _phases, bool _resetClaimEligibility)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
uint256 existingStartIndex = claimCondition.currentStartId;
uint256 existingPhaseCount = claimCondition.count;
/**
* `limitLastClaimTimestamp` and `limitMerkleProofClaim` are mappings that use a
* claim condition's UID as a key.
*
* If `_resetClaimEligibility == true`, we assign completely new UIDs to the claim
* conditions in `_phases`, effectively resetting the restrictions on claims expressed
* by `limitLastClaimTimestamp` and `limitMerkleProofClaim`.
*/
uint256 newStartIndex = existingStartIndex;
if (_resetClaimEligibility) {
newStartIndex = existingStartIndex + existingPhaseCount;
}
claimCondition.count = _phases.length;
claimCondition.currentStartId = newStartIndex;
uint256 lastConditionStartTimestamp;
for (uint256 i = 0; i < _phases.length; i++) {
require(i == 0 || lastConditionStartTimestamp < _phases[i].startTimestamp, "ST");
uint256 supplyClaimedAlready = claimCondition.phases[newStartIndex + i].supplyClaimed;
require(supplyClaimedAlready <= _phases[i].maxClaimableSupply, "max supply claimed already");
claimCondition.phases[newStartIndex + i] = _phases[i];
claimCondition.phases[newStartIndex + i].supplyClaimed = supplyClaimedAlready;
lastConditionStartTimestamp = _phases[i].startTimestamp;
}
/**
* Gas refunds (as much as possible)
*
* If `_resetClaimEligibility == true`, we assign completely new UIDs to the claim
* conditions in `_phases`. So, we delete claim conditions with UID < `newStartIndex`.
*
* If `_resetClaimEligibility == false`, and there are more existing claim conditions
* than in `_phases`, we delete the existing claim conditions that don't get replaced
* by the conditions in `_phases`.
*/
if (_resetClaimEligibility) {
for (uint256 i = existingStartIndex; i < newStartIndex; i++) {
delete claimCondition.phases[i];
delete claimCondition.limitMerkleProofClaim[i];
}
} else {
if (existingPhaseCount > _phases.length) {
for (uint256 i = _phases.length; i < existingPhaseCount; i++) {
delete claimCondition.phases[newStartIndex + i];
delete claimCondition.limitMerkleProofClaim[newStartIndex + i];
}
}
}
emit ClaimConditionsUpdated(_phases);
}
/// @dev Collects and distributes the primary sale value of NFTs being claimed.
function collectClaimPrice(
uint256 _quantityToClaim,
address _currency,
uint256 _pricePerToken
) internal {
if (_pricePerToken == 0) {
return;
}
uint256 totalPrice = _quantityToClaim * _pricePerToken;
uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS;
(address twFeeRecipient, uint256 twFeeBps) = thirdwebFee.getFeeInfo(address(this), FeeType.PRIMARY_SALE);
uint256 twFee = (totalPrice * twFeeBps) / MAX_BPS;
if (_currency == CurrencyTransferLib.NATIVE_TOKEN) {
require(msg.value == totalPrice, "must send total price.");
}
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), platformFeeRecipient, platformFees);
CurrencyTransferLib.transferCurrency(_currency, _msgSender(), twFeeRecipient, twFee);
CurrencyTransferLib.transferCurrency(
_currency,
_msgSender(),
primarySaleRecipient,
totalPrice - platformFees - twFee
);
}
/// @dev Transfers the NFTs being claimed.
function transferClaimedTokens(
address _to,
uint256 _conditionId,
uint256 _quantityBeingClaimed
) internal {
// Update the supply minted under mint condition.
claimCondition.phases[_conditionId].supplyClaimed += _quantityBeingClaimed;
// if transfer claimed tokens is called when `to != msg.sender`, it'd use msg.sender's limits.
// behavior would be similar to `msg.sender` mint for itself, then transfer to `_to`.
claimCondition.limitLastClaimTimestamp[_conditionId][_msgSender()] = block.timestamp;
walletClaimCount[_msgSender()] += _quantityBeingClaimed;
uint256 tokenIdToClaim = nextTokenIdToClaim;
for (uint256 i = 0; i < _quantityBeingClaimed; i += 1) {
_mint(_to, tokenIdToClaim);
tokenIdToClaim += 1;
}
nextTokenIdToClaim = tokenIdToClaim;
}
/// @dev Checks a request to claim NFTs against the active claim condition's criteria.
function verifyClaim(
uint256 _conditionId,
address _claimer,
uint256 _quantity,
address _currency,
uint256 _pricePerToken,
bool verifyMaxQuantityPerTransaction
) public view {
ClaimCondition memory currentClaimPhase = claimCondition.phases[_conditionId];
require(
_currency == currentClaimPhase.currency && _pricePerToken == currentClaimPhase.pricePerToken,
"invalid currency or price."
);
// If we're checking for an allowlist quantity restriction, ignore the general quantity restriction.
require(
_quantity > 0 &&
(!verifyMaxQuantityPerTransaction || _quantity <= currentClaimPhase.quantityLimitPerTransaction),
"invalid quantity."
);
require(
currentClaimPhase.supplyClaimed + _quantity <= currentClaimPhase.maxClaimableSupply,
"exceed max claimable supply."
);
require(nextTokenIdToClaim + _quantity <= nextTokenIdToMint, "not enough minted tokens.");
require(maxTotalSupply == 0 || nextTokenIdToClaim + _quantity <= maxTotalSupply, "exceed max total supply.");
require(
maxWalletClaimCount == 0 || walletClaimCount[_claimer] + _quantity <= maxWalletClaimCount,
"exceed claim limit"
);
(uint256 lastClaimTimestamp, uint256 nextValidClaimTimestamp) = getClaimTimestamp(_conditionId, _claimer);
require(lastClaimTimestamp == 0 || block.timestamp >= nextValidClaimTimestamp, "cannot claim.");
}
/// @dev Checks whether a claimer meets the claim condition's allowlist criteria.
function verifyClaimMerkleProof(
uint256 _conditionId,
address _claimer,
uint256 _quantity,
bytes32[] calldata _proofs,
uint256 _proofMaxQuantityPerTransaction
) public view returns (bool validMerkleProof, uint256 merkleProofIndex) {
ClaimCondition memory currentClaimPhase = claimCondition.phases[_conditionId];
if (currentClaimPhase.merkleRoot != bytes32(0)) {
(validMerkleProof, merkleProofIndex) = MerkleProof.verify(
_proofs,
currentClaimPhase.merkleRoot,
keccak256(abi.encodePacked(_claimer, _proofMaxQuantityPerTransaction))
);
require(validMerkleProof, "not in whitelist.");
require(!claimCondition.limitMerkleProofClaim[_conditionId].get(merkleProofIndex), "proof claimed.");
require(
_proofMaxQuantityPerTransaction == 0 || _quantity <= _proofMaxQuantityPerTransaction,
"invalid quantity proof."
);
}
}
/*///////////////////////////////////////////////////////////////
Getter functions
//////////////////////////////////////////////////////////////*/
/// @dev At any given moment, returns the uid for the active claim condition.
function getActiveClaimConditionId() public view returns (uint256) {
for (uint256 i = claimCondition.currentStartId + claimCondition.count; i > claimCondition.currentStartId; i--) {
if (block.timestamp >= claimCondition.phases[i - 1].startTimestamp) {
return i - 1;
}
}
revert("!CONDITION.");
}
/// @dev Returns the royalty recipient and bps for a particular token Id.
function getRoyaltyInfoForToken(uint256 _tokenId) public view returns (address, uint16) {
RoyaltyInfo memory royaltyForToken = royaltyInfoForToken[_tokenId];
return
royaltyForToken.recipient == address(0)
? (royaltyRecipient, uint16(royaltyBps))
: (royaltyForToken.recipient, uint16(royaltyForToken.bps));
}
/// @dev Returns the platform fee recipient and bps.
function getPlatformFeeInfo() external view returns (address, uint16) {
return (platformFeeRecipient, uint16(platformFeeBps));
}
/// @dev Returns the default royalty recipient and bps.
function getDefaultRoyaltyInfo() external view returns (address, uint16) {
return (royaltyRecipient, uint16(royaltyBps));
}
/// @dev Returns the timestamp for when a claimer is eligible for claiming NFTs again.
function getClaimTimestamp(uint256 _conditionId, address _claimer)
public
view
returns (uint256 lastClaimTimestamp, uint256 nextValidClaimTimestamp)
{
lastClaimTimestamp = claimCondition.limitLastClaimTimestamp[_conditionId][_claimer];
unchecked {
nextValidClaimTimestamp =
lastClaimTimestamp +
claimCondition.phases[_conditionId].waitTimeInSecondsBetweenClaims;
if (nextValidClaimTimestamp < lastClaimTimestamp) {
nextValidClaimTimestamp = type(uint256).max;
}
}
}
/// @dev Returns the claim condition at the given uid.
function getClaimConditionById(uint256 _conditionId) external view returns (ClaimCondition memory condition) {
condition = claimCondition.phases[_conditionId];
}
/// @dev Returns the amount of stored baseURIs
function getBaseURICount() external view returns (uint256) {
return baseURIIndices.length;
}
/*///////////////////////////////////////////////////////////////
Setter functions
//////////////////////////////////////////////////////////////*/
/// @dev Lets a contract admin set a claim count for a wallet.
function setWalletClaimCount(address _claimer, uint256 _count) external onlyRole(DEFAULT_ADMIN_ROLE) {
walletClaimCount[_claimer] = _count;
emit WalletClaimCountUpdated(_claimer, _count);
}
/// @dev Lets a contract admin set a maximum number of NFTs that can be claimed by any wallet.
function setMaxWalletClaimCount(uint256 _count) external onlyRole(DEFAULT_ADMIN_ROLE) {
maxWalletClaimCount = _count;
emit MaxWalletClaimCountUpdated(_count);
}
/// @dev Lets a contract admin set the global maximum supply for collection's NFTs.
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_maxTotalSupply < nextTokenIdToMint, "existing > desired max supply");
maxTotalSupply = _maxTotalSupply;
emit MaxTotalSupplyUpdated(_maxTotalSupply);
}
/// @dev Lets a contract admin set the recipient for all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external onlyRole(DEFAULT_ADMIN_ROLE) {
primarySaleRecipient = _saleRecipient;
emit PrimarySaleRecipientUpdated(_saleRecipient);
}
/// @dev Lets a contract admin update the default royalty recipient and bps.
function setDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_royaltyBps <= MAX_BPS, "> MAX_BPS");
royaltyRecipient = _royaltyRecipient;
royaltyBps = uint16(_royaltyBps);
emit DefaultRoyalty(_royaltyRecipient, _royaltyBps);
}
/// @dev Lets a contract admin set the royalty recipient and bps for a particular token Id.
function setRoyaltyInfoForToken(
uint256 _tokenId,
address _recipient,
uint256 _bps
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_bps <= MAX_BPS, "> MAX_BPS");
royaltyInfoForToken[_tokenId] = RoyaltyInfo({ recipient: _recipient, bps: _bps });
emit RoyaltyForToken(_tokenId, _recipient, _bps);
}
/// @dev Lets a contract admin update the platform fee recipient and bps
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(_platformFeeBps <= MAX_BPS, "> MAX_BPS.");
platformFeeBps = uint16(_platformFeeBps);
platformFeeRecipient = _platformFeeRecipient;
emit PlatformFeeInfoUpdated(_platformFeeRecipient, _platformFeeBps);
}
/// @dev Lets a contract admin set a new owner for the contract. The new owner must be a contract admin.
function setOwner(address _newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(hasRole(DEFAULT_ADMIN_ROLE, _newOwner), "!ADMIN");
address _prevOwner = _owner;
_owner = _newOwner;
emit OwnerUpdated(_prevOwner, _newOwner);
}
/// @dev Lets a contract admin set the URI for contract-level metadata.
function setContractURI(string calldata _uri) external onlyRole(DEFAULT_ADMIN_ROLE) {
contractURI = _uri;
}
/*///////////////////////////////////////////////////////////////
Miscellaneous
//////////////////////////////////////////////////////////////*/
/// @dev Burns `tokenId`. See {ERC721-_burn}.
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "caller not owner nor approved");
_burn(tokenId);
}
/// @dev See {ERC721-_beforeTokenTransfer}.
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721EnumerableUpgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
// if transfer is restricted on the contract, we still want to allow burning and minting
if (!hasRole(TRANSFER_ROLE, address(0)) && from != address(0) && to != address(0)) {
require(hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "!TRANSFER_ROLE");
}
}
function _msgSender()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (address sender)
{
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData()
internal
view
virtual
override(ContextUpgradeable, ERC2771ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal onlyInitializing {
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
// 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(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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();
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981Upgradeable is IERC165Upgradeable {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/BitMaps.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing uint256 to bool mapping in a compact and efficient way, providing the keys are sequential.
* Largelly inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
*/
library BitMapsUpgradeable {
struct BitMap {
mapping(uint256 => uint256) _data;
}
/**
* @dev Returns whether the bit at `index` is set.
*/
function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
return bitmap._data[bucket] & mask != 0;
}
/**
* @dev Sets the bit at `index` to the boolean `value`.
*/
function setTo(
BitMap storage bitmap,
uint256 index,
bool value
) internal {
if (value) {
set(bitmap, index);
} else {
unset(bitmap, index);
}
}
/**
* @dev Sets the bit at `index`.
*/
function set(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
bitmap._data[bucket] |= mask;
}
/**
* @dev Unsets the bit at `index`.
*/
function unset(BitMap storage bitmap, uint256 index) internal {
uint256 bucket = index >> 8;
uint256 mask = 1 << (index & 0xff);
bitmap._data[bucket] &= ~mask;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Multicall.sol)
pragma solidity ^0.8.0;
import "./AddressUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides a function to batch together multiple calls in a single external call.
*
* _Available since v4.1._
*/
abstract contract MulticallUpgradeable is Initializable {
function __Multicall_init() internal onlyInitializing {
}
function __Multicall_init_unchained() internal onlyInitializing {
}
/**
* @dev Receives and executes a batch of function calls on this contract.
*/
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = _functionDelegateCall(address(this), data[i]);
}
return results;
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "../IThirdwebContract.sol";
import "../IThirdwebPlatformFee.sol";
import "../IThirdwebPrimarySale.sol";
import "../IThirdwebRoyalty.sol";
import "../IThirdwebOwnable.sol";
import "./IDropClaimCondition.sol";
/**
* Thirdweb's 'Drop' contracts are distribution mechanisms for tokens. The
* `DropERC721` contract is a distribution mechanism for ERC721 tokens.
*
* A minter wallet (i.e. holder of `MINTER_ROLE`) can (lazy)mint 'n' tokens
* at once by providing a single base URI for all tokens being lazy minted.
* The URI for each of the 'n' tokens lazy minted is the provided base URI +
* `{tokenId}` of the respective token. (e.g. "ipsf://Qmece.../1").
*
* A minter can choose to lazy mint 'delayed-reveal' tokens. More on 'delayed-reveal'
* tokens in [this article](https://blog.thirdweb.com/delayed-reveal-nfts).
*
* A contract admin (i.e. holder of `DEFAULT_ADMIN_ROLE`) can create claim conditions
* with non-overlapping time windows, and accounts can claim the tokens according to
* restrictions defined in the claim condition that is active at the time of the transaction.
*/
interface IDropERC721 is
IThirdwebContract,
IThirdwebOwnable,
IThirdwebRoyalty,
IThirdwebPrimarySale,
IThirdwebPlatformFee,
IERC721Upgradeable,
IDropClaimCondition
{
/// @dev Emitted when tokens are claimed.
event TokensClaimed(
uint256 indexed claimConditionIndex,
address indexed claimer,
address indexed receiver,
uint256 startTokenId,
uint256 quantityClaimed
);
/// @dev Emitted when tokens are lazy minted.
event TokensLazyMinted(uint256 startTokenId, uint256 endTokenId, string baseURI, bytes encryptedBaseURI);
/// @dev Emitted when the URI for a batch of 'delayed-reveal' NFTs is revealed.
event NFTRevealed(uint256 endTokenId, string revealedURI);
/// @dev Emitted when new claim conditions are set.
event ClaimConditionsUpdated(ClaimCondition[] claimConditions);
/// @dev Emitted when the global max supply of tokens is updated.
event MaxTotalSupplyUpdated(uint256 maxTotalSupply);
/// @dev Emitted when the wallet claim count for an address is updated.
event WalletClaimCountUpdated(address indexed wallet, uint256 count);
/// @dev Emitted when the global max wallet claim count is updated.
event MaxWalletClaimCountUpdated(uint256 count);
/**
* @notice Lets an account with `MINTER_ROLE` lazy mint 'n' NFTs.
* The URIs for each token is the provided `_baseURIForTokens` + `{tokenId}`.
*
* @param amount The amount of NFTs to lazy mint.
* @param baseURIForTokens The URI for the NFTs to lazy mint. If lazy minting
* 'delayed-reveal' NFTs, the is a URI for NFTs in the
* un-revealed state.
* @param encryptedBaseURI If lazy minting 'delayed-reveal' NFTs, this is the
* result of encrypting the URI of the NFTs in the revealed
* state.
*/
function lazyMint(
uint256 amount,
string calldata baseURIForTokens,
bytes calldata encryptedBaseURI
) external;
/**
* @notice Lets an account claim a given quantity of NFTs.
*
* @param receiver The receiver of the NFTs to claim.
* @param quantity The quantity of NFTs to claim.
* @param currency The currency in which to pay for the claim.
* @param pricePerToken The price per token to pay for the claim.
* @param proofs The proof of the claimer's inclusion in the merkle root allowlist
* of the claim conditions that apply.
* @param proofMaxQuantityPerTransaction (Optional) The maximum number of NFTs an address included in an
* allowlist can claim.
*/
function claim(
address receiver,
uint256 quantity,
address currency,
uint256 pricePerToken,
bytes32[] calldata proofs,
uint256 proofMaxQuantityPerTransaction
) external payable;
/**
* @notice Lets a contract admin (account with `DEFAULT_ADMIN_ROLE`) set claim conditions.
*
* @param phases Claim conditions in ascending order by `startTimestamp`.
* @param resetClaimEligibility Whether to reset `limitLastClaimTimestamp` and
* `limitMerkleProofClaim` values when setting new
* claim conditions.
*/
function setClaimConditions(ClaimCondition[] calldata phases, bool resetClaimEligibility) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface ITWFee {
function getFeeInfo(address _proxy, uint256 _type) external view returns (address recipient, uint256 bps);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (metatx/ERC2771Context.sol)
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @dev Context variant with ERC2771 support.
*/
abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {
mapping(address => bool) private _trustedForwarder;
function __ERC2771Context_init(address[] memory trustedForwarder) internal onlyInitializing {
__Context_init_unchained();
__ERC2771Context_init_unchained(trustedForwarder);
}
function __ERC2771Context_init_unchained(address[] memory trustedForwarder) internal onlyInitializing {
for (uint256 i = 0; i < trustedForwarder.length; i++) {
_trustedForwarder[trustedForwarder[i]] = true;
}
}
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return _trustedForwarder[forwarder];
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return super._msgSender();
}
}
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
} else {
return super._msgData();
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
// Helper interfaces
import { IWETH } from "../interfaces/IWETH.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
library CurrencyTransferLib {
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @dev The address interpreted as native token of the chain.
address public constant NATIVE_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Transfers a given amount of currency.
function transferCurrency(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
safeTransferNativeToken(_to, _amount);
} else {
safeTransferERC20(_currency, _from, _to, _amount);
}
}
/// @dev Transfers a given amount of currency. (With native token wrapping)
function transferCurrencyWithWrapper(
address _currency,
address _from,
address _to,
uint256 _amount,
address _nativeTokenWrapper
) internal {
if (_amount == 0) {
return;
}
if (_currency == NATIVE_TOKEN) {
if (_from == address(this)) {
// withdraw from weth then transfer withdrawn native token to recipient
IWETH(_nativeTokenWrapper).withdraw(_amount);
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
} else if (_to == address(this)) {
// store native currency in weth
require(_amount == msg.value, "msg.value != amount");
IWETH(_nativeTokenWrapper).deposit{ value: _amount }();
} else {
safeTransferNativeTokenWithWrapper(_to, _amount, _nativeTokenWrapper);
}
} else {
safeTransferERC20(_currency, _from, _to, _amount);
}
}
/// @dev Transfer `amount` of ERC20 token from `from` to `to`.
function safeTransferERC20(
address _currency,
address _from,
address _to,
uint256 _amount
) internal {
if (_from == _to) {
return;
}
if (_from == address(this)) {
IERC20Upgradeable(_currency).safeTransfer(_to, _amount);
} else {
IERC20Upgradeable(_currency).safeTransferFrom(_from, _to, _amount);
}
}
/// @dev Transfers `amount` of native token to `to`.
function safeTransferNativeToken(address to, uint256 value) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
require(success, "native token transfer failed");
}
/// @dev Transfers `amount` of native token to `to`. (With native token wrapping)
function safeTransferNativeTokenWithWrapper(
address to,
uint256 value,
address _nativeTokenWrapper
) internal {
// solhint-disable avoid-low-level-calls
// slither-disable-next-line low-level-calls
(bool success, ) = to.call{ value: value }("");
if (!success) {
IWETH(_nativeTokenWrapper).deposit{ value: value }();
IERC20Upgradeable(_nativeTokenWrapper).safeTransfer(to, value);
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
library FeeType {
uint256 internal constant PRIMARY_SALE = 0;
uint256 internal constant MARKET_SALE = 1;
uint256 internal constant SPLIT = 2;
}
// SPDX-License-Identifier: MIT
// Modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.0/contracts/utils/cryptography/MerkleProof.sol
// Copied from https://github.com/ensdomains/governance/blob/master/contracts/MerkleProof.sol
pragma solidity ^0.8.11;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*
* Source: https://github.com/ensdomains/governance/blob/master/contracts/MerkleProof.sol
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool, uint256) {
bytes32 computedHash = leaf;
uint256 index = 0;
for (uint256 i = 0; i < proof.length; i++) {
index *= 2;
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
index += 1;
}
}
// Check if the computed hash (root) is equal to the provided root
return (computedHash == root, index);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).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 = ERC721Upgradeable.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 = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^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);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/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
// 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 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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^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
// 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 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
* ====
*
* [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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// 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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165Upgradeable.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebContract {
/// @dev Returns the module type of the contract.
function contractType() external pure returns (bytes32);
/// @dev Returns the version of the contract.
function contractVersion() external pure returns (uint8);
/// @dev Returns the metadata URI of the contract.
function contractURI() external view returns (string memory);
/**
* @dev Sets contract URI for the storefront-level metadata of the contract.
* Only module admin can call this function.
*/
function setContractURI(string calldata _uri) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPlatformFee {
/// @dev Returns the platform fee bps and recipient.
function getPlatformFeeInfo() external view returns (address, uint16);
/// @dev Lets a module admin update the fees on primary sales.
function setPlatformFeeInfo(address _platformFeeRecipient, uint256 _platformFeeBps) external;
/// @dev Emitted when fee on primary sales is updated.
event PlatformFeeInfoUpdated(address platformFeeRecipient, uint256 platformFeeBps);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebPrimarySale {
/// @dev The adress that receives all primary sales value.
function primarySaleRecipient() external view returns (address);
/// @dev Lets a module admin set the default recipient of all primary sales.
function setPrimarySaleRecipient(address _saleRecipient) external;
/// @dev Emitted when a new sale recipient is set.
event PrimarySaleRecipientUpdated(address indexed recipient);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol";
interface IThirdwebRoyalty is IERC2981Upgradeable {
struct RoyaltyInfo {
address recipient;
uint256 bps;
}
/// @dev Returns the royalty recipient and fee bps.
function getDefaultRoyaltyInfo() external view returns (address, uint16);
/// @dev Lets a module admin update the royalty bps and recipient.
function setDefaultRoyaltyInfo(address _royaltyRecipient, uint256 _royaltyBps) external;
/// @dev Lets a module admin set the royalty recipient for a particular token Id.
function setRoyaltyInfoForToken(
uint256 tokenId,
address recipient,
uint256 bps
) external;
/// @dev Returns the royalty recipient for a particular token Id.
function getRoyaltyInfoForToken(uint256 tokenId) external view returns (address, uint16);
/// @dev Emitted when royalty info is updated.
event DefaultRoyalty(address newRoyaltyRecipient, uint256 newRoyaltyBps);
/// @dev Emitted when royalty recipient for tokenId is set
event RoyaltyForToken(uint256 indexed tokenId, address royaltyRecipient, uint256 royaltyBps);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IThirdwebOwnable {
/// @dev Returns the owner of the contract.
function owner() external view returns (address);
/// @dev Lets a module admin set a new owner for the contract. The new owner must be a module admin.
function setOwner(address _newOwner) external;
/// @dev Emitted when a new Owner is set.
event OwnerUpdated(address prevOwner, address newOwner);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/utils/structs/BitMapsUpgradeable.sol";
/**
* Thirdweb's 'Drop' contracts are distribution mechanisms for tokens.
*
* A contract admin (i.e. a holder of `DEFAULT_ADMIN_ROLE`) can set a series of claim conditions,
* ordered by their respective `startTimestamp`. A claim condition defines criteria under which
* accounts can mint tokens. Claim conditions can be overwritten or added to by the contract admin.
* At any moment, there is only one active claim condition.
*/
interface IDropClaimCondition {
/**
* @notice The criteria that make up a claim condition.
*
* @param startTimestamp The unix timestamp after which the claim condition applies.
* The same claim condition applies until the `startTimestamp`
* of the next claim condition.
*
* @param maxClaimableSupply The maximum total number of tokens that can be claimed under
* the claim condition.
*
* @param supplyClaimed At any given point, the number of tokens that have been claimed
* under the claim condition.
*
* @param quantityLimitPerTransaction The maximum number of tokens that can be claimed in a single
* transaction.
*
* @param waitTimeInSecondsBetweenClaims The least number of seconds an account must wait after claiming
* tokens, to be able to claim tokens again.
*
* @param merkleRoot The allowlist of addresses that can claim tokens under the claim
* condition.
*
* @param pricePerToken The price required to pay per token claimed.
*
* @param currency The currency in which the `pricePerToken` must be paid.
*/
struct ClaimCondition {
uint256 startTimestamp;
uint256 maxClaimableSupply;
uint256 supplyClaimed;
uint256 quantityLimitPerTransaction;
uint256 waitTimeInSecondsBetweenClaims;
bytes32 merkleRoot;
uint256 pricePerToken;
address currency;
}
/**
* @notice The set of all claim conditions, at any given moment.
* Claim Phase ID = [currentStartId, currentStartId + length - 1];
*
* @param currentStartId The uid for the first claim condition amongst the current set of
* claim conditions. The uid for each next claim condition is one
* more than the previous claim condition's uid.
*
* @param count The total number of phases / claim conditions in the list
* of claim conditions.
*
* @param phases The claim conditions at a given uid. Claim conditions
* are ordered in an ascending order by their `startTimestamp`.
*
* @param limitLastClaimTimestamp Map from an account and uid for a claim condition, to the last timestamp
* at which the account claimed tokens under that claim condition.
*
* @param limitMerkleProofClaim Map from a claim condition uid to whether an address in an allowlist
* has already claimed tokens i.e. used their place in the allowlist.
*/
struct ClaimConditionList {
uint256 currentStartId;
uint256 count;
mapping(uint256 => ClaimCondition) phases;
mapping(uint256 => mapping(address => uint256)) limitLastClaimTimestamp;
mapping(uint256 => BitMapsUpgradeable.BitMap) limitMerkleProofClaim;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IWETH {
function deposit() external payable;
function withdraw(uint256 amount) external;
function transfer(address to, uint256 value) external returns (bool);
}
// 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 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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.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 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'
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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable 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(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
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
|
The assembly code is more direct than the Solidity version using `abi.decode`.
|
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
return super._msgSender();
}
}
| 94,736 |
pragma solidity 0.6.12;
// SPDX-License-Identifier: MIT
import "@pancakeswap/pancake-swap-lib/contracts/access/Ownable.sol";
import "@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol";
import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol";
import './ArtichainToken.sol';
import './libs/ReentrancyGuard.sol';
/**
* @title AITPresale
* @dev AITPresale is a contract for managing a token presale,
* allowing investors to purchase tokens with busd. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for Presales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of Presales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
* start time (11 june 2021 14:00 UTC - 8,192,324 block)
*/
contract ArtichainPresale is Ownable, ReentrancyGuard {
using SafeMath for uint256;
// The token being sold
ArtichainToken public token;
// The token being received
IBEP20 public tokenBUSD;
// Address where funds are collected
address public wallet;
address public tokenWallet;
// total amount for sale
uint256 public cap;
// Amount of sold tokens in presale
uint256 public totalSoldAmount;
// Amount of busd raised
uint256 public busdRaised;
uint256 public startTime;
uint256 public endTime;
bool isFinished = false;
// Track investor contributions
mapping(address => uint256) public contributions;
// Presale Stages
struct PresaleStage {
uint256 stage;
uint256 cap;
uint256 rate;
uint256 bonus;
}
// Percentages with Presale stages
mapping(uint256 => PresaleStage) public presaleStages;
// sold amount for stages
mapping(uint256 => uint256) public soldAmounts;
struct Presale {
uint256 stage;
uint256 rate;
uint256 usdAmount;
uint256 tokenAmount;
}
mapping(address => Presale[]) public userSales;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param curStage current presale stage
* @param rate current rate
* @param value busd paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
uint256 curStage,
uint256 rate,
uint256 value,
uint256 amount
);
event PresaleStarted();
event PresaleStageChanged(uint256 nextStage);
event RateChanged(uint256 stage, uint256 rate);
event PresaleFinished();
// -----------------------------------------
// Presale external interface
// -----------------------------------------
constructor(
address _wallet,
address _tokenWallet,
address _token,
address _tokenBUSD,
uint256 _startTime,
uint256 _prevSold
) public {
require(_wallet != address(0), "wallet shouldn't be zero address");
require(_token != address(0), "token shouldn't be zero address");
require(_tokenBUSD != address(0), "busd shouldn't be zero address");
wallet = _wallet;
tokenWallet = _tokenWallet;
token = ArtichainToken(_token);
tokenBUSD = IBEP20(_tokenBUSD);
startTime = _startTime;
endTime = _startTime + (3 * 7 days); // 3 weeks
// 10k tokens for presale + bonus 350
cap = 10350 * (10**uint(token.decimals()));
presaleStages[1] = PresaleStage(1, 4000 * (10**uint(token.decimals())), 5000, 500);
presaleStages[2] = PresaleStage(2, 3000 * (10**uint(token.decimals())), 5500, 300);
presaleStages[3] = PresaleStage(3, 3000 * (10**uint(token.decimals())), 6000, 200);
totalSoldAmount = _prevSold;
soldAmounts[1] = _prevSold;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return totalSoldAmount >= cap;
}
function currentStage() public view returns (uint256) {
if(block.timestamp < startTime) return 0;
if(isFinished == true) return 4;
uint256 curStage = (block.timestamp - startTime) / 7 days + 1;
uint256 currentCap = 0;
for(uint256 i = 1; i <= curStage; i++) {
currentCap = currentCap.add(presaleStages[i].cap);
}
if(currentCap <= totalSoldAmount) {
curStage = curStage.add(1);
}
return curStage;
}
function currentRate() public view returns (uint256) {
uint256 currentPresaleStage = currentStage();
if(currentPresaleStage < 1) return presaleStages[1].rate;
if(currentPresaleStage > 3) return presaleStages[3].rate;
return presaleStages[currentPresaleStage].rate;
}
/**
* @dev Reverts if not in Presale time range.
*/
modifier onlyWhileOpen {
require(startTime <= block.timestamp, "Presale is not started");
require(capReached() == false, "Presale cap is reached");
require(block.timestamp <= endTime && isFinished == false, "Presale is closed");
_;
}
/**
* @dev Checks whether the period in which the Presale is open has already elapsed.
* @return Whether Presale period has elapsed
*/
function hasClosed() external view returns (bool) {
return capReached() || block.timestamp > endTime || isFinished;
}
/**
* @dev Start presale.
* @return Whether presale is started
*/
function startPresale() external onlyOwner returns (bool) {
require(startTime > block.timestamp, "Presale is already started");
startTime = block.timestamp;
endTime = startTime + (3 * 7 days); // 3 weeks
emit PresaleStarted();
return true;
}
/**
* @dev update presale params.
* @return Whether presale is updated
*/
function setPresale(uint256 _stage, uint256 _cap, uint256 _rate, uint256 _bonus) external onlyOwner returns (bool) {
require(_stage > 0 && _stage <= 3, "Invalid stage");
require(!(currentStage() == _stage && startTime <= block.timestamp), "Cannot change params for current stage");
require(_cap > 0 && _rate > 0);
presaleStages[_stage].cap = _cap;
presaleStages[_stage].rate = _rate;
presaleStages[_stage].bonus = _bonus;
return true;
}
/**
* @dev Finish presale.
* @return Whether presale is finished
*/
function finishPresale() external onlyOwner returns (bool) {
require(startTime <= block.timestamp, "Presale is not started");
require(isFinished == false , "Presale was finished");
_finishPresale();
return true;
}
/**
* @dev Returns the amount contributed so far by a sepecific user.
* @param _beneficiary Address of contributor
* @return User contribution so far
*/
function getUserContribution(address _beneficiary) external view returns (uint256) {
return contributions[_beneficiary];
}
/**
* @dev Returns if exchange rate was set by a sepecific user.
* @param _rate exchange rate for current presale stage
*/
function setExchangeRate(uint256 _rate) external onlyWhileOpen onlyOwner returns (bool) {
require(_rate >= 5000, "rate should be greater than 5000"); // 50 busd
uint256 currentPresaleStage = currentStage();
presaleStages[currentPresaleStage].rate = _rate;
emit RateChanged(currentPresaleStage, _rate);
return true;
}
function updateCompanyWallet(address _wallet) external onlyOwner returns (bool){
wallet = _wallet;
return true;
}
function setTokenWallet(address _wallet) external onlyOwner {
tokenWallet = _wallet;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param busdAmount purchased busd amount
*/
function buyTokens(uint256 busdAmount) external nonReentrant{
_preValidatePurchase(msg.sender, busdAmount);
uint256 currentPresaleStage = currentStage();
// calculate token amount to be created
uint256 tokens = _getTokenAmount(busdAmount);
uint256 bonus = presaleStages[currentPresaleStage].bonus;
bonus = tokens.mul(bonus).div(10000);
tokens = tokens.add(bonus);
_forwardFunds(busdAmount);
// update state
busdRaised = busdRaised.add(busdAmount);
_processPurchase(msg.sender, tokens);
emit TokenPurchase(msg.sender, currentPresaleStage, presaleStages[currentPresaleStage].rate, busdAmount, tokens);
_updatePurchasingState(msg.sender, busdAmount, tokens);
_postValidatePurchase(msg.sender, tokens);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _busdAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _busdAmount)
internal
onlyWhileOpen
{
require(_beneficiary != address(0), "can't buy for zero address");
uint256 currentPresaleStage = currentStage();
require(currentPresaleStage > 0 , "Presale is not started");
require(currentPresaleStage <= 3 && isFinished == false, "Presale was finished");
// calculate token amount to be created
uint256 tokens = _getTokenAmount(_busdAmount);
require(tokens >= 10**uint(token.decimals()) / 10, "AIT amount must exceed 0.1");
contributions[_beneficiary] = contributions[_beneficiary].add(_busdAmount);
uint256 bonus = presaleStages[currentPresaleStage].bonus;
bonus = tokens.mul(bonus).div(10000);
tokens = tokens.add(bonus);
uint256 soldAmount = totalSoldAmount.add(tokens);
require(soldAmount <= cap, "CAP reached, can't sell more token");
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _busdAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _busdAmount)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the Presale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount)
internal
{
// token.mint(_beneficiary, _tokenAmount);
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _buyer Address receiving the tokens
* @param _busdAmount Value in busd involved in the purchase
* @param _tokenAmount Value in token involved in the purchase
*/
function _updatePurchasingState(address _buyer, uint256 _busdAmount, uint256 _tokenAmount)
internal
{
uint256 currentPresaleStage = currentStage();
// optional override
totalSoldAmount = totalSoldAmount.add(_tokenAmount);
soldAmounts[currentPresaleStage] = soldAmounts[currentPresaleStage].add(_tokenAmount);
userSales[_buyer].push(Presale(currentPresaleStage, presaleStages[currentPresaleStage].rate, _busdAmount, _tokenAmount));
if(currentStage() > 3) _finishPresale();
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _busdAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _busdAmount
*/
function _getTokenAmount(uint256 _busdAmount)
internal
view
returns (uint256)
{
uint256 currentPresaleStage = currentStage();
return _busdAmount.mul(10**uint(token.decimals() - tokenBUSD.decimals())).mul(100).div(presaleStages[currentPresaleStage].rate);
}
/**
* @dev Determines how BUSD is stored/forwarded on purchases.
*/
function _forwardFunds(uint256 _busdAmount) internal {
tokenBUSD.transferFrom(msg.sender, wallet, _busdAmount);
}
/**
* @dev Finish presale.
*/
function _finishPresale() internal {
endTime = block.timestamp;
isFinished = true;
emit PresaleFinished();
}
}
|
Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. _beneficiary Address performing the token purchase _busdAmount Value in wei involved in the purchase/ optional override
|
function _postValidatePurchase(address _beneficiary, uint256 _busdAmount)
internal
{
}
| 12,966,726 |
./full_match/5/0x7658f1B282790FEe91f2E0BFA6D9f2EdAd7ACE6D/sources/contracts/MysticRealms.sol
|
User chooses attack or defense move for battle card
|
function attackOrDefendChoice(uint8 _choice, string memory _battleName) external {
Battle memory _battle = getBattle(_battleName);
require(
_battle.battleStatus == BattleStatus.STARTED,
"Battle not started. Please tell another player to join the battle"
require(
_battle.battleStatus != BattleStatus.ENDED,
"Battle has already ended"
require(
msg.sender == _battle.players[0] || msg.sender == _battle.players[1],
"You are not in this battle"
require(_battle.moves[_battle.players[0] == msg.sender ? 0 : 1] == 0, "You have already made a move!");
_registerPlayerMove(_battle.players[0] == msg.sender ? 0 : 1, _choice, _battleName);
_battle = getBattle(_battleName);
uint _movesLeft = 2 - (_battle.moves[0] == 0 ? 0 : 1) - (_battle.moves[1] == 0 ? 0 : 1);
emit BattleMove(_battleName, _movesLeft == 1 ? true : false);
if(_movesLeft == 0) {
_awaitBattleResults(_battleName);
}
}
| 1,865,726 |
./full_match/80001/0xD020917Bc396787375AcE783DF896d14aDF18FB6/sources/src/exchange/mixins/Trading.sol
|
Fetch remaining amount from storage Update remaining if the order is new/has not been filled Throw if the makingAmount(amount to be filled) is greater than the amount available Update remaining using the makingAmount If order is completely filled, update isFilledOrCancelled in storage Update remaining in storage
|
function _updateOrderStatus(bytes32 orderHash, Order memory order, uint256 makingAmount)
internal
returns (uint256 remaining)
{
OrderStatus storage status = orderStatus[orderHash];
remaining = status.remaining;
remaining = remaining == 0 ? order.makerAmount : remaining;
if (makingAmount > remaining) revert MakingGtRemaining();
remaining = remaining - makingAmount;
if (remaining == 0) status.isFilledOrCancelled = true;
status.remaining = remaining;
}
| 9,433,486 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.8.0;
import {ManagedIdentity} from "../metatx/ManagedIdentity.sol";
/**
* Contract module which allows derived contracts to implement a mechanism for
* activating, or 'starting', a contract.
*
* This module is used through inheritance. It will make available the modifiers
* `whenNotStarted` and `whenStarted`, which can be applied to the functions of
* your contract. Those functions will only be 'startable' once the modifiers
* are put in place.
*/
abstract contract Startable is ManagedIdentity {
event Started(address account);
uint256 private _startedAt;
/**
* Modifier to make a function callable only when the contract has not started.
*/
modifier whenNotStarted() {
require(_startedAt == 0, "Startable: started");
_;
}
/**
* Modifier to make a function callable only when the contract has started.
*/
modifier whenStarted() {
require(_startedAt != 0, "Startable: not started");
_;
}
/**
* Constructor.
*/
constructor() {}
/**
* Returns the timestamp when the contract entered the started state.
* @return The timestamp when the contract entered the started state.
*/
function startedAt() public view returns (uint256) {
return _startedAt;
}
/**
* Triggers the started state.
* @dev Emits the Started event when the function is successfully called.
*/
function _start() internal virtual whenNotStarted {
_startedAt = block.timestamp;
emit Started(_msgSender());
}
}
|
Triggers the started state. Emits the Started event when the function is successfully called./
|
function _start() internal virtual whenNotStarted {
_startedAt = block.timestamp;
emit Started(_msgSender());
}
| 1,779,131 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {ECDSAUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
/// @title BNPL KYC store contract.
///
/// @notice
/// - Features:
/// **Create and store KYC status**
/// **Create a KYC bank node**
/// **Change the KYC mode**
/// **Check the KYC status**
/// **Approve or reject the applicant**
///
/// @author BNPL
contract BNPLKYCStore is Initializable, ReentrancyGuardUpgradeable {
using ECDSAUpgradeable for bytes32;
/// @dev [Domain id] => [KYC public key]
mapping(uint32 => address) public publicKeys;
/// @dev [encode(Domain, User)] => [Permissions]
mapping(uint256 => uint32) public domainPermissions;
/// @dev [encode(Domain, User)] => [KYC status]
mapping(uint256 => uint32) public userKycStatuses;
/// @dev [Proof hash] => [Use status]
mapping(bytes32 => uint8) public proofUsed;
/// @dev [Domain id] => [KYC mode]
mapping(uint32 => uint256) public domainKycMode;
uint32 public constant PROOF_MAGIC = 0xfc203827;
uint32 public constant DOMAIN_ADMIN_PERM = 0xffff;
/// @notice The current number of domains in the KYC store
uint32 public domainCount;
/// @dev Encode KYC domain and user address into a uint256
///
/// @param domain The domain id
/// @param user The address of user
/// @return KYCUserDomainKey Encoded user domain key
function encodeKYCUserDomainKey(uint32 domain, address user) internal pure returns (uint256) {
return (uint256(uint160(user)) << 32) | uint256(domain);
}
/// @dev Can only be operated by domain admin
modifier onlyDomainAdmin(uint32 domain) {
require(
domainPermissions[encodeKYCUserDomainKey(domain, msg.sender)] == DOMAIN_ADMIN_PERM,
"User must be an admin for this domain to perform this action"
);
_;
}
/// @notice Get domain permissions with domain id and user address
///
/// @param domain The domain id
/// @param user The address of user
/// @return DomainPermissions User's domain permissions
function getDomainPermissions(uint32 domain, address user) external view returns (uint32) {
return domainPermissions[encodeKYCUserDomainKey(domain, user)];
}
/// @dev Set domain permissions with domain id and user address
function _setDomainPermissions(
uint32 domain,
address user,
uint32 permissions
) internal {
domainPermissions[encodeKYCUserDomainKey(domain, user)] = permissions;
}
/// @notice Get user's kyc status under domain
///
/// @param domain The domain id
/// @param user The address of user
/// @return KYCStatusUser User's KYC status
function getKYCStatusUser(uint32 domain, address user) public view returns (uint32) {
return userKycStatuses[encodeKYCUserDomainKey(domain, user)];
}
/// @dev Verify that the operation and signature are valid
function _verifyProof(
uint32 domain,
address user,
uint32 status,
uint256 nonce,
bytes calldata signature
) internal {
require(domain != 0 && domain <= domainCount, "invalid domain");
require(publicKeys[domain] != address(0), "this domain is disabled");
bytes32 proofHash = getKYCSignatureHash(domain, user, status, nonce);
require(proofHash.toEthSignedMessageHash().recover(signature) == publicKeys[domain], "invalid signature");
require(proofUsed[proofHash] == 0, "proof already used");
proofUsed[proofHash] = 1;
}
/// @dev Set KYC status for user
function _setKYCStatusUser(
uint32 domain,
address user,
uint32 status
) internal {
userKycStatuses[encodeKYCUserDomainKey(domain, user)] = status;
}
/// @dev Bitwise OR the user's KYC status
function _orKYCStatusUser(
uint32 domain,
address user,
uint32 status
) internal {
userKycStatuses[encodeKYCUserDomainKey(domain, user)] |= status;
}
/// @notice Create a new KYC store domain
///
/// @param admin The address of domain admin
/// @param publicKey The KYC domain publicKey
/// @param kycMode The KYC mode
/// @return DomainId The new KYC domain id
function createNewKYCDomain(
address admin,
address publicKey,
uint256 kycMode
) external returns (uint32) {
require(admin != address(0), "cannot create a kyc domain with an empty user");
uint32 id = domainCount + 1;
domainCount = id;
_setDomainPermissions(id, admin, DOMAIN_ADMIN_PERM);
publicKeys[id] = publicKey;
domainKycMode[id] = kycMode;
return id;
}
/// @notice Set KYC domain public key for domain
///
/// - PRIVILEGES REQUIRED:
/// Domain admin
///
/// @param domain The KYC domain id
/// @param newPublicKey New KYC domain publickey
function setKYCDomainPublicKey(uint32 domain, address newPublicKey) external onlyDomainAdmin(domain) {
publicKeys[domain] = newPublicKey;
}
/// @notice Set KYC mode for domain
///
/// - PRIVILEGES REQUIRED:
/// Domain admin
///
/// @param domain The KYC domain id
/// @param mode The KYC mode
function setKYCDomainMode(uint32 domain, uint256 mode) external onlyDomainAdmin(domain) {
domainKycMode[domain] = mode;
}
/// @notice Check the KYC mode of the user under the specified domain
///
/// @param domain The KYC domain id
/// @param user The address of user
/// @param mode The KYC mode
/// @return result Return `1` if valid
function checkUserBasicBitwiseMode(
uint32 domain,
address user,
uint256 mode
) external view returns (uint256) {
require(domain != 0 && domain <= domainCount, "invalid domain");
require(
user != address(0) && ((domainKycMode[domain] & mode) == 0 || (mode & getKYCStatusUser(domain, user) != 0)),
"invalid user permissions"
);
return 1;
}
/// @notice Allow domain admin to set KYC status for user
///
/// - PRIVILEGES REQUIRED:
/// Domain admin
///
/// @param domain The KYC domain id
/// @param user The address of user
/// @param status The status number
function setKYCStatusUser(
uint32 domain,
address user,
uint32 status
) external onlyDomainAdmin(domain) {
_setKYCStatusUser(domain, user, status);
}
/// @notice Returns KYC signature (encoded data)
///
/// @param domain The KYC domain id
/// @param user The address of user
/// @param status The status number
/// @param nonce The nonce
/// @return KYCSignaturePayload The KYC signature (encoded data)
function getKYCSignaturePayload(
uint32 domain,
address user,
uint32 status,
uint256 nonce
) public pure returns (bytes memory) {
return (
abi.encode(
((uint256(PROOF_MAGIC) << 224) |
(uint256(uint160(user)) << 64) |
(uint256(domain) << 32) |
uint256(status)),
nonce
)
);
}
/// @notice Returns KYC signature (keccak256 hash)
///
/// @param domain The KYC domain id
/// @param user The address of user
/// @param status The status number
/// @param nonce The nonce
/// @return KYCSignatureHash The KYC signature (keccak256 hash)
function getKYCSignatureHash(
uint32 domain,
address user,
uint32 status,
uint256 nonce
) public pure returns (bytes32) {
return keccak256(getKYCSignaturePayload(domain, user, status, nonce));
}
/// @notice Bitwise OR the user's KYC status
///
/// - SIGNATURE REQUIRED:
/// Domain admin
///
/// @param domain The KYC domain id
/// @param user The address of user
/// @param status The status number to bitwise OR
/// @param nonce The nonce
/// @param signature The domain admin signature (proof)
function orKYCStatusWithProof(
uint32 domain,
address user,
uint32 status,
uint256 nonce,
bytes calldata signature
) external {
_verifyProof(domain, user, status, nonce, signature);
_orKYCStatusUser(domain, user, status);
}
/// @notice Clear KYC status for user
///
/// - SIGNATURE REQUIRED:
/// Domain admin
///
/// @param domain The KYC domain id
/// @param user The address of user
/// @param nonce The nonce
/// @param signature The domain admin signature (proof)
function clearKYCStatusWithProof(
uint32 domain,
address user,
uint256 nonce,
bytes calldata signature
) external {
_verifyProof(domain, user, 1, nonce, signature);
_setKYCStatusUser(domain, user, 1);
}
/// @dev This contract is called through the proxy.
function initialize() external initializer nonReentrant {
__ReentrancyGuard_init_unchained();
}
}
|
Get user's kyc status under domain domain The domain id user The address of user return KYCStatusUser User's KYC status
|
function getKYCStatusUser(uint32 domain, address user) public view returns (uint32) {
return userKycStatuses[encodeKYCUserDomainKey(domain, user)];
}
| 5,438,280 |
pragma solidity ^0.4.24;
contract FFFevents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d short only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d short only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract modularShort is FFFevents {}
contract FFFultra is modularShort {
using SafeMath for *;
using NameFilter for string;
using FFFKeysCalcShort for uint256;
PlayerBookInterface private PlayerBook;
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
address private admin = msg.sender;
address private yyyy;
address private gggg;
string constant public name = "ethfomo3d";
string constant public symbol = "ethfomo3d";
uint256 private rndExtra_ = 0; // length of the very first ICO
uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 1 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
uint256 constant private preIcoMax_ = 50000000000000000000; // max ico num
uint256 constant private preIcoPerEth_ = 1500000000000000000; // in ico, per addr eth
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => FFFdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => FFFdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => FFFdatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => FFFdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => FFFdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor(PlayerBookInterface _PlayerBook, address _yyyy, address _gggg)
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = FFFdatasets.TeamFee(60,8); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = FFFdatasets.TeamFee(60,8); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = FFFdatasets.TeamFee(60,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = FFFdatasets.TeamFee(60,8); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = FFFdatasets.PotSplit(30,10); //48% to winner, 25% to next round, 2% to com
potSplit_[1] = FFFdatasets.PotSplit(30,10); //48% to winner, 25% to next round, 2% to com
potSplit_[2] = FFFdatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com
potSplit_[3] = FFFdatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com
PlayerBook = _PlayerBook;
yyyy = _yyyy;
gggg = _gggg;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
FFFdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
FFFdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
FFFdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
FFFdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
FFFdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
FFFdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
FFFdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
FFFdatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit FFFevents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit FFFevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit FFFevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit FFFevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit FFFevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, FFFdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit FFFevents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, FFFdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit FFFevents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, FFFdatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < preIcoMax_ && plyrRnds_[_pID][_rID].eth.add(_eth) > preIcoPerEth_)
{
uint256 _availableLimit = (preIcoPerEth_).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(FFFdatasets.EventReturns memory _eventData_)
private
returns (FFFdatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, FFFdatasets.EventReturns memory _eventData_)
private
returns (FFFdatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(FFFdatasets.EventReturns memory _eventData_)
private
returns (FFFdatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
_com = _com.add(_p3d.sub(_p3d / 2));
yyyy.transfer((_com.mul(80)/100));
gggg.transfer((_com.sub((_com.mul(80)/100))));
_res = _res.add(_p3d / 2);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, FFFdatasets.EventReturns memory _eventData_)
private
returns(FFFdatasets.EventReturns)
{
// pay 3% out to community rewards
uint256 _p1 = _eth / 100;
uint256 _com = _eth / 50;
_com = _com.add(_p1);
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit FFFevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_com = (_com.add(_aff));
}
// pay out p3d
uint256 _p3d;
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
// deposit to divies contract
uint256 _potAmount = _p3d / 2;
_com = (_com.add((_p3d.sub(_potAmount))));
round_[_rID].pot = round_[_rID].pot.add(_potAmount);
// set up event data
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
yyyy.transfer((_com.mul(80)/100));
gggg.transfer((_com.sub((_com.mul(80)/100))));
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit FFFevents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, FFFdatasets.EventReturns memory _eventData_)
private
returns(FFFdatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, FFFdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit FFFevents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(msg.sender == admin, "only admin can activate");
// can only be ran once
require(activated_ == false, "FOMO Short already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library FFFdatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library FFFKeysCalcShort {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
/**
* @title -Name Filter- v0.1.9
* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐
* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐
* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘
* _____ _____
* (, / /) /) /) (, / /) /)
* ┌─┐ / _ (/_ // // / _ // _ __ _(/
* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_
* ┴ ┴ / / .-/ _____ (__ /
* (__ / (_/ (, / /)™
* / __ __ __ __ _ __ __ _ _/_ _ _(/
* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_
* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018
* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/
* _ __ _ ____ ____ _ _ _____ ____ ___
*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============*
*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============*
*
* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐
* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │
* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘
*/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
essentially the same as buy, but instead of you sending ether from your wallet, it uses your unwithdrawn earnings. -functionhash- 0x349cdcac (using ID for affiliate) -functionhash- 0x82bfc739 (using address for affiliate) -functionhash- 0x079ce327 (using name for affiliate) _affCode the ID/address/name of the player who gets the affiliate fee _team what team is the player playing for? _eth amount of earnings to use (remainder returned to gen vault)/ set up our tx event data fetch player ID manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz use last stored affiliate code if affiliate code was given & its not the same as previously stored update last affiliate
|
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
FFFdatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
plyr_[_pID].laff = _affCode;
}
}
| 13,501,280 |
// SPDX-License-Identifier: MIT
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.7.3;
import "./IERC20.sol";
import "./SafeMath.sol";
import "./ABDKMath64x64.sol";
import "./IAssimilator.sol";
import "./IOracle.sol";
contract XsgdToUsdAssimilator is IAssimilator {
using ABDKMath64x64 for int128;
using ABDKMath64x64 for uint256;
using SafeMath for uint256;
IERC20 private constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
IOracle private constant oracle = IOracle(0xe25277fF4bbF9081C75Ab0EB13B4A13a721f3E13);
IERC20 private constant xsgd = IERC20(0x70e8dE73cE538DA2bEEd35d14187F6959a8ecA96);
// solhint-disable-next-line
constructor() {}
function getRate() public view override returns (uint256) {
(, int256 price, , , ) = oracle.latestRoundData();
return uint256(price);
}
// takes raw xsgd amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRawAndGetBalance(uint256 _amount) external override returns (int128 amount_, int128 balance_) {
bool _transferSuccess = xsgd.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/XSGD-transfer-from-failed");
uint256 _balance = xsgd.balanceOf(address(this));
uint256 _rate = getRate();
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// takes raw xsgd amount, transfers it in, calculates corresponding numeraire amount and returns it
function intakeRaw(uint256 _amount) external override returns (int128 amount_) {
bool _transferSuccess = xsgd.transferFrom(msg.sender, address(this), _amount);
require(_transferSuccess, "Curve/XSGD-transfer-from-failed");
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// takes a numeraire amount, calculates the raw amount of xsgd, transfers it in and returns the corresponding raw amount
function intakeNumeraire(int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
bool _transferSuccess = xsgd.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/XSGD-transfer-from-failed");
}
// takes a numeraire amount, calculates the raw amount of xsgd, transfers it in and returns the corresponding raw amount
function intakeNumeraireLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external override returns (uint256 amount_) {
uint256 _xsgdBal = xsgd.balanceOf(_addr);
if (_xsgdBal <= 0) return 0;
// 1e6
_xsgdBal = _xsgdBal.mul(1e18).div(_baseWeight);
// 1e6
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e6).div(_xsgdBal);
amount_ = (_amount.mulu(1e6) * 1e6) / _rate;
bool _transferSuccess = xsgd.transferFrom(msg.sender, address(this), amount_);
require(_transferSuccess, "Curve/XSGD-transfer-failed");
}
// takes a raw amount of xsgd and transfers it out, returns numeraire value of the raw amount
function outputRawAndGetBalance(address _dst, uint256 _amount)
external
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
uint256 _xsgdAmount = ((_amount) * _rate) / 1e8;
bool _transferSuccess = xsgd.transfer(_dst, _xsgdAmount);
require(_transferSuccess, "Curve/XSGD-transfer-failed");
uint256 _balance = xsgd.balanceOf(address(this));
amount_ = _xsgdAmount.divu(1e6);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// takes a raw amount of xsgd and transfers it out, returns numeraire value of the raw amount
function outputRaw(address _dst, uint256 _amount) external override returns (int128 amount_) {
uint256 _rate = getRate();
uint256 _xsgdAmount = (_amount * _rate) / 1e8;
bool _transferSuccess = xsgd.transfer(_dst, _xsgdAmount);
require(_transferSuccess, "Curve/XSGD-transfer-failed");
amount_ = _xsgdAmount.divu(1e6);
}
// takes a numeraire value of xsgd, figures out the raw amount, transfers raw amount out, and returns raw amount
function outputNumeraire(address _dst, int128 _amount) external override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
bool _transferSuccess = xsgd.transfer(_dst, amount_);
require(_transferSuccess, "Curve/XSGD-transfer-failed");
}
// takes a numeraire amount and returns the raw amount
function viewRawAmount(int128 _amount) external view override returns (uint256 amount_) {
uint256 _rate = getRate();
amount_ = (_amount.mulu(1e6) * 1e8) / _rate;
}
function viewRawAmountLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr,
int128 _amount
) external view override returns (uint256 amount_) {
uint256 _xsgdBal = xsgd.balanceOf(_addr);
if (_xsgdBal <= 0) return 0;
// 1e6
_xsgdBal = _xsgdBal.mul(1e18).div(_baseWeight);
// 1e6
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e6).div(_xsgdBal);
amount_ = (_amount.mulu(1e6) * 1e6) / _rate;
}
// takes a raw amount and returns the numeraire amount
function viewNumeraireAmount(uint256 _amount) external view override returns (int128 amount_) {
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case xsgd
function viewNumeraireBalance(address _addr) external view override returns (int128 balance_) {
uint256 _rate = getRate();
uint256 _balance = xsgd.balanceOf(_addr);
if (_balance <= 0) return ABDKMath64x64.fromUInt(0);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case xsgd
function viewNumeraireAmountAndBalance(address _addr, uint256 _amount)
external
view
override
returns (int128 amount_, int128 balance_)
{
uint256 _rate = getRate();
amount_ = ((_amount * _rate) / 1e8).divu(1e6);
uint256 _balance = xsgd.balanceOf(_addr);
balance_ = ((_balance * _rate) / 1e8).divu(1e6);
}
// views the numeraire value of the current balance of the reserve, in this case xsgd
// instead of calculating with chainlink's "rate" it'll be determined by the existing
// token ratio
// Mainly to protect LP from losing
function viewNumeraireBalanceLPRatio(
uint256 _baseWeight,
uint256 _quoteWeight,
address _addr
) external view override returns (int128 balance_) {
uint256 _xsgdBal = xsgd.balanceOf(_addr);
if (_xsgdBal <= 0) return ABDKMath64x64.fromUInt(0);
uint256 _usdcBal = usdc.balanceOf(_addr).mul(1e18).div(_quoteWeight);
// Rate is in 1e6
uint256 _rate = _usdcBal.mul(1e18).div(_xsgdBal.mul(1e18).div(_baseWeight));
balance_ = ((_xsgdBal * _rate) / 1e6).divu(1e18);
}
}
|
takes a raw amount of xsgd and transfers it out, returns numeraire value of the raw amount
|
function outputRaw(address _dst, uint256 _amount) external override returns (int128 amount_) {
uint256 _rate = getRate();
uint256 _xsgdAmount = (_amount * _rate) / 1e8;
bool _transferSuccess = xsgd.transfer(_dst, _xsgdAmount);
require(_transferSuccess, "Curve/XSGD-transfer-failed");
amount_ = _xsgdAmount.divu(1e6);
}
| 10,049,909 |
./full_match/5/0x61474Ec2b66fd4b6206BACC5795DD8Bf5813c476/sources/localhost/contracts/GatebridgeV2Router.sol
|
REMOVE LIQUIDITY here could use map
|
function removeLiquidityAdmin(
bytes32 resourceId,
uint liquidity,
uint chainId,
uint[] calldata amountMin,
uint[] calldata chainIds,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amount) {
uint localChainId = IGatebridgeV2Factory(factory).factoryChainId();
address pool = GatebridgeV2Library.LPTokenByResourceId(factory, resourceId, localChainId);
if (chainId == localChainId) {
amount = IGatebridgeV2LPToken(pool).burn(to, liquidity);
amount = IGatebridgeV2LPToken(pool).burnOther(chainId, liquidity);
}
for (uint i; i < chainIds.length - 1; i++) {
if (chainIds[i] == localChainId) {
require(amount >= amountMin[i], 'GateswapV2Router: INSUFFICIENT_A_AMOUNT');
break;
}
}
}
| 1,945,257 |
pragma solidity ^0.4.24;
interface ConflictResolutionInterface {
function minHouseStake(uint activeGames) external pure returns(uint);
function maxBalance() external pure returns(int);
function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) external pure returns(bool);
function endGameConflict(
uint8 _gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
bytes32 _serverSeed,
bytes32 _playerSeed
)
external
view
returns(int);
function serverForceGameEnd(
uint8 gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
uint _endInitiatedTime
)
external
view
returns(int);
function playerForceGameEnd(
uint8 _gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
uint _endInitiatedTime
)
external
view
returns(int);
}
library MathUtil {
/**
* @dev Returns the absolute value of _val.
* @param _val value
* @return The absolute value of _val.
*/
function abs(int _val) internal pure returns(uint) {
if (_val < 0) {
return uint(-_val);
} else {
return uint(_val);
}
}
/**
* @dev Calculate maximum.
*/
function max(uint _val1, uint _val2) internal pure returns(uint) {
return _val1 >= _val2 ? _val1 : _val2;
}
/**
* @dev Calculate minimum.
*/
function min(uint _val1, uint _val2) internal pure returns(uint) {
return _val1 <= _val2 ? _val1 : _val2;
}
}
contract Ownable {
address public owner;
address public pendingOwner;
event LogOwnerShipTransferred(address indexed previousOwner, address indexed newOwner);
event LogOwnerShipTransferInitiated(address indexed previousOwner, address indexed newOwner);
/**
* @dev Modifier, which throws if called by other account than owner.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Set contract creator as initial owner
*/
constructor() public {
owner = msg.sender;
pendingOwner = address(0);
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
pendingOwner = _newOwner;
emit LogOwnerShipTransferInitiated(owner, _newOwner);
}
/**
* @dev New owner can accpet ownership.
*/
function claimOwnership() public onlyPendingOwner {
emit LogOwnerShipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract ConflictResolutionManager is Ownable {
/// @dev Conflict resolution contract.
ConflictResolutionInterface public conflictRes;
/// @dev New Conflict resolution contract.
address public newConflictRes = 0;
/// @dev Time update of new conflict resolution contract was initiated.
uint public updateTime = 0;
/// @dev Min time before new conflict res contract can be activated after initiating update.
uint public constant MIN_TIMEOUT = 3 days;
/// @dev Min time before new conflict res contract can be activated after initiating update.
uint public constant MAX_TIMEOUT = 6 days;
/// @dev Update of conflict resolution contract was initiated.
event LogUpdatingConflictResolution(address newConflictResolutionAddress);
/// @dev New conflict resolution contract is active.
event LogUpdatedConflictResolution(address newConflictResolutionAddress);
/**
* @dev Constructor
* @param _conflictResAddress conflict resolution contract address.
*/
constructor(address _conflictResAddress) public {
conflictRes = ConflictResolutionInterface(_conflictResAddress);
}
/**
* @dev Initiate conflict resolution contract update.
* @param _newConflictResAddress New conflict resolution contract address.
*/
function updateConflictResolution(address _newConflictResAddress) public onlyOwner {
newConflictRes = _newConflictResAddress;
updateTime = block.timestamp;
emit LogUpdatingConflictResolution(_newConflictResAddress);
}
/**
* @dev Active new conflict resolution contract.
*/
function activateConflictResolution() public onlyOwner {
require(newConflictRes != 0);
require(updateTime != 0);
require(updateTime + MIN_TIMEOUT <= block.timestamp && block.timestamp <= updateTime + MAX_TIMEOUT);
conflictRes = ConflictResolutionInterface(newConflictRes);
newConflictRes = 0;
updateTime = 0;
emit LogUpdatedConflictResolution(newConflictRes);
}
}
contract Pausable is Ownable {
/// @dev Is contract paused.
bool public paused = false;
/// @dev Time pause was called
uint public timePaused = 0;
/// @dev Modifier, which only allows function execution if not paused.
modifier onlyNotPaused() {
require(!paused);
_;
}
/// @dev Modifier, which only allows function execution if paused.
modifier onlyPaused() {
require(paused);
_;
}
/// @dev Modifier, which only allows function execution if paused longer than timeSpan.
modifier onlyPausedSince(uint timeSpan) {
require(paused && timePaused + timeSpan <= block.timestamp);
_;
}
/// @dev Event is fired if paused.
event LogPause();
/// @dev Event is fired if pause is ended.
event LogUnpause();
/**
* @dev Pause contract. No new game sessions can be created.
*/
function pause() public onlyOwner onlyNotPaused {
paused = true;
timePaused = block.timestamp;
emit LogPause();
}
/**
* @dev Unpause contract.
*/
function unpause() public onlyOwner onlyPaused {
paused = false;
timePaused = 0;
emit LogUnpause();
}
}
contract Destroyable is Pausable {
/// @dev After pausing the contract for 20 days owner can selfdestruct it.
uint public constant TIMEOUT_DESTROY = 20 days;
/**
* @dev Destroy contract and transfer ether to address _targetAddress.
*/
function destroy() public onlyOwner onlyPausedSince(TIMEOUT_DESTROY) {
selfdestruct(owner);
}
}
contract GameChannelBase is Destroyable, ConflictResolutionManager {
/// @dev Different game session states.
enum GameStatus {
ENDED, ///< @dev Game session is ended.
ACTIVE, ///< @dev Game session is active.
PLAYER_INITIATED_END, ///< @dev Player initiated non regular end.
SERVER_INITIATED_END ///< @dev Server initiated non regular end.
}
/// @dev Reason game session ended.
enum ReasonEnded {
REGULAR_ENDED, ///< @dev Game session is regularly ended.
END_FORCED_BY_SERVER, ///< @dev Player did not respond. Server forced end.
END_FORCED_BY_PLAYER ///< @dev Server did not respond. Player forced end.
}
struct Game {
/// @dev Game session status.
GameStatus status;
/// @dev Player's stake.
uint128 stake;
/// @dev Last game round info if not regularly ended.
/// If game session is ended normally this data is not used.
uint8 gameType;
uint32 roundId;
uint16 betNum;
uint betValue;
int balance;
bytes32 playerSeed;
bytes32 serverSeed;
uint endInitiatedTime;
}
/// @dev Minimal time span between profit transfer.
uint public constant MIN_TRANSFER_TIMESPAN = 1 days;
/// @dev Maximal time span between profit transfer.
uint public constant MAX_TRANSFER_TIMSPAN = 6 * 30 days;
bytes32 public constant TYPE_HASH = keccak256(abi.encodePacked(
"uint32 Round Id",
"uint8 Game Type",
"uint16 Number",
"uint Value (Wei)",
"int Current Balance (Wei)",
"bytes32 Server Hash",
"bytes32 Player Hash",
"uint Game Id",
"address Contract Address"
));
/// @dev Current active game sessions.
uint public activeGames = 0;
/// @dev Game session id counter. Points to next free game session slot. So gameIdCntr -1 is the
// number of game sessions created.
uint public gameIdCntr;
/// @dev Only this address can accept and end games.
address public serverAddress;
/// @dev Address to transfer profit to.
address public houseAddress;
/// @dev Current house stake.
uint public houseStake = 0;
/// @dev House profit since last profit transfer.
int public houseProfit = 0;
/// @dev Min value player needs to deposit for creating game session.
uint128 public minStake;
/// @dev Max value player can deposit for creating game session.
uint128 public maxStake;
/// @dev Timeout until next profit transfer is allowed.
uint public profitTransferTimeSpan = 14 days;
/// @dev Last time profit transferred to house.
uint public lastProfitTransferTimestamp;
/// @dev Maps gameId to game struct.
mapping (uint => Game) public gameIdGame;
/// @dev Maps player address to current player game id.
mapping (address => uint) public playerGameId;
/// @dev Maps player address to pending returns.
mapping (address => uint) public pendingReturns;
/// @dev Modifier, which only allows to execute if house stake is high enough.
modifier onlyValidHouseStake(uint _activeGames) {
uint minHouseStake = conflictRes.minHouseStake(_activeGames);
require(houseStake >= minHouseStake);
_;
}
/// @dev Modifier to check if value send fulfills player stake requirements.
modifier onlyValidValue() {
require(minStake <= msg.value && msg.value <= maxStake);
_;
}
/// @dev Modifier, which only allows server to call function.
modifier onlyServer() {
require(msg.sender == serverAddress);
_;
}
/// @dev Modifier, which only allows to set valid transfer timeouts.
modifier onlyValidTransferTimeSpan(uint transferTimeout) {
require(transferTimeout >= MIN_TRANSFER_TIMESPAN
&& transferTimeout <= MAX_TRANSFER_TIMSPAN);
_;
}
/// @dev This event is fired when player creates game session.
event LogGameCreated(address indexed player, uint indexed gameId, uint128 stake, bytes32 indexed serverEndHash, bytes32 playerEndHash);
/// @dev This event is fired when player requests conflict end.
event LogPlayerRequestedEnd(address indexed player, uint indexed gameId);
/// @dev This event is fired when server requests conflict end.
event LogServerRequestedEnd(address indexed player, uint indexed gameId);
/// @dev This event is fired when game session is ended.
event LogGameEnded(address indexed player, uint indexed gameId, uint32 roundId, int balance, ReasonEnded reason);
/// @dev this event is fired when owner modifies player's stake limits.
event LogStakeLimitsModified(uint minStake, uint maxStake);
/**
* @dev Contract constructor.
* @param _serverAddress Server address.
* @param _minStake Min value player needs to deposit to create game session.
* @param _maxStake Max value player can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address.
* @param _houseAddress House address to move profit to.
*/
constructor(
address _serverAddress,
uint128 _minStake,
uint128 _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCntr
)
public
ConflictResolutionManager(_conflictResAddress)
{
require(_minStake > 0 && _minStake <= _maxStake);
require(_gameIdCntr > 0);
gameIdCntr = _gameIdCntr;
serverAddress = _serverAddress;
houseAddress = _houseAddress;
lastProfitTransferTimestamp = block.timestamp;
minStake = _minStake;
maxStake = _maxStake;
}
/**
* @notice Withdraw pending returns.
*/
function withdraw() public {
uint toTransfer = pendingReturns[msg.sender];
require(toTransfer > 0);
pendingReturns[msg.sender] = 0;
msg.sender.transfer(toTransfer);
}
/**
* @notice Transfer house profit to houseAddress.
*/
function transferProfitToHouse() public {
require(lastProfitTransferTimestamp + profitTransferTimeSpan <= block.timestamp);
// update last transfer timestamp
lastProfitTransferTimestamp = block.timestamp;
if (houseProfit <= 0) {
// no profit to transfer
return;
}
// houseProfit is gt 0 => safe to cast
uint toTransfer = uint(houseProfit);
assert(houseStake >= toTransfer);
houseProfit = 0;
houseStake = houseStake - toTransfer;
houseAddress.transfer(toTransfer);
}
/**
* @dev Set profit transfer time span.
*/
function setProfitTransferTimeSpan(uint _profitTransferTimeSpan)
public
onlyOwner
onlyValidTransferTimeSpan(_profitTransferTimeSpan)
{
profitTransferTimeSpan = _profitTransferTimeSpan;
}
/**
* @dev Increase house stake by msg.value
*/
function addHouseStake() public payable onlyOwner {
houseStake += msg.value;
}
/**
* @dev Withdraw house stake.
*/
function withdrawHouseStake(uint value) public onlyOwner {
uint minHouseStake = conflictRes.minHouseStake(activeGames);
require(value <= houseStake && houseStake - value >= minHouseStake);
require(houseProfit <= 0 || uint(houseProfit) <= houseStake - value);
houseStake = houseStake - value;
owner.transfer(value);
}
/**
* @dev Withdraw house stake and profit.
*/
function withdrawAll() public onlyOwner onlyPausedSince(3 days) {
houseProfit = 0;
uint toTransfer = houseStake;
houseStake = 0;
owner.transfer(toTransfer);
}
/**
* @dev Set new house address.
* @param _houseAddress New house address.
*/
function setHouseAddress(address _houseAddress) public onlyOwner {
houseAddress = _houseAddress;
}
/**
* @dev Set stake min and max value.
* @param _minStake Min stake.
* @param _maxStake Max stake.
*/
function setStakeRequirements(uint128 _minStake, uint128 _maxStake) public onlyOwner {
require(_minStake > 0 && _minStake <= _maxStake);
minStake = _minStake;
maxStake = _maxStake;
emit LogStakeLimitsModified(minStake, maxStake);
}
/**
* @dev Close game session.
* @param _game Game session data.
* @param _gameId Id of game session.
* @param _playerAddress Player's address of game session.
* @param _reason Reason for closing game session.
* @param _balance Game session balance.
*/
function closeGame(
Game storage _game,
uint _gameId,
uint32 _roundId,
address _playerAddress,
ReasonEnded _reason,
int _balance
)
internal
{
_game.status = GameStatus.ENDED;
assert(activeGames > 0);
activeGames = activeGames - 1;
payOut(_playerAddress, _game.stake, _balance);
emit LogGameEnded(_playerAddress, _gameId, _roundId, _balance, _reason);
}
/**
* @dev End game by paying out player and server.
* @param _playerAddress Player's address.
* @param _stake Player's stake.
* @param _balance Player's balance.
*/
function payOut(address _playerAddress, uint128 _stake, int _balance) internal {
assert(_balance <= conflictRes.maxBalance());
assert((int(_stake) + _balance) >= 0); // safe as _balance (see line above), _stake ranges are fixed.
uint valuePlayer = uint(int(_stake) + _balance); // safe as _balance, _stake ranges are fixed.
if (_balance > 0 && int(houseStake) < _balance) { // safe to cast houseStake is limited.
// Should never happen!
// House is bankrupt.
// Payout left money.
valuePlayer = houseStake;
}
houseProfit = houseProfit - _balance;
int newHouseStake = int(houseStake) - _balance; // safe to cast and sub as houseStake, balance ranges are fixed
assert(newHouseStake >= 0);
houseStake = uint(newHouseStake);
pendingReturns[_playerAddress] += valuePlayer;
if (pendingReturns[_playerAddress] > 0) {
safeSend(_playerAddress);
}
}
/**
* @dev Send value of pendingReturns[_address] to _address.
* @param _address Address to send value to.
*/
function safeSend(address _address) internal {
uint valueToSend = pendingReturns[_address];
assert(valueToSend > 0);
pendingReturns[_address] = 0;
if (_address.send(valueToSend) == false) {
pendingReturns[_address] = valueToSend;
}
}
/**
* @dev Verify signature of given data. Throws on verification failure.
* @param _sig Signature of given data in the form of rsv.
* @param _address Address of signature signer.
*/
function verifySig(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _sig,
address _address
)
internal
view
{
// check if this is the correct contract
address contractAddress = this;
require(_contractAddress == contractAddress);
bytes32 roundHash = calcHash(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress
);
verify(
roundHash,
_sig,
_address
);
}
/**
* @dev Check if _sig is valid signature of _hash. Throws if invalid signature.
* @param _hash Hash to check signature of.
* @param _sig Signature of _hash.
* @param _address Address of signer.
*/
function verify(
bytes32 _hash,
bytes _sig,
address _address
)
internal
pure
{
bytes32 r;
bytes32 s;
uint8 v;
(r, s, v) = signatureSplit(_sig);
address addressRecover = ecrecover(_hash, v, r, s);
require(addressRecover == _address);
}
/**
* @dev Calculate typed hash of given data (compare eth_signTypedData).
* @return Hash of given data.
*/
function calcHash(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress
)
private
pure
returns(bytes32)
{
bytes32 dataHash = keccak256(abi.encodePacked(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress
));
return keccak256(abi.encodePacked(
TYPE_HASH,
dataHash
));
}
/**
* @dev Split the given signature of the form rsv in r s v. v is incremented with 27 if
* it is below 2.
* @param _signature Signature to split.
* @return r s v
*/
function signatureSplit(bytes _signature)
private
pure
returns (bytes32 r, bytes32 s, uint8 v)
{
require(_signature.length == 65);
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := and(mload(add(_signature, 65)), 0xff)
}
if (v < 2) {
v = v + 27;
}
}
}
contract GameChannelConflict is GameChannelBase {
/**
* @dev Contract constructor.
* @param _serverAddress Server address.
* @param _minStake Min value player needs to deposit to create game session.
* @param _maxStake Max value player can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address
* @param _houseAddress House address to move profit to
*/
constructor(
address _serverAddress,
uint128 _minStake,
uint128 _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCtr
)
public
GameChannelBase(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _gameIdCtr)
{
// nothing to do
}
/**
* @dev Used by server if player does not end game session.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server seed for this bet.
* @param _playerHash Hash of player seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _playerSig Player signature of this bet.
* @param _playerAddress Address of player.
* @param _serverSeed Server seed for this bet.
* @param _playerSeed Player seed for this bet.
*/
function serverEndGameConflict(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _playerSig,
address _playerAddress,
bytes32 _serverSeed,
bytes32 _playerSeed
)
public
onlyServer
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_playerSig,
_playerAddress
);
serverEndGameConflictImpl(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_serverSeed,
_playerSeed,
_gameId,
_playerAddress
);
}
/**
* @notice Can be used by player if server does not answer to the end game session request.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server seed for this bet.
* @param _playerHash Hash of player seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _serverSig Server signature of this bet.
* @param _playerSeed Player seed for this bet.
*/
function playerEndGameConflict(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _serverSig,
bytes32 _playerSeed
)
public
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_serverSig,
serverAddress
);
playerEndGameConflictImpl(
_roundId,
_gameType,
_num,
_value,
_balance,
_playerHash,
_playerSeed,
_gameId,
msg.sender
);
}
/**
* @notice Cancel active game without playing. Useful if server stops responding before
* one game is played.
* @param _gameId Game session id.
*/
function playerCancelActiveGame(uint _gameId) public {
address playerAddress = msg.sender;
uint gameId = playerGameId[playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
if (game.status == GameStatus.ACTIVE) {
game.endInitiatedTime = block.timestamp;
game.status = GameStatus.PLAYER_INITIATED_END;
emit LogPlayerRequestedEnd(msg.sender, gameId);
} else if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == 0) {
closeGame(game, gameId, 0, playerAddress, ReasonEnded.REGULAR_ENDED, 0);
} else {
revert();
}
}
/**
* @dev Cancel active game without playing. Useful if player starts game session and
* does not play.
* @param _playerAddress Players' address.
* @param _gameId Game session id.
*/
function serverCancelActiveGame(address _playerAddress, uint _gameId) public onlyServer {
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
if (game.status == GameStatus.ACTIVE) {
game.endInitiatedTime = block.timestamp;
game.status = GameStatus.SERVER_INITIATED_END;
emit LogServerRequestedEnd(msg.sender, gameId);
} else if (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId == 0) {
closeGame(game, gameId, 0, _playerAddress, ReasonEnded.REGULAR_ENDED, 0);
} else {
revert();
}
}
/**
* @dev Force end of game if player does not respond. Only possible after a certain period of time
* to give the player a chance to respond.
* @param _playerAddress Player's address.
*/
function serverForceGameEnd(address _playerAddress, uint _gameId) public onlyServer {
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
require(game.status == GameStatus.SERVER_INITIATED_END);
// theoretically we have enough data to calculate winner
// but as player did not respond assume he has lost.
int newBalance = conflictRes.serverForceGameEnd(
game.gameType,
game.betNum,
game.betValue,
game.balance,
game.stake,
game.endInitiatedTime
);
closeGame(game, gameId, game.roundId, _playerAddress, ReasonEnded.END_FORCED_BY_SERVER, newBalance);
}
/**
* @notice Force end of game if server does not respond. Only possible after a certain period of time
* to give the server a chance to respond.
*/
function playerForceGameEnd(uint _gameId) public {
address playerAddress = msg.sender;
uint gameId = playerGameId[playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
require(game.status == GameStatus.PLAYER_INITIATED_END);
int newBalance = conflictRes.playerForceGameEnd(
game.gameType,
game.betNum,
game.betValue,
game.balance,
game.stake,
game.endInitiatedTime
);
closeGame(game, gameId, game.roundId, playerAddress, ReasonEnded.END_FORCED_BY_PLAYER, newBalance);
}
/**
* @dev Conflict handling implementation. Stores game data and timestamp if game
* is active. If server has already marked conflict for game session the conflict
* resolution contract is used (compare conflictRes).
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _playerSeed Player's seed for this bet.
* @param _gameId game Game session id.
* @param _playerAddress Player's address.
*/
function playerEndGameConflictImpl(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _playerHash,
bytes32 _playerSeed,
uint _gameId,
address _playerAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
int maxBalance = conflictRes.maxBalance();
require(gameId == _gameId);
require(_roundId > 0);
require(keccak256(abi.encodePacked(_playerSeed)) == _playerHash);
require(-int(game.stake) <= _balance && _balance <= maxBalance); // save to cast as ranges are fixed
require(conflictRes.isValidBet(_gameType, _num, _value));
require(int(game.stake) + _balance - int(_value) >= 0); // save to cast as ranges are fixed
if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == _roundId) {
game.playerSeed = _playerSeed;
endGameConflict(game, gameId, _playerAddress);
} else if (game.status == GameStatus.ACTIVE
|| (game.status == GameStatus.SERVER_INITIATED_END && game.roundId < _roundId)) {
game.status = GameStatus.PLAYER_INITIATED_END;
game.endInitiatedTime = block.timestamp;
game.roundId = _roundId;
game.gameType = _gameType;
game.betNum = _num;
game.betValue = _value;
game.balance = _balance;
game.playerSeed = _playerSeed;
game.serverSeed = bytes32(0);
emit LogPlayerRequestedEnd(msg.sender, gameId);
} else {
revert();
}
}
/**
* @dev Conflict handling implementation. Stores game data and timestamp if game
* is active. If player has already marked conflict for game session the conflict
* resolution contract is used (compare conflictRes).
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server's seed for this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _serverSeed Server's seed for this bet.
* @param _playerSeed Player's seed for this bet.
* @param _playerAddress Player's address.
*/
function serverEndGameConflictImpl(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
bytes32 _serverSeed,
bytes32 _playerSeed,
uint _gameId,
address _playerAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
int maxBalance = conflictRes.maxBalance();
require(gameId == _gameId);
require(_roundId > 0);
require(keccak256(abi.encodePacked(_serverSeed)) == _serverHash);
require(keccak256(abi.encodePacked(_playerSeed)) == _playerHash);
require(-int(game.stake) <= _balance && _balance <= maxBalance); // save to cast as ranges are fixed
require(conflictRes.isValidBet(_gameType, _num, _value));
require(int(game.stake) + _balance - int(_value) >= 0); // save to cast as ranges are fixed
if (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId == _roundId) {
game.serverSeed = _serverSeed;
endGameConflict(game, gameId, _playerAddress);
} else if (game.status == GameStatus.ACTIVE
|| (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId < _roundId)) {
game.status = GameStatus.SERVER_INITIATED_END;
game.endInitiatedTime = block.timestamp;
game.roundId = _roundId;
game.gameType = _gameType;
game.betNum = _num;
game.betValue = _value;
game.balance = _balance;
game.serverSeed = _serverSeed;
game.playerSeed = _playerSeed;
emit LogServerRequestedEnd(_playerAddress, gameId);
} else {
revert();
}
}
/**
* @dev End conflicting game.
* @param _game Game session data.
* @param _gameId Game session id.
* @param _playerAddress Player's address.
*/
function endGameConflict(Game storage _game, uint _gameId, address _playerAddress) private {
int newBalance = conflictRes.endGameConflict(
_game.gameType,
_game.betNum,
_game.betValue,
_game.balance,
_game.stake,
_game.serverSeed,
_game.playerSeed
);
closeGame(_game, _gameId, _game.roundId, _playerAddress, ReasonEnded.REGULAR_ENDED, newBalance);
}
}
contract GameChannel is GameChannelConflict {
/**
* @dev contract constructor
* @param _serverAddress Server address.
* @param _minStake Min value player needs to deposit to create game session.
* @param _maxStake Max value player can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address.
* @param _houseAddress House address to move profit to.
*/
constructor(
address _serverAddress,
uint128 _minStake,
uint128 _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCntr
)
public
GameChannelConflict(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _gameIdCntr)
{
// nothing to do
}
/**
* @notice Create games session request. msg.value needs to be valid stake value.
* @param _playerEndHash last entry of players' hash chain.
* @param _previousGameId player's previous game id, initial 0.
* @param _createBefore game can be only created before this timestamp.
* @param _serverEndHash last entry of server's hash chain.
* @param _serverSig server signature. See verifyCreateSig
*/
function createGame(
bytes32 _playerEndHash,
uint _previousGameId,
uint _createBefore,
bytes32 _serverEndHash,
bytes _serverSig
)
public
payable
onlyValidValue
onlyValidHouseStake(activeGames + 1)
onlyNotPaused
{
uint previousGameId = playerGameId[msg.sender];
Game storage game = gameIdGame[previousGameId];
require(game.status == GameStatus.ENDED);
require(previousGameId == _previousGameId);
require(block.timestamp < _createBefore);
verifyCreateSig(msg.sender, _previousGameId, _createBefore, _serverEndHash, _serverSig);
uint gameId = gameIdCntr++;
playerGameId[msg.sender] = gameId;
Game storage newGame = gameIdGame[gameId];
newGame.stake = uint128(msg.value); // It's safe to cast msg.value as it is limited, see onlyValidValue
newGame.status = GameStatus.ACTIVE;
activeGames = activeGames + 1;
// It's safe to cast msg.value as it is limited, see onlyValidValue
emit LogGameCreated(msg.sender, gameId, uint128(msg.value), _serverEndHash, _playerEndHash);
}
/**
* @dev Regular end game session. Used if player and house have both
* accepted current game session state.
* The game session with gameId _gameId is closed
* and the player paid out. This functions is called by the server after
* the player requested the termination of the current game session.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Current balance.
* @param _serverHash Hash of server's seed for this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _playerAddress Address of player.
* @param _playerSig Player's signature of this bet.
*/
function serverEndGame(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
address _playerAddress,
bytes _playerSig
)
public
onlyServer
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_playerSig,
_playerAddress
);
regularEndGame(_playerAddress, _roundId, _gameType, _num, _value, _balance, _gameId, _contractAddress);
}
/**
* @notice Regular end game session. Normally not needed as server ends game (@see serverEndGame).
* Can be used by player if server does not end game session.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Current balance.
* @param _serverHash Hash of server's seed for this bet.
* @param _playerHash Hash of player's seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _serverSig Server's signature of this bet.
*/
function playerEndGame(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _serverSig
)
public
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_serverSig,
serverAddress
);
regularEndGame(msg.sender, _roundId, _gameType, _num, _value, _balance, _gameId, _contractAddress);
}
/**
* @dev Verify server signature.
* @param _playerAddress player's address.
* @param _previousGameId player's previous game id, initial 0.
* @param _createBefore game can be only created before this timestamp.
* @param _serverEndHash last entry of server's hash chain.
* @param _serverSig server signature.
*/
function verifyCreateSig(
address _playerAddress,
uint _previousGameId,
uint _createBefore,
bytes32 _serverEndHash,
bytes _serverSig
)
private view
{
address contractAddress = this;
bytes32 hash = keccak256(abi.encodePacked(
contractAddress, _playerAddress, _previousGameId, _createBefore, _serverEndHash
));
verify(hash, _serverSig, serverAddress);
}
/**
* @dev Regular end game session implementation. Used if player and house have both
* accepted current game session state. The game session with gameId _gameId is closed
* and the player paid out.
* @param _playerAddress Address of player.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Current balance.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
*/
function regularEndGame(
address _playerAddress,
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
uint _gameId,
address _contractAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
address contractAddress = this;
int maxBalance = conflictRes.maxBalance();
require(_gameId == gameId);
require(_roundId > 0);
// save to cast as game.stake hash fixed range
require(-int(game.stake) <= _balance && _balance <= maxBalance);
require((_gameType == 0) && (_num == 0) && (_value == 0));
require(game.status == GameStatus.ACTIVE);
assert(_contractAddress == contractAddress);
closeGame(game, gameId, _roundId, _playerAddress, ReasonEnded.REGULAR_ENDED, _balance);
}
}
|
End conflicting game. _game Game session data. _gameId Game session id. _playerAddress Player's address./
|
function endGameConflict(Game storage _game, uint _gameId, address _playerAddress) private {
int newBalance = conflictRes.endGameConflict(
_game.gameType,
_game.betNum,
_game.betValue,
_game.balance,
_game.stake,
_game.serverSeed,
_game.playerSeed
);
closeGame(_game, _gameId, _game.roundId, _playerAddress, ReasonEnded.REGULAR_ENDED, newBalance);
}
| 5,901,321 |
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2020, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "@openzeppelin/contracts/utils/Address.sol";
import "arb-bridge-eth/contracts/libraries/BytesLib.sol";
import "arb-bridge-eth/contracts/libraries/ProxyUtil.sol";
import "arb-bridge-eth/contracts/libraries/AddressAliasHelper.sol";
import "../IArbToken.sol";
import "../L2ArbitrumMessenger.sol";
import "../../libraries/gateway/GatewayMessageHandler.sol";
import "../../libraries/gateway/TokenGateway.sol";
/**
* @title Common interface for gatways on Arbitrum messaging to L1.
*/
abstract contract L2ArbitrumGateway is L2ArbitrumMessenger, TokenGateway {
using Address for address;
uint256 public exitNum;
event DepositFinalized(
address indexed l1Token,
address indexed _from,
address indexed _to,
uint256 _amount
);
event WithdrawalInitiated(
address l1Token,
address indexed _from,
address indexed _to,
uint256 indexed _l2ToL1Id,
uint256 _exitNum,
uint256 _amount
);
modifier onlyCounterpartGateway() override {
require(
msg.sender == counterpartGateway ||
AddressAliasHelper.undoL1ToL2Alias(msg.sender) == counterpartGateway,
"ONLY_COUNTERPART_GATEWAY"
);
_;
}
function postUpgradeInit() external {
// it is assumed the L2 Arbitrum Gateway contract is behind a Proxy controlled by a proxy admin
// this function can only be called by the proxy admin contract
address proxyAdmin = ProxyUtil.getProxyAdmin();
require(msg.sender == proxyAdmin, "NOT_FROM_ADMIN");
// this has no other logic since the current upgrade doesn't require this logic
}
function _initialize(address _l1Counterpart, address _router) internal virtual override {
TokenGateway._initialize(_l1Counterpart, _router);
// L1 gateway must have a router
require(_router != address(0), "BAD_ROUTER");
}
function createOutboundTx(
address _from,
uint256, /* _tokenAmount */
bytes memory _outboundCalldata
) internal virtual returns (uint256) {
// We make this function virtual since outboundTransfer logic is the same for many gateways
// but sometimes (ie weth) you construct the outgoing message differently.
// exitNum incremented after being included in _outboundCalldata
exitNum++;
return
sendTxToL1(
// default to sending no callvalue to the L1
0,
_from,
counterpartGateway,
_outboundCalldata
);
}
function getOutboundCalldata(
address _token,
address _from,
address _to,
uint256 _amount,
bytes memory _data
) public view override returns (bytes memory outboundCalldata) {
outboundCalldata = abi.encodeWithSelector(
TokenGateway.finalizeInboundTransfer.selector,
_token,
_from,
_to,
_amount,
GatewayMessageHandler.encodeFromL2GatewayMsg(exitNum, _data)
);
return outboundCalldata;
}
function outboundTransfer(
address _l1Token,
address _to,
uint256 _amount,
bytes calldata _data
) public payable virtual returns (bytes memory) {
return outboundTransfer(_l1Token, _to, _amount, 0, 0, _data);
}
/**
* @notice Initiates a token withdrawal from Arbitrum to Ethereum
* @param _l1Token l1 address of token
* @param _to destination address
* @param _amount amount of tokens withdrawn
* @return res encoded unique identifier for withdrawal
*/
function outboundTransfer(
address _l1Token,
address _to,
uint256 _amount,
uint256, /* _maxGas */
uint256, /* _gasPriceBid */
bytes calldata _data
) public payable virtual override returns (bytes memory res) {
// This function is set as public and virtual so that subclasses can override
// it and add custom validation for callers (ie only whitelisted users)
// the function is marked as payable to conform to the inheritance setup
// this particular code path shouldn't have a msg.value > 0
// TODO: remove this invariant for execution markets
require(msg.value == 0, "NO_VALUE");
address _from;
bytes memory _extraData;
{
if (isRouter(msg.sender)) {
(_from, _extraData) = GatewayMessageHandler.parseFromRouterToGateway(_data);
} else {
_from = msg.sender;
_extraData = _data;
}
}
// the inboundEscrowAndCall functionality has been disabled, so no data is allowed
require(_extraData.length == 0, "EXTRA_DATA_DISABLED");
uint256 id;
{
address l2Token = calculateL2TokenAddress(_l1Token);
require(l2Token.isContract(), "TOKEN_NOT_DEPLOYED");
require(IArbToken(l2Token).l1Address() == _l1Token, "NOT_EXPECTED_L1_TOKEN");
_amount = outboundEscrowTransfer(l2Token, _from, _amount);
id = triggerWithdrawal(_l1Token, _from, _to, _amount, _extraData);
}
return abi.encode(id);
}
function triggerWithdrawal(
address _l1Token,
address _from,
address _to,
uint256 _amount,
bytes memory _data
) internal returns (uint256) {
// exit number used for tradeable exits
uint256 currExitNum = exitNum;
// unique id used to identify the L2 to L1 tx
uint256 id = createOutboundTx(
_from,
_amount,
getOutboundCalldata(_l1Token, _from, _to, _amount, _data)
);
emit WithdrawalInitiated(_l1Token, _from, _to, id, currExitNum, _amount);
return id;
}
function outboundEscrowTransfer(
address _l2Token,
address _from,
uint256 _amount
) internal virtual returns (uint256 amountBurnt) {
// this method is virtual since different subclasses can handle escrow differently
// user funds are escrowed on the gateway using this function
// burns L2 tokens in order to release escrowed L1 tokens
IArbToken(_l2Token).bridgeBurn(_from, _amount);
// by default we assume that the amount we send to bridgeBurn is the amount burnt
// this might not be the case for every token
return _amount;
}
function inboundEscrowTransfer(
address _l2Address,
address _dest,
uint256 _amount
) internal virtual {
// this method is virtual since different subclasses can handle escrow differently
IArbToken(_l2Address).bridgeMint(_dest, _amount);
}
/**
* @notice Mint on L2 upon L1 deposit.
* If token not yet deployed and symbol/name/decimal data is included, deploys StandardArbERC20
* @dev Callable only by the L1ERC20Gateway.outboundTransfer method. For initial deployments of a token the L1 L1ERC20Gateway
* is expected to include the deployData. If not a L1 withdrawal is automatically triggered for the user
* @param _token L1 address of ERC20
* @param _from account that initiated the deposit in the L1
* @param _to account to be credited with the tokens in the L2 (can be the user's L2 account or a contract)
* @param _amount token amount to be minted to the user
* @param _data encoded symbol/name/decimal data for deploy, in addition to any additional callhook data
*/
function finalizeInboundTransfer(
address _token,
address _from,
address _to,
uint256 _amount,
bytes calldata _data
) external payable override onlyCounterpartGateway {
(bytes memory gatewayData, bytes memory callHookData) = GatewayMessageHandler
.parseFromL1GatewayMsg(_data);
if (callHookData.length != 0) {
// callHookData should always be 0 since inboundEscrowAndCall is disabled
callHookData = bytes("");
}
address expectedAddress = calculateL2TokenAddress(_token);
if (!expectedAddress.isContract()) {
bool shouldHalt = handleNoContract(
_token,
expectedAddress,
_from,
_to,
_amount,
gatewayData
);
if (shouldHalt) return;
}
// ignores gatewayData if token already deployed
{
// validate if L1 address supplied matches that of the expected L2 address
(bool success, bytes memory _l1AddressData) = expectedAddress.staticcall(
abi.encodeWithSelector(IArbToken.l1Address.selector)
);
bool shouldWithdraw;
if (!success || _l1AddressData.length < 32) {
shouldWithdraw = true;
} else {
// we do this in the else branch since we want to avoid reverts
// and `toAddress` reverts if _l1AddressData has a short length
// `_l1AddressData` should be 12 bytes of padding then 20 bytes for the address
address expectedL1Address = BytesLib.toAddress(_l1AddressData, 12);
if (expectedL1Address != _token) {
shouldWithdraw = true;
}
}
if (shouldWithdraw) {
// we don't need the return value from triggerWithdrawal since this is forcing
// a withdrawal back to the L1 instead of composing with a L2 dapp
triggerWithdrawal(_token, address(this), _from, _amount, "");
return;
}
}
inboundEscrowTransfer(expectedAddress, _to, _amount);
emit DepositFinalized(_token, _from, _to, _amount);
return;
}
// returns if function should halt after
function handleNoContract(
address _l1Token,
address expectedL2Address,
address _from,
address _to,
uint256 _amount,
bytes memory gatewayData
) internal virtual returns (bool shouldHalt);
}
|
exit number used for tradeable exits unique id used to identify the L2 to L1 tx
|
function triggerWithdrawal(
address _l1Token,
address _from,
address _to,
uint256 _amount,
bytes memory _data
) internal returns (uint256) {
uint256 currExitNum = exitNum;
uint256 id = createOutboundTx(
_from,
_amount,
getOutboundCalldata(_l1Token, _from, _to, _amount, _data)
);
emit WithdrawalInitiated(_l1Token, _from, _to, id, currExitNum, _amount);
return id;
}
| 5,407,416 |
/**
*Submitted for verification at Etherscan.io on 2022-01-11
*/
// Sources flattened with hardhat v2.3.0 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
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/Initializable.sol
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
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/utils/PausableUpgradeable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol
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 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;
}
// File contracts/libraries/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File contracts/token/ChainportToken.sol
pragma solidity ^0.6.12;
contract ChainportToken is IERC20, PausableUpgradeable, ReentrancyGuardUpgradeable {
using SafeMath for uint256;
// Globals
address public chainportCongress;
address public chainportBridge;
mapping (address => bool) public isBlocked;
string private constant NAME = "ChainPort Token";
string private constant SYMBOL = "CPT";
uint8 private constant DECIMALS = 18;
uint256 private constant MAX_SUPPLY = 1000000000 * (uint(10) ** DECIMALS);
uint256 private _totalSupply;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
// Events
event ChainportBridgeChanged(address indexed addr);
event ChainportCongressChanged(address indexed addr);
event AddressBlocked(address indexed addr);
event AddressUnblocked(address indexed addr);
event BlackFundsDestroyed(address indexed addr, uint256 amount);
event StuckTokenWithdrawn(address indexed token, address indexed to, uint256 amount);
/**
* @dev Modifier for functions callable only by chainport authorities
*/
modifier onlyClassifiedAuthority() {
require(
msg.sender == chainportBridge || msg.sender == chainportCongress,
"ChainportToken: Restricted only to classified authorities."
);
_;
}
/**
* @dev Modifier for functions callable only by chainport congress
*/
modifier onlyChainportCongress() {
require(
msg.sender == chainportCongress,
"ChainportToken: Restricted only to congress."
);
_;
}
function initialize(
address chainportCongress_,
address chainportBridge_
)
external
initializer
{
chainportCongress = chainportCongress_;
chainportBridge = chainportBridge_;
_mint(chainportCongress, MAX_SUPPLY);
__ReentrancyGuard_init();
__Pausable_init();
}
/**
* @dev Returns the name of the token.
*/
function name() public pure returns (string memory) {
return NAME;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public pure 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 pure 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);
_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");
_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");
_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 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);
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
* - the contract must not be paused.
* - 'from' address must not be blocked.
*
* Affects:
* - 'transfer' & 'transferFrom'
*/
function _beforeTokenTransfer(address from) internal view {
require(!paused(), "ChainportToken: Token paused.");
require(!isBlocked[from], "ChainportToken: Sender address blocked.");
}
/**
* @notice Function to pause token contract
*/
function pause() external onlyClassifiedAuthority {
_pause();
}
/**
* @notice Function to unpause token contract
*/
function unpause() external onlyChainportCongress {
_unpause();
}
/**
* @notice Function used to block transfers from malicious address
*
* @param addressToBlock is an address that needs to be blocked
*/
function blockAddress(address addressToBlock) external onlyClassifiedAuthority {
isBlocked[addressToBlock] = true;
emit AddressBlocked(addressToBlock);
}
/**
* @notice Function used to unblock an address
*
* @param addressToUnblock is an address that needs to be unblocked
*/
function unblockAddress(address addressToUnblock) external onlyChainportCongress {
isBlocked[addressToUnblock] = false;
emit AddressUnblocked(addressToUnblock);
}
/**
* @notice Function for replacing proxy address of main bridge
*
* @param chainportBridge_ is new proxy address
*/
function setChainportBridge(address chainportBridge_) external onlyChainportCongress {
require(chainportBridge_ != address(0), "ChainportToken: Address malformed.");
chainportBridge = chainportBridge_;
emit ChainportBridgeChanged(chainportBridge);
}
/**
* @notice Function for replacing address of chainport congress
*
* @param chainportCongress_ is new congress address
*/
function setChainportCongress(address chainportCongress_) external onlyChainportCongress {
require(chainportCongress_ != address(0), "ChainportToken: Address malformed.");
chainportCongress = chainportCongress_;
emit ChainportCongressChanged(chainportCongress);
}
/**
* @notice Function for removing black funds from malicious address
*
* @param maliciousAddress is address containing black funds
* @param amount is amount of black funds to be destroyed
*/
function destroyBlackFunds(address maliciousAddress, uint256 amount) external onlyChainportCongress {
_burn(maliciousAddress, amount);
emit BlackFundsDestroyed(maliciousAddress, amount);
}
/**
* @notice Function for withdrawal of tokens stuck on contract
*
* @param token is token that got stuck
* @param beneficiary is address of token owner/sender
*/
function withdrawTokenIfStuck(address token, address beneficiary) external onlyChainportCongress nonReentrant {
uint256 amount = IERC20(token).balanceOf(address(this));
IERC20(token).transfer(beneficiary, amount);
emit StuckTokenWithdrawn(token, beneficiary, amount);
}
}
|
See {ERC20-_beforeTokenTransfer}. Requirements: - the contract must not be paused. - 'from' address must not be blocked. Affects: - 'transfer' & 'transferFrom'/
|
function _beforeTokenTransfer(address from) internal view {
require(!paused(), "ChainportToken: Token paused.");
require(!isBlocked[from], "ChainportToken: Sender address blocked.");
}
| 2,255,836 |
./full_match/43114/0x306f6257CbA2274D171eC871F63ab622C45F9eb9/sources/TimedMasterChefTest.sol
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid, uint256 _amount) external nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
payOrLockupPending(_pid);
uint256 pending = user.amount.mul(pool.accTestPerShare).div(1e18).sub(user.rewardDebt);
if (pending > 0) {
safeTestTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
pool.lpSupply = pool.lpSupply.sub(_amount);
}
user.rewardDebt = user.amount.mul(pool.accTestPerShare).div(1e18);
emit Withdraw(msg.sender, _pid, _amount);
}
| 4,610,863 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/presets/ERC20PresetMinterPauserUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @dev ERC20 token with minting, burning and pausable token transfers.
*
*/
contract EnhancedMinterPauser is
Initializable,
ERC20PresetMinterPauserUpgradeable,
OwnableUpgradeable
{
using SafeMathUpgradeable for uint256;
//role for excluding addresses for feeless transfer
bytes32 public constant FEE_EXCLUDED_ROLE = keccak256("FEE_EXCLUDED_ROLE");
// fee percent represented in integer for example 400, will be used as 1/400 = 0,0025 percent
uint32 public tokenTransferFeeDivisor;
//address where the transfer fees will be sent
address public feeAddress;
event feeWalletAddressChanged(address newValue);
event mintingFeePercentChanged(uint32 newValue);
function __EnhancedMinterPauser_init(
string memory name,
string memory symbol
) internal initializer {
__ERC20_init_unchained(name, symbol);
__ERC20PresetMinterPauser_init_unchained(name, symbol);
__EnhancedMinterPauser_init_unchained();
__Ownable_init();
}
function __EnhancedMinterPauser_init_unchained() internal initializer {
_setupRole(FEE_EXCLUDED_ROLE, _msgSender());
setFeeWalletAddress(0x9D1Cb8509A7b60421aB28492ce05e06f52Ddf727);
setTransferFeeDivisor(400);
}
/**
* @dev minting without 18 decimal places for convenience
* if withFee = true calls the mintWithFee function
* else sends the minted tokens without substracting a fee
*/
function mintWithoutDecimals(
address recipient,
uint256 amount,
bool withFee
) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to mint"
);
if (withFee) {
mintWithFee(recipient, amount * 1 ether);
} else super._mint(recipient, amount * 1 ether);
}
/**
* @dev mint tokens substract the fee, send the fee to the fee wallet
* and send the final amount to the given address
*/
function mintWithFee(address recipient, uint256 amount) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to mint"
);
//transfer fee
super._mint(feeAddress, _calculateFee(amount));
super._mint(recipient, _calculateAmountSubTransferFee(amount));
}
/**
* @dev overriding the openzeppelin _transfer method
* if the sender address is not excluded substract transfer fee from the amount
* and send the fee to the predefined fee address
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual override {
if (hasRole(FEE_EXCLUDED_ROLE, _msgSender())) {
super._transfer(
sender,
recipient,
amount
);
} else {
// transfer amount - fee
super._transfer(
sender,
recipient,
_calculateAmountSubTransferFee(amount)
);
//transfer the fee to the predefined fee address
super._transfer(sender, feeAddress, _calculateFee(amount));
}
}
/**
* @dev set the wallet address where fees will be collected
*/
function setFeeWalletAddress(address _feeAddress) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to set minting fee address"
);
require(address(0) != address(_feeAddress),
"zero address is not allowed"
);
feeAddress = _feeAddress;
emit feeWalletAddressChanged(feeAddress);
}
/**
* @dev sets the transfer fee
* example: divisor 400 would equal to 0,05 percent; 1/400 = 0,0025/100
*/
function setTransferFeeDivisor(uint32 _tokenTransferFeeDivisor) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to set minting fee percent"
);
require(
_tokenTransferFeeDivisor > 2,
"Token transfer fee divisor must be greater than 0"
);
tokenTransferFeeDivisor = _tokenTransferFeeDivisor;
emit mintingFeePercentChanged(tokenTransferFeeDivisor);
}
/**
* @dev calculates the total amount minus the the transfer fee
*/
function _calculateAmountSubTransferFee(uint256 amount)
private
view
returns (uint256)
{
return amount.sub(_calculateFee(amount));
}
/**
* @dev calculates the transfer fee
*/
function _calculateFee(uint256 amount) private view returns (uint256) {
return amount.div(tokenTransferFeeDivisor);
}
uint256[50] private __gap;
}
|
sets the transfer fee example: divisor 400 would equal to 0,05 percent; 1/400 = 0,0025/100/
|
function setTransferFeeDivisor(uint32 _tokenTransferFeeDivisor) public {
require(
hasRole(DEFAULT_ADMIN_ROLE, _msgSender()),
"Caller must have admin role to set minting fee percent"
);
require(
_tokenTransferFeeDivisor > 2,
"Token transfer fee divisor must be greater than 0"
);
tokenTransferFeeDivisor = _tokenTransferFeeDivisor;
emit mintingFeePercentChanged(tokenTransferFeeDivisor);
}
| 12,573,241 |
./partial_match/1/0x4fb901A75EAaC4e77C84533328A0e59C7a1C7686/sources/CoboSafeModule.sol
|
Internal function to check if a role has the permission to transfer ETH roles the roles to check receiver ETH receiver value ETH value return true|false
|
function _checkByTransferProtector(
bytes32[] memory roles,
address receiver,
uint256 value
) internal returns (bool) {
bool success = TransferProtector(transferProtector).check(
roles,
receiver,
value
);
emit TransferChecked(
transferProtector,
receiver,
value,
success,
_msgSender()
);
return success;
}
| 3,708,886 |
./full_match/137/0x8445F1dF2328A2E70AC9A2307c823a0449833f0f/sources/contracts/GasStation.sol
|
Function to deposit ether to the contract Update the balance of the sender
|
function deposit() public payable {
require(msg.value > uint256(1*10**18), "Must deposit 1 or more MATIC");
balances[msg.sender] += msg.value;
}
| 3,736,438 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../WrappedToken.sol";
import "../interfaces/IERC2612Permit.sol";
import "../interfaces/IRouter.sol";
import "../libraries/LibDiamond.sol";
import "../libraries/LibFeeCalculator.sol";
import "../libraries/LibRouter.sol";
import "../libraries/LibGovernance.sol";
contract RouterFacet is IRouter {
using SafeERC20 for IERC20;
/// @notice Constructs the Router contract instance
function initRouter() external override {
LibRouter.Storage storage rs = LibRouter.routerStorage();
require(!rs.initialized, "RouterFacet: already initialized");
rs.initialized = true;
}
/// @param _ethHash The ethereum signed message hash
/// @return Whether this hash has already been used for a mint/unlock transaction
function hashesUsed(bytes32 _ethHash)
external
view
override
returns (bool)
{
LibRouter.Storage storage rs = LibRouter.routerStorage();
return rs.hashesUsed[_ethHash];
}
/// @return The count of native tokens in the set
function nativeTokensCount() external view override returns (uint256) {
return LibRouter.nativeTokensCount();
}
/// @return The address of the native token at a given index
function nativeTokenAt(uint256 _index)
external
view
override
returns (address)
{
return LibRouter.nativeTokenAt(_index);
}
/// @notice Transfers `amount` native tokens to the router contract.
/// The router must be authorised to transfer the native token.
/// @param _targetChain The target chain for the bridging operation
/// @param _nativeToken The token to be bridged
/// @param _amount The amount of tokens to bridge
/// @param _receiver The address of the receiver on the target chain
function lock(
uint256 _targetChain,
address _nativeToken,
uint256 _amount,
bytes memory _receiver
) public override whenNotPaused onlyNativeToken(_nativeToken) {
IERC20(_nativeToken).safeTransferFrom(
msg.sender,
address(this),
_amount
);
uint256 serviceFee = LibFeeCalculator.distributeRewards(
_nativeToken,
_amount
);
emit Lock(_targetChain, _nativeToken, _receiver, _amount, serviceFee);
}
/// @notice Locks the provided amount of nativeToken using an EIP-2612 permit and initiates a bridging transaction
/// @param _targetChain The chain to bridge the tokens to
/// @param _nativeToken The native token to bridge
/// @param _amount The amount of nativeToken to lock and bridge
/// @param _deadline The deadline for the provided permit
/// @param _v The recovery id of the permit's ECDSA signature
/// @param _r The first output of the permit's ECDSA signature
/// @param _s The second output of the permit's ECDSA signature
function lockWithPermit(
uint256 _targetChain,
address _nativeToken,
uint256 _amount,
bytes memory _receiver,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external override {
IERC2612Permit(_nativeToken).permit(
msg.sender,
address(this),
_amount,
_deadline,
_v,
_r,
_s
);
lock(_targetChain, _nativeToken, _amount, _receiver);
}
/// @notice Transfers `amount` native tokens to the `receiver` address.
/// Must be authorised by the configured supermajority threshold of `signatures` from the `members` set.
/// @param _sourceChain The chainId of the chain that we're bridging from
/// @param _transactionId The transaction ID + log index in the source chain
/// @param _nativeToken The address of the native token
/// @param _amount The amount to transfer
/// @param _receiver The address reveiving the tokens
/// @param _signatures The array of signatures from the members, authorising the operation
function unlock(
uint256 _sourceChain,
bytes memory _transactionId,
address _nativeToken,
uint256 _amount,
address _receiver,
bytes[] calldata _signatures
) external override whenNotPaused onlyNativeToken(_nativeToken) {
LibGovernance.validateSignaturesLength(_signatures.length);
bytes32 ethHash = computeMessage(
_sourceChain,
block.chainid,
_transactionId,
_nativeToken,
_receiver,
_amount
);
LibRouter.Storage storage rs = LibRouter.routerStorage();
require(
!rs.hashesUsed[ethHash],
"RouterFacet: transaction already submitted"
);
validateAndStoreTx(ethHash, _signatures);
uint256 serviceFee = LibFeeCalculator.distributeRewards(
_nativeToken,
_amount
);
uint256 transferAmount = _amount - serviceFee;
IERC20(_nativeToken).safeTransfer(_receiver, transferAmount);
emit Unlock(
_sourceChain,
_transactionId,
_nativeToken,
transferAmount,
_receiver,
serviceFee
);
}
/// @notice Burns `amount` of `wrappedToken` initializes a bridging transaction to the target chain
/// @param _targetChain The target chain to which the wrapped asset will be transferred
/// @param _wrappedToken The address of the wrapped token
/// @param _amount The amount of `wrappedToken` to burn
/// @param _receiver The address of the receiver on the target chain
function burn(
uint256 _targetChain,
address _wrappedToken,
uint256 _amount,
bytes memory _receiver
) public override whenNotPaused {
WrappedToken(_wrappedToken).burnFrom(msg.sender, _amount);
emit Burn(_targetChain, _wrappedToken, _amount, _receiver);
}
/// @notice Burns `amount` of `wrappedToken` using an EIP-2612 permit and initializes a bridging transaction to the target chain
/// @param _targetChain The target chain to which the wrapped asset will be transferred
/// @param _wrappedToken The address of the wrapped token
/// @param _amount The amount of `wrappedToken` to burn
/// @param _receiver The address of the receiver on the target chain
/// @param _deadline The deadline of the provided permit
/// @param _v The recovery id of the permit's ECDSA signature
/// @param _r The first output of the permit's ECDSA signature
/// @param _s The second output of the permit's ECDSA signature
function burnWithPermit(
uint256 _targetChain,
address _wrappedToken,
uint256 _amount,
bytes memory _receiver,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external override {
WrappedToken(_wrappedToken).permit(
msg.sender,
address(this),
_amount,
_deadline,
_v,
_r,
_s
);
burn(_targetChain, _wrappedToken, _amount, _receiver);
}
/// @notice Mints `amount` wrapped tokens to the `receiver` address.
/// Must be authorised by the configured supermajority threshold of `signatures` from the `members` set.
/// @param _sourceChain ID of the source chain
/// @param _transactionId The source transaction ID + log index
/// @param _wrappedToken The address of the wrapped token on the current chain
/// @param _amount The desired minting amount
/// @param _receiver The address of the receiver on this chain
/// @param _signatures The array of signatures from the members, authorising the operation
function mint(
uint256 _sourceChain,
bytes memory _transactionId,
address _wrappedToken,
address _receiver,
uint256 _amount,
bytes[] calldata _signatures
) external override whenNotPaused {
LibGovernance.validateSignaturesLength(_signatures.length);
bytes32 ethHash = computeMessage(
_sourceChain,
block.chainid,
_transactionId,
_wrappedToken,
_receiver,
_amount
);
LibRouter.Storage storage rs = LibRouter.routerStorage();
require(
!rs.hashesUsed[ethHash],
"RouterFacet: transaction already submitted"
);
validateAndStoreTx(ethHash, _signatures);
WrappedToken(_wrappedToken).mint(_receiver, _amount);
emit Mint(
_sourceChain,
_transactionId,
_wrappedToken,
_amount,
_receiver
);
}
/// @notice Deploys a wrapped version of `nativeToken` to the current chain
/// @param _sourceChain The chain where `nativeToken` is originally deployed to
/// @param _nativeToken The address of the token
/// @param _tokenParams The name/symbol/decimals to use for the wrapped version of `nativeToken`
function deployWrappedToken(
uint256 _sourceChain,
bytes memory _nativeToken,
WrappedTokenParams memory _tokenParams
) external override {
require(
bytes(_tokenParams.name).length > 0,
"RouterFacet: empty wrapped token name"
);
require(
bytes(_tokenParams.symbol).length > 0,
"RouterFacet: empty wrapped token symbol"
);
require(
_tokenParams.decimals > 0,
"RouterFacet: invalid wrapped token decimals"
);
LibDiamond.enforceIsContractOwner();
WrappedToken t = new WrappedToken(
_tokenParams.name,
_tokenParams.symbol,
_tokenParams.decimals
);
emit WrappedTokenDeployed(_sourceChain, _nativeToken, address(t));
}
/// @notice Updates a native token, which will be used for lock/unlock.
/// @param _nativeToken The native token address
/// @param _serviceFee The amount of fee, which will be taken upon lock/unlock execution
/// @param _status Whether the token will be added or removed
function updateNativeToken(
address _nativeToken,
uint256 _serviceFee,
bool _status
) external override {
require(_nativeToken != address(0), "RouterFacet: zero address");
LibDiamond.enforceIsContractOwner();
LibRouter.updateNativeToken(_nativeToken, _status);
LibFeeCalculator.setServiceFee(_nativeToken, _serviceFee);
emit NativeTokenUpdated(_nativeToken, _serviceFee, _status);
}
/// @notice Validates the signatures and the data and saves the transaction
/// @param _ethHash The hashed data
/// @param _signatures The array of signatures from the members, authorising the operation
function validateAndStoreTx(bytes32 _ethHash, bytes[] calldata _signatures)
internal
{
LibRouter.Storage storage rs = LibRouter.routerStorage();
LibGovernance.validateSignatures(_ethHash, _signatures);
rs.hashesUsed[_ethHash] = true;
}
/// @notice Computes the bytes32 ethereum signed message hash for signatures
/// @param _sourceChain The chain where the bridge transaction was initiated from
/// @param _targetChain The target chain of the bridge transaction.
/// Should always be the current chainId.
/// @param _transactionId The transaction ID of the bridge transaction
/// @param _token The address of the token on this chain
/// @param _receiver The receiving address on the current chain
/// @param _amount The amount of `_token` that is being bridged
function computeMessage(
uint256 _sourceChain,
uint256 _targetChain,
bytes memory _transactionId,
address _token,
address _receiver,
uint256 _amount
) internal pure returns (bytes32) {
bytes32 hashedData = keccak256(
abi.encode(
_sourceChain,
_targetChain,
_transactionId,
_token,
_receiver,
_amount
)
);
return ECDSA.toEthSignedMessageHash(hashedData);
}
modifier onlyNativeToken(address _nativeToken) {
require(
LibRouter.containsNativeToken(_nativeToken),
"RouterFacet: native token not found"
);
_;
}
/// Modifier to make a function callable only when the contract is not paused
modifier whenNotPaused() {
LibGovernance.enforceNotPaused();
_;
}
}
|
return The count of native tokens in the set
|
function nativeTokensCount() external view override returns (uint256) {
return LibRouter.nativeTokensCount();
}
| 973,625 |
pragma solidity 0.4.24;
/**
* CryptoCanvas Terms of Use
*
* 1. Intro
*
* CryptoCanvas is a set of collectible artworks (“Canvas”) created by the CryptoCanvas community with proof of ownership stored on the Ethereum blockchain.
*
* This agreement does a few things. First, it passes copyright ownership of a Canvas from the Canvas Authors to the first Canvas Owner. The first Canvas Owner is then obligated to pass on the copyright ownership along with the Canvas to the next owner, and so on forever, such that each owner of a Canvas is also the copyright owner. Second, it requires each Canvas Owner to allow certain uses of their Canvas image. Third, it limits the rights of Canvas owners to sue The Mindhouse and the prior owners of the Canvas.
*
* Canvases of CryptoCanvas are not an investment. They are experimental digital art.
*
* PLEASE READ THESE TERMS CAREFULLY BEFORE USING THE APP, THE SMART CONTRACTS, OR THE SITE. BY USING THE APP, THE SMART CONTRACTS, THE SITE, OR ANY PART OF THEM YOU ARE CONFIRMING THAT YOU UNDERSTAND AND AGREE TO BE BOUND BY ALL OF THESE TERMS. IF YOU ARE ACCEPTING THESE TERMS ON BEHALF OF A COMPANY OR OTHER LEGAL ENTITY, YOU REPRESENT THAT YOU HAVE THE LEGAL AUTHORITY TO ACCEPT THESE TERMS ON THAT ENTITY’S BEHALF, IN WHICH CASE “YOU” WILL MEAN THAT ENTITY. IF YOU DO NOT HAVE SUCH AUTHORITY, OR IF YOU DO NOT ACCEPT ALL OF THESE TERMS, THEN WE ARE UNWILLING TO MAKE THE APP, THE SMART CONTRACTS, OR THE SITE AVAILABLE TO YOU. IF YOU DO NOT AGREE TO THESE TERMS, YOU MAY NOT ACCESS OR USE THE APP, THE SMART CONTRACTS, OR THE SITE.
*
* 2. Definitions
*
* “Smart Contract” refers to this smart contract.
*
* “Canvas” means a collectible artwork created by the CryptoCanvas community with information about the color and author of each pixel of the Canvas, and proof of ownership stored in the Smart Contract. The Canvas is considered finished when all the pixels of the Canvas have their color set. Specifically, the Canvas is considered finished when its “state” field in the Smart Contract equals to STATE_INITIAL_BIDDING or STATE_OWNED constant.
*
* “Canvas Author” means the person who painted at least one final pixel of the finished Canvas by sending a transaction to the Smart Contract. Specifically, Canvas Author means the person with the private key for at least one address in the “painter” field of the “pixels” field of the applicable Canvas in the Smart Contract.
*
* “Canvas Owner” means the person that can cryptographically prove ownership of the applicable Canvas. Specifically, Canvas Owner means the person with the private key for the address in the “owner” field of the applicable Canvas in the Smart Contract. The person is the Canvas Owner only after the Initial Bidding phase is finished, that is when the field “state” of the applicable Canvas equals to the STATE_OWNED constant.
*
* “Initial Bidding” means the state of the Canvas when each of its pixels has been set by Canvas Authors but it does not have the Canvas Owner yet. In this phase any user can claim the ownership of the Canvas by sending a transaction to the Smart Contract (a “Bid”). Other users have 48 hours from the time of making the first Bid on the Canvas to submit their own Bids. After that time, the user who sent the highest Bid becomes the sole Canvas Owner of the applicable Canvas. Users who placed Bids with lower amounts are able to withdraw their Bid amount from their Account Balance.
*
* “Account Balance” means the value stored in the Smart Contract assigned to an address. The Account Balance can be withdrawn by the person with the private key for the applicable address by sending a transaction to the Smart Contract. Account Balance consists of Rewards for painting, Bids from Initial Bidding which have been overbid, cancelled offers to buy a Canvas and profits from selling a Canvas.
*
* “The Mindhouse”, “we” or “us” is the group of developers who created and published the CryptoCanvas Smart Contract.
*
* “The App” means collectively the Smart Contract and the website created by The Mindhouse to interact with the Smart Contract.
*
* 3. Intellectual Property
*
* A. First Assignment
* The Canvas Authors of the applicable Canvas hereby assign all copyright ownership in the Canvas to the Canvas Owner. In exchange for this copyright ownership, the Canvas Owner agrees to the terms below.
*
* B. Later Assignments
* When the Canvas Owner transfers the Canvas to a new owner, the Canvas Owner hereby agrees to assign all copyright ownership in the Canvas to the new owner of the Canvas. In exchange for these rights, the new owner shall agree to become the Canvas Owner, and shall agree to be subject to this Terms of Use.
*
* C. No Other Assignments.
* The Canvas Owner shall not assign or license the copyright except as set forth in the “Later Assignments” section above.
*
* D. Third Party Permissions.
* The Canvas Owner agrees to allow CryptoCanvas fans to make non-commercial Use of images of the Canvas to discuss CryptoCanvas, digital collectibles and related matters. “Use” means to reproduce, display, transmit, and distribute images of the Canvas. This permission excludes the right to print the Canvas onto physical copies (including, for example, shirts and posters).
*
* 4. Fees and Payment
*
* A. If you choose to paint, make a bid or trade any Canvas of CryptoCanvas any financial transactions that you engage in will be conducted solely through the Ethereum network via MetaMask. We will have no insight into or control over these payments or transactions, nor do we have the ability to reverse any transactions. With that in mind, we will have no liability to you or to any third party for any claims or damages that may arise as a result of any transactions that you engage in via the App, or using the Smart Contracts, or any other transactions that you conduct via the Ethereum network or MetaMask.
*
* B. Ethereum requires the payment of a transaction fee (a “Gas Fee”) for every transaction that occurs on the Ethereum network. The Gas Fee funds the network of computers that run the decentralized Ethereum network. This means that you will need to pay a Gas Fee for each transaction that occurs via the App.
*
* C. In addition to the Gas Fee, each time you sell a Canvas to another user of the App, you authorize us to collect a fee of 10% of the total value of that transaction. That fee consists of:
1) 3.9% of the total value of that transaction (a “Commission”). You acknowledge and agree that the Commission will be transferred to us through the Ethereum network as a part of the payment.
2) 6.1% of the total value of that transaction (a “Reward”). You acknowledge and agree that the Reward will be transferred evenly to all painters of the sold canvas through the Ethereum network as a part of the payment.
*
* D. If you are the Canvas Author you are eligible to receive a reward for painting a Canvas (a “Reward”). A Reward is distributed in these scenarios:
1) After the Initial Bidding phase is completed. You acknowledge and agree that the Reward for the Canvas Author will be calculated by dividing the value of the winning Bid, decreased by our commission of 3.9% of the total value of the Bid, by the total number of pixels of the Canvas and multiplied by the number of pixels of the Canvas that have been painted by applicable Canvas Author.
2) Each time the Canvas is sold. You acknowledge and agree that the Reward for the Canvas Author will be calculated by dividing 6.1% of the total transaction value by the total number of pixels of the Canvas and multiplied by the number of pixels of the Canvas that have been painted by the applicable Canvas Author.
You acknowledge and agree that in order to withdraw the Reward you first need to add the Reward to your Account Balance by sending a transaction to the Smart Contract.
*
* 5. Disclaimers
*
* A. YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR ACCESS TO AND USE OF THE APP IS AT YOUR SOLE RISK, AND THAT THE APP IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED. TO THE FULLEST EXTENT PERMISSIBLE PURSUANT TO APPLICABLE LAW, WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS MAKE NO EXPRESS WARRANTIES AND HEREBY DISCLAIM ALL IMPLIED WARRANTIES REGARDING THE APP AND ANY PART OF IT (INCLUDING, WITHOUT LIMITATION, THE SITE, ANY SMART CONTRACT, OR ANY EXTERNAL WEBSITES), INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, CORRECTNESS, ACCURACY, OR RELIABILITY. WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS DO NOT REPRESENT OR WARRANT TO YOU THAT: (I) YOUR ACCESS TO OR USE OF THE APP WILL MEET YOUR REQUIREMENTS, (II) YOUR ACCESS TO OR USE OF THE APP WILL BE UNINTERRUPTED, TIMELY, SECURE OR FREE FROM ERROR, (III) USAGE DATA PROVIDED THROUGH THE APP WILL BE ACCURATE, (III) THE APP OR ANY CONTENT, SERVICES, OR FEATURES MADE AVAILABLE ON OR THROUGH THE APP ARE FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS, OR (IV) THAT ANY DATA THAT YOU DISCLOSE WHEN YOU USE THE APP WILL BE SECURE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES IN CONTRACTS WITH CONSUMERS, SO SOME OR ALL OF THE ABOVE EXCLUSIONS MAY NOT APPLY TO YOU.
*
* B. YOU ACCEPT THE INHERENT SECURITY RISKS OF PROVIDING INFORMATION AND DEALING ONLINE OVER THE INTERNET, AND AGREE THAT WE HAVE NO LIABILITY OR RESPONSIBILITY FOR ANY BREACH OF SECURITY UNLESS IT IS DUE TO OUR GROSS NEGLIGENCE.
*
* C. WE WILL NOT BE RESPONSIBLE OR LIABLE TO YOU FOR ANY LOSSES YOU INCUR AS THE RESULT OF YOUR USE OF THE ETHEREUM NETWORK OR THE METAMASK ELECTRONIC WALLET, INCLUDING BUT NOT LIMITED TO ANY LOSSES, DAMAGES OR CLAIMS ARISING FROM: (A) USER ERROR, SUCH AS FORGOTTEN PASSWORDS OR INCORRECTLY CONSTRUED SMART CONTRACTS OR OTHER TRANSACTIONS; (B) SERVER FAILURE OR DATA LOSS; (C) CORRUPTED WALLET FILES; (D) UNAUTHORIZED ACCESS OR ACTIVITIES BY THIRD PARTIES, INCLUDING BUT NOT LIMITED TO THE USE OF VIRUSES, PHISHING, BRUTEFORCING OR OTHER MEANS OF ATTACK AGAINST THE APP, ETHEREUM NETWORK, OR THE METAMASK ELECTRONIC WALLET.
*
* D. THE CANVASES OF CRYPTOCANVAS ARE INTANGIBLE DIGITAL ASSETS THAT EXIST ONLY BY VIRTUE OF THE OWNERSHIP RECORD MAINTAINED IN THE ETHEREUM NETWORK. ALL SMART CONTRACTS ARE CONDUCTED AND OCCUR ON THE DECENTRALIZED LEDGER WITHIN THE ETHEREUM PLATFORM. WE HAVE NO CONTROL OVER AND MAKE NO GUARANTEES OR PROMISES WITH RESPECT TO SMART CONTRACTS.
*
* E. THE MINDHOUSE IS NOT RESPONSIBLE FOR LOSSES DUE TO BLOCKCHAINS OR ANY OTHER FEATURES OF THE ETHEREUM NETWORK OR THE METAMASK ELECTRONIC WALLET, INCLUDING BUT NOT LIMITED TO LATE REPORT BY DEVELOPERS OR REPRESENTATIVES (OR NO REPORT AT ALL) OF ANY ISSUES WITH THE BLOCKCHAIN SUPPORTING THE ETHEREUM NETWORK, INCLUDING FORKS, TECHNICAL NODE ISSUES, OR ANY OTHER ISSUES HAVING FUND LOSSES AS A RESULT.
*
* 6. Limitation of Liability
* YOU UNDERSTAND AND AGREE THAT WE, OUR SUBSIDIARIES, AFFILIATES, AND LICENSORS WILL NOT BE LIABLE TO YOU OR TO ANY THIRD PARTY FOR ANY CONSEQUENTIAL, INCIDENTAL, INDIRECT, EXEMPLARY, SPECIAL, PUNITIVE, OR ENHANCED DAMAGES, OR FOR ANY LOSS OF ACTUAL OR ANTICIPATED PROFITS (REGARDLESS OF HOW THESE ARE CLASSIFIED AS DAMAGES), WHETHER ARISING OUT OF BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, REGARDLESS OF WHETHER SUCH DAMAGE WAS FORESEEABLE AND WHETHER EITHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
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) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @dev Contract that is aware of time. Useful for tests - like this
* we can mock time.
*/
contract TimeAware is Ownable {
/**
* @dev Returns current time.
*/
function getTime() public view returns (uint) {
return now;
}
}
/**
* @dev Contract that holds pending withdrawals. Responsible for withdrawals.
*/
contract Withdrawable {
mapping(address => uint) private pendingWithdrawals;
event Withdrawal(address indexed receiver, uint amount);
event BalanceChanged(address indexed _address, uint oldBalance, uint newBalance);
/**
* Returns amount of wei that given address is able to withdraw.
*/
function getPendingWithdrawal(address _address) public view returns (uint) {
return pendingWithdrawals[_address];
}
/**
* Add pending withdrawal for an address.
*/
function addPendingWithdrawal(address _address, uint _amount) internal {
require(_address != 0x0);
uint oldBalance = pendingWithdrawals[_address];
pendingWithdrawals[_address] += _amount;
emit BalanceChanged(_address, oldBalance, oldBalance + _amount);
}
/**
* Withdraws all pending withdrawals.
*/
function withdraw() external {
uint amount = getPendingWithdrawal(msg.sender);
require(amount > 0);
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
emit Withdrawal(msg.sender, amount);
emit BalanceChanged(msg.sender, amount, 0);
}
}
/**
* @dev This contract takes care of painting on canvases, returning artworks and creating ones.
*/
contract CanvasFactory is TimeAware, Withdrawable {
//@dev It means canvas is not finished yet, and bidding is not possible.
uint8 public constant STATE_NOT_FINISHED = 0;
//@dev there is ongoing bidding and anybody can bid. If there canvas can have
// assigned owner, but it can change if someone will over-bid him.
uint8 public constant STATE_INITIAL_BIDDING = 1;
//@dev canvas has been sold, and has the owner
uint8 public constant STATE_OWNED = 2;
uint8 public constant WIDTH = 48;
uint8 public constant HEIGHT = 48;
uint32 public constant PIXEL_COUNT = 2304; //WIDTH * HEIGHT doesn't work for some reason
uint32 public constant MAX_CANVAS_COUNT = 1000;
uint8 public constant MAX_ACTIVE_CANVAS = 12;
uint8 public constant MAX_CANVAS_NAME_LENGTH = 24;
Canvas[] canvases;
uint32 public activeCanvasCount = 0;
event PixelPainted(uint32 indexed canvasId, uint32 index, uint8 color, address indexed painter);
event CanvasFinished(uint32 indexed canvasId);
event CanvasCreated(uint indexed canvasId, address indexed bookedFor);
event CanvasNameSet(uint indexed canvasId, string name);
modifier notFinished(uint32 _canvasId) {
require(!isCanvasFinished(_canvasId));
_;
}
modifier finished(uint32 _canvasId) {
require(isCanvasFinished(_canvasId));
_;
}
modifier validPixelIndex(uint32 _pixelIndex) {
require(_pixelIndex < PIXEL_COUNT);
_;
}
/**
* @notice Creates new canvas. There can't be more canvases then MAX_CANVAS_COUNT.
* There can't be more unfinished canvases than MAX_ACTIVE_CANVAS.
*/
function createCanvas() external returns (uint canvasId) {
return _createCanvasInternal(0x0);
}
/**
* @notice Similar to createCanvas(). Books it for given address. If address is 0x0 everybody will
* be allowed to paint on a canvas.
*/
function createAndBookCanvas(address _bookFor) external onlyOwner returns (uint canvasId) {
return _createCanvasInternal(_bookFor);
}
/**
* @notice Changes canvas.bookFor variable. Only for the owner of the contract.
*/
function bookCanvasFor(uint32 _canvasId, address _bookFor) external onlyOwner {
Canvas storage _canvas = _getCanvas(_canvasId);
_canvas.bookedFor = _bookFor;
}
/**
* @notice Sets pixel. Given canvas can't be yet finished.
*/
function setPixel(uint32 _canvasId, uint32 _index, uint8 _color) external {
Canvas storage _canvas = _getCanvas(_canvasId);
_setPixelInternal(_canvas, _canvasId, _index, _color);
_finishCanvasIfNeeded(_canvas, _canvasId);
}
/**
* Set many pixels with one tx. Be careful though - sending a lot of pixels
* to set may cause out of gas error.
*
* Throws when none of the pixels has been set.
*
*/
function setPixels(uint32 _canvasId, uint32[] _indexes, uint8[] _colors) external {
require(_indexes.length == _colors.length);
Canvas storage _canvas = _getCanvas(_canvasId);
bool anySet = false;
for (uint32 i = 0; i < _indexes.length; i++) {
Pixel storage _pixel = _canvas.pixels[_indexes[i]];
if (_pixel.painter == 0x0) {
//only allow when pixel is not set
_setPixelInternal(_canvas, _canvasId, _indexes[i], _colors[i]);
anySet = true;
}
}
if (!anySet) {
//If didn't set any pixels - revert to show that transaction failed
revert();
}
_finishCanvasIfNeeded(_canvas, _canvasId);
}
/**
* @notice Returns full bitmap for given canvas.
*/
function getCanvasBitmap(uint32 _canvasId) external view returns (uint8[]) {
Canvas storage canvas = _getCanvas(_canvasId);
uint8[] memory result = new uint8[](PIXEL_COUNT);
for (uint32 i = 0; i < PIXEL_COUNT; i++) {
result[i] = canvas.pixels[i].color;
}
return result;
}
/**
* @notice Returns how many pixels has been already set.
*/
function getCanvasPaintedPixelsCount(uint32 _canvasId) public view returns (uint32) {
return _getCanvas(_canvasId).paintedPixelsCount;
}
function getPixelCount() external pure returns (uint) {
return PIXEL_COUNT;
}
/**
* @notice Returns amount of created canvases.
*/
function getCanvasCount() public view returns (uint) {
return canvases.length;
}
/**
* @notice Returns true if the canvas has been already finished.
*/
function isCanvasFinished(uint32 _canvasId) public view returns (bool) {
return _isCanvasFinished(_getCanvas(_canvasId));
}
/**
* @notice Returns the author of given pixel.
*/
function getPixelAuthor(uint32 _canvasId, uint32 _pixelIndex) public view validPixelIndex(_pixelIndex) returns (address) {
return _getCanvas(_canvasId).pixels[_pixelIndex].painter;
}
/**
* @notice Returns number of pixels set by given address.
*/
function getPaintedPixelsCountByAddress(address _address, uint32 _canvasId) public view returns (uint32) {
Canvas storage canvas = _getCanvas(_canvasId);
return canvas.addressToCount[_address];
}
function _isCanvasFinished(Canvas canvas) internal pure returns (bool) {
return canvas.paintedPixelsCount == PIXEL_COUNT;
}
function _getCanvas(uint32 _canvasId) internal view returns (Canvas storage) {
require(_canvasId < canvases.length);
return canvases[_canvasId];
}
function _createCanvasInternal(address _bookedFor) private returns (uint canvasId) {
require(canvases.length < MAX_CANVAS_COUNT);
require(activeCanvasCount < MAX_ACTIVE_CANVAS);
uint id = canvases.push(Canvas(STATE_NOT_FINISHED, 0x0, _bookedFor, "", 0, 0, false)) - 1;
emit CanvasCreated(id, _bookedFor);
activeCanvasCount++;
_onCanvasCreated(id);
return id;
}
function _onCanvasCreated(uint /* _canvasId */) internal {}
/**
* Sets the pixel.
*/
function _setPixelInternal(Canvas storage _canvas, uint32 _canvasId, uint32 _index, uint8 _color)
private
notFinished(_canvasId)
validPixelIndex(_index) {
require(_color > 0);
require(_canvas.bookedFor == 0x0 || _canvas.bookedFor == msg.sender);
if (_canvas.pixels[_index].painter != 0x0) {
//it means this pixel has been already set!
revert();
}
_canvas.paintedPixelsCount++;
_canvas.addressToCount[msg.sender]++;
_canvas.pixels[_index] = Pixel(_color, msg.sender);
emit PixelPainted(_canvasId, _index, _color, msg.sender);
}
/**
* Marks canvas as finished if all the pixels has been already set.
* Starts initial bidding session.
*/
function _finishCanvasIfNeeded(Canvas storage _canvas, uint32 _canvasId) private {
if (_isCanvasFinished(_canvas)) {
activeCanvasCount--;
_canvas.state = STATE_INITIAL_BIDDING;
emit CanvasFinished(_canvasId);
}
}
struct Pixel {
uint8 color;
address painter;
}
struct Canvas {
/**
* Map of all pixels.
*/
mapping(uint32 => Pixel) pixels;
uint8 state;
/**
* Owner of canvas. Canvas doesn't have an owner until initial bidding ends.
*/
address owner;
/**
* Booked by this address. It means that only that address can draw on the canvas.
* 0x0 if everybody can paint on the canvas.
*/
address bookedFor;
string name;
/**
* Numbers of pixels set. Canvas will be considered finished when all pixels will be set.
* Technically it means that setPixelsCount == PIXEL_COUNT
*/
uint32 paintedPixelsCount;
mapping(address => uint32) addressToCount;
/**
* Initial bidding finish time.
*/
uint initialBiddingFinishTime;
/**
* If commission from initial bidding has been paid.
*/
bool isCommissionPaid;
/**
* @dev if address has been paid a reward for drawing.
*/
mapping(address => bool) isAddressPaid;
}
}
/**
* @notice Useful methods to manage canvas' state.
*/
contract CanvasState is CanvasFactory {
modifier stateBidding(uint32 _canvasId) {
require(getCanvasState(_canvasId) == STATE_INITIAL_BIDDING);
_;
}
modifier stateOwned(uint32 _canvasId) {
require(getCanvasState(_canvasId) == STATE_OWNED);
_;
}
/**
* Ensures that canvas's saved state is STATE_OWNED.
*
* Because initial bidding is based on current time, we had to find a way to
* trigger saving new canvas state. Every transaction (not a call) that
* requires state owned should use it modifier as a last one.
*
* Thank's to that, we can make sure, that canvas state gets updated.
*/
modifier forceOwned(uint32 _canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
if (canvas.state != STATE_OWNED) {
canvas.state = STATE_OWNED;
}
_;
}
/**
* @notice Returns current canvas state.
*/
function getCanvasState(uint32 _canvasId) public view returns (uint8) {
Canvas storage canvas = _getCanvas(_canvasId);
if (canvas.state != STATE_INITIAL_BIDDING) {
//if state is set to owned, or not finished
//it means it doesn't depend on current time -
//we don't have to double check
return canvas.state;
}
//state initial bidding - as that state depends on
//current time, we have to double check if initial bidding
//hasn't finish yet
uint finishTime = canvas.initialBiddingFinishTime;
if (finishTime == 0 || finishTime > getTime()) {
return STATE_INITIAL_BIDDING;
} else {
return STATE_OWNED;
}
}
/**
* @notice Returns all canvas' id for a given state.
*/
function getCanvasByState(uint8 _state) external view returns (uint32[]) {
uint size;
if (_state == STATE_NOT_FINISHED) {
size = activeCanvasCount;
} else {
size = getCanvasCount() - activeCanvasCount;
}
uint32[] memory result = new uint32[](size);
uint currentIndex = 0;
for (uint32 i = 0; i < canvases.length; i++) {
if (getCanvasState(i) == _state) {
result[currentIndex] = i;
currentIndex++;
}
}
return _slice(result, 0, currentIndex);
}
/**
* Sets canvas name. Only for the owner of the canvas. Name can be an empty
* string which is the same as lack of the name.
*/
function setCanvasName(uint32 _canvasId, string _name) external
stateOwned(_canvasId)
forceOwned(_canvasId)
{
bytes memory _strBytes = bytes(_name);
require(_strBytes.length <= MAX_CANVAS_NAME_LENGTH);
Canvas storage _canvas = _getCanvas(_canvasId);
require(msg.sender == _canvas.owner);
_canvas.name = _name;
emit CanvasNameSet(_canvasId, _name);
}
/**
* @dev Slices array from start (inclusive) to end (exclusive).
* Doesn't modify input array.
*/
function _slice(uint32[] memory _array, uint _start, uint _end) internal pure returns (uint32[]) {
require(_start <= _end);
if (_start == 0 && _end == _array.length) {
return _array;
}
uint size = _end - _start;
uint32[] memory sliced = new uint32[](size);
for (uint i = 0; i < size; i++) {
sliced[i] = _array[i + _start];
}
return sliced;
}
}
/**
* @notice Keeps track of all rewards and commissions.
* Commission - fee that we charge for using CryptoCanvas.
* Reward - painters cut.
*/
contract RewardableCanvas is CanvasState {
/**
* As it's hard to operate on floating numbers, each fee will be calculated like this:
* PRICE * COMMISSION / COMMISSION_DIVIDER. It's impossible to keep float number here.
*
* ufixed COMMISSION = 0.039; may seem useful, but it's not possible to multiply ufixed * uint.
*/
uint public constant COMMISSION = 39;
uint public constant TRADE_REWARD = 61;
uint public constant PERCENT_DIVIDER = 1000;
event RewardAddedToWithdrawals(uint32 indexed canvasId, address indexed toAddress, uint amount);
event CommissionAddedToWithdrawals(uint32 indexed canvasId, uint amount);
event FeesUpdated(uint32 indexed canvasId, uint totalCommissions, uint totalReward);
mapping(uint => FeeHistory) private canvasToFeeHistory;
/**
* @notice Adds all unpaid commission to the owner's pending withdrawals.
* Ethers to withdraw has to be greater that 0, otherwise transaction
* will be rejected.
* Can be called only by the owner.
*/
function addCommissionToPendingWithdrawals(uint32 _canvasId)
public
onlyOwner
stateOwned(_canvasId)
forceOwned(_canvasId) {
FeeHistory storage _history = _getFeeHistory(_canvasId);
uint _toWithdraw = calculateCommissionToWithdraw(_canvasId);
uint _lastIndex = _history.commissionCumulative.length - 1;
require(_toWithdraw > 0);
_history.paidCommissionIndex = _lastIndex;
addPendingWithdrawal(owner, _toWithdraw);
emit CommissionAddedToWithdrawals(_canvasId, _toWithdraw);
}
/**
* @notice Adds all unpaid rewards of the caller to his pending withdrawals.
* Ethers to withdraw has to be greater that 0, otherwise transaction
* will be rejected.
*/
function addRewardToPendingWithdrawals(uint32 _canvasId)
public
stateOwned(_canvasId)
forceOwned(_canvasId) {
FeeHistory storage _history = _getFeeHistory(_canvasId);
uint _toWithdraw;
(_toWithdraw,) = calculateRewardToWithdraw(_canvasId, msg.sender);
uint _lastIndex = _history.rewardsCumulative.length - 1;
require(_toWithdraw > 0);
_history.addressToPaidRewardIndex[msg.sender] = _lastIndex;
addPendingWithdrawal(msg.sender, _toWithdraw);
emit RewardAddedToWithdrawals(_canvasId, msg.sender, _toWithdraw);
}
/**
* @notice Calculates how much of commission there is to be paid.
*/
function calculateCommissionToWithdraw(uint32 _canvasId)
public
view
stateOwned(_canvasId)
returns (uint)
{
FeeHistory storage _history = _getFeeHistory(_canvasId);
uint _lastIndex = _history.commissionCumulative.length - 1;
uint _lastPaidIndex = _history.paidCommissionIndex;
if (_lastIndex < 0) {
//means that FeeHistory hasn't been created yet
return 0;
}
uint _commissionSum = _history.commissionCumulative[_lastIndex];
uint _lastWithdrawn = _history.commissionCumulative[_lastPaidIndex];
uint _toWithdraw = _commissionSum - _lastWithdrawn;
require(_toWithdraw <= _commissionSum);
return _toWithdraw;
}
/**
* @notice Calculates unpaid rewards of a given address. Returns amount to withdraw
* and amount of pixels owned.
*/
function calculateRewardToWithdraw(uint32 _canvasId, address _address)
public
view
stateOwned(_canvasId)
returns (
uint reward,
uint pixelsOwned
)
{
FeeHistory storage _history = _getFeeHistory(_canvasId);
uint _lastIndex = _history.rewardsCumulative.length - 1;
uint _lastPaidIndex = _history.addressToPaidRewardIndex[_address];
uint _pixelsOwned = getPaintedPixelsCountByAddress(_address, _canvasId);
if (_lastIndex < 0) {
//means that FeeHistory hasn't been created yet
return (0, _pixelsOwned);
}
uint _rewardsSum = _history.rewardsCumulative[_lastIndex];
uint _lastWithdrawn = _history.rewardsCumulative[_lastPaidIndex];
// Our data structure guarantees that _commissionSum is greater or equal to _lastWithdrawn
uint _toWithdraw = ((_rewardsSum - _lastWithdrawn) / PIXEL_COUNT) * _pixelsOwned;
return (_toWithdraw, _pixelsOwned);
}
/**
* @notice Returns total amount of commission charged for a given canvas.
* It is not a commission to be withdrawn!
*/
function getTotalCommission(uint32 _canvasId) external view returns (uint) {
require(_canvasId < canvases.length);
FeeHistory storage _history = canvasToFeeHistory[_canvasId];
uint _lastIndex = _history.commissionCumulative.length - 1;
if (_lastIndex < 0) {
//means that FeeHistory hasn't been created yet
return 0;
}
return _history.commissionCumulative[_lastIndex];
}
/**
* @notice Returns total amount of commission that has been already
* paid (added to pending withdrawals).
*/
function getCommissionWithdrawn(uint32 _canvasId) external view returns (uint) {
require(_canvasId < canvases.length);
FeeHistory storage _history = canvasToFeeHistory[_canvasId];
uint _index = _history.paidCommissionIndex;
return _history.commissionCumulative[_index];
}
/**
* @notice Returns all rewards charged for the given canvas.
*/
function getTotalRewards(uint32 _canvasId) external view returns (uint) {
require(_canvasId < canvases.length);
FeeHistory storage _history = canvasToFeeHistory[_canvasId];
uint _lastIndex = _history.rewardsCumulative.length - 1;
if (_lastIndex < 0) {
//means that FeeHistory hasn't been created yet
return 0;
}
return _history.rewardsCumulative[_lastIndex];
}
/**
* @notice Returns total amount of rewards that has been already
* paid (added to pending withdrawals) by a given address.
*/
function getRewardsWithdrawn(uint32 _canvasId, address _address) external view returns (uint) {
require(_canvasId < canvases.length);
FeeHistory storage _history = canvasToFeeHistory[_canvasId];
uint _index = _history.addressToPaidRewardIndex[_address];
uint _pixelsOwned = getPaintedPixelsCountByAddress(_address, _canvasId);
if (_history.rewardsCumulative.length == 0 || _index == 0) {
return 0;
}
return (_history.rewardsCumulative[_index] / PIXEL_COUNT) * _pixelsOwned;
}
/**
* @notice Calculates how the initial bidding money will be split.
*
* @return Commission and sum of all painter rewards.
*/
function splitBid(uint _amount) public pure returns (
uint commission,
uint paintersRewards
){
uint _rewardPerPixel = ((_amount - _calculatePercent(_amount, COMMISSION))) / PIXEL_COUNT;
// Rewards is divisible by PIXEL_COUNT
uint _rewards = _rewardPerPixel * PIXEL_COUNT;
return (_amount - _rewards, _rewards);
}
/**
* @notice Calculates how the money from selling canvas will be split.
*
* @return Commission, sum of painters' rewards and a seller's profit.
*/
function splitTrade(uint _amount) public pure returns (
uint commission,
uint paintersRewards,
uint sellerProfit
){
uint _commission = _calculatePercent(_amount, COMMISSION);
// We make sure that painters reward is divisible by PIXEL_COUNT.
// It is important to split reward across all the painters equally.
uint _rewardPerPixel = _calculatePercent(_amount, TRADE_REWARD) / PIXEL_COUNT;
uint _paintersReward = _rewardPerPixel * PIXEL_COUNT;
uint _sellerProfit = _amount - _commission - _paintersReward;
//check for the underflow
require(_sellerProfit < _amount);
return (_commission, _paintersReward, _sellerProfit);
}
/**
* @notice Adds a bid to fee history. Doesn't perform any checks if the bid is valid!
* @return Returns how the bid was split. Same value as _splitBid function.
*/
function _registerBid(uint32 _canvasId, uint _amount) internal stateBidding(_canvasId) returns (
uint commission,
uint paintersRewards
){
uint _commission;
uint _rewards;
(_commission, _rewards) = splitBid(_amount);
FeeHistory storage _history = _getFeeHistory(_canvasId);
// We have to save the difference between new bid and a previous one.
// Because we save data as cumulative sum, it's enough to save
// only the new value.
_history.commissionCumulative.push(_commission);
_history.rewardsCumulative.push(_rewards);
return (_commission, _rewards);
}
/**
* @notice Adds a bid to fee history. Doesn't perform any checks if the bid is valid!
* @return Returns how the trade ethers were split. Same value as splitTrade function.
*/
function _registerTrade(uint32 _canvasId, uint _amount)
internal
stateOwned(_canvasId)
forceOwned(_canvasId)
returns (
uint commission,
uint paintersRewards,
uint sellerProfit
){
uint _commission;
uint _rewards;
uint _sellerProfit;
(_commission, _rewards, _sellerProfit) = splitTrade(_amount);
FeeHistory storage _history = _getFeeHistory(_canvasId);
_pushCumulative(_history.commissionCumulative, _commission);
_pushCumulative(_history.rewardsCumulative, _rewards);
return (_commission, _rewards, _sellerProfit);
}
function _onCanvasCreated(uint _canvasId) internal {
//we create a fee entrance on the moment canvas is created
canvasToFeeHistory[_canvasId] = FeeHistory(new uint[](1), new uint[](1), 0);
}
/**
* @notice Gets a fee history of a canvas.
*/
function _getFeeHistory(uint32 _canvasId) private view returns (FeeHistory storage) {
require(_canvasId < canvases.length);
//fee history entry is created in onCanvasCreated() method.
FeeHistory storage _history = canvasToFeeHistory[_canvasId];
return _history;
}
function _pushCumulative(uint[] storage _array, uint _value) private returns (uint) {
uint _lastValue = _array[_array.length - 1];
uint _newValue = _lastValue + _value;
//overflow protection
require(_newValue >= _lastValue);
return _array.push(_newValue);
}
/**
* @param _percent - percent value mapped to scale [0-1000]
*/
function _calculatePercent(uint _amount, uint _percent) private pure returns (uint) {
return (_amount * _percent) / PERCENT_DIVIDER;
}
struct FeeHistory {
/**
* @notice Cumulative sum of all charged commissions.
*/
uint[] commissionCumulative;
/**
* @notice Cumulative sum of all charged rewards.
*/
uint[] rewardsCumulative;
/**
* Index of last paid commission (from commissionCumulative array)
*/
uint paidCommissionIndex;
/**
* Mapping showing what rewards has been already paid.
*/
mapping(address => uint) addressToPaidRewardIndex;
}
}
/**
* @dev This contract takes care of initial bidding.
*/
contract BiddableCanvas is RewardableCanvas {
uint public constant BIDDING_DURATION = 48 hours;
mapping(uint32 => Bid) bids;
mapping(address => uint32) addressToCount;
uint public minimumBidAmount = 0.1 ether;
event BidPosted(uint32 indexed canvasId, address indexed bidder, uint amount, uint finishTime);
/**
* Places bid for canvas that is in the state STATE_INITIAL_BIDDING.
* If somebody is outbid his pending withdrawals will be to topped up.
*/
function makeBid(uint32 _canvasId) external payable stateBidding(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
Bid storage oldBid = bids[_canvasId];
if (msg.value < minimumBidAmount || msg.value <= oldBid.amount) {
revert();
}
if (oldBid.bidder != 0x0 && oldBid.amount > 0) {
//return old bidder his money
addPendingWithdrawal(oldBid.bidder, oldBid.amount);
}
uint finishTime = canvas.initialBiddingFinishTime;
if (finishTime == 0) {
canvas.initialBiddingFinishTime = getTime() + BIDDING_DURATION;
}
bids[_canvasId] = Bid(msg.sender, msg.value);
if (canvas.owner != 0x0) {
addressToCount[canvas.owner]--;
}
canvas.owner = msg.sender;
addressToCount[msg.sender]++;
_registerBid(_canvasId, msg.value);
emit BidPosted(_canvasId, msg.sender, msg.value, canvas.initialBiddingFinishTime);
}
/**
* @notice Returns last bid for canvas. If the initial bidding has been
* already finished that will be winning offer.
*/
function getLastBidForCanvas(uint32 _canvasId) external view returns (
uint32 canvasId,
address bidder,
uint amount,
uint finishTime
) {
Bid storage bid = bids[_canvasId];
Canvas storage canvas = _getCanvas(_canvasId);
return (_canvasId, bid.bidder, bid.amount, canvas.initialBiddingFinishTime);
}
/**
* @notice Returns number of canvases owned by the given address.
*/
function balanceOf(address _owner) external view returns (uint) {
return addressToCount[_owner];
}
/**
* @notice Only for the owner of the contract. Sets minimum bid amount.
*/
function setMinimumBidAmount(uint _amount) external onlyOwner {
minimumBidAmount = _amount;
}
struct Bid {
address bidder;
uint amount;
}
}
/**
* @dev This contract takes trading our artworks. Trading can happen
* if artwork has been initially bought.
*/
contract CanvasMarket is BiddableCanvas {
mapping(uint32 => SellOffer) canvasForSale;
mapping(uint32 => BuyOffer) buyOffers;
event CanvasOfferedForSale(uint32 indexed canvasId, uint minPrice, address indexed from, address indexed to);
event SellOfferCancelled(uint32 indexed canvasId, uint minPrice, address indexed from, address indexed to);
event CanvasSold(uint32 indexed canvasId, uint amount, address indexed from, address indexed to);
event BuyOfferMade(uint32 indexed canvasId, address indexed buyer, uint amount);
event BuyOfferCancelled(uint32 indexed canvasId, address indexed buyer, uint amount);
struct SellOffer {
bool isForSale;
address seller;
uint minPrice;
address onlySellTo; // specify to sell only to a specific address
}
struct BuyOffer {
bool hasOffer;
address buyer;
uint amount;
}
/**
* @notice Buy artwork. Artwork has to be put on sale. If buyer has bid before for
* that artwork, that bid will be canceled.
*/
function acceptSellOffer(uint32 _canvasId)
external
payable
stateOwned(_canvasId)
forceOwned(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
SellOffer memory sellOffer = canvasForSale[_canvasId];
require(msg.sender != canvas.owner);
//don't sell for the owner
require(sellOffer.isForSale);
require(msg.value >= sellOffer.minPrice);
require(sellOffer.seller == canvas.owner);
//seller is no longer owner
require(sellOffer.onlySellTo == 0x0 || sellOffer.onlySellTo == msg.sender);
//protect from selling to unintended address
uint toTransfer;
(, ,toTransfer) = _registerTrade(_canvasId, msg.value);
addPendingWithdrawal(sellOffer.seller, toTransfer);
addressToCount[canvas.owner]--;
addressToCount[msg.sender]++;
canvas.owner = msg.sender;
_cancelSellOfferInternal(_canvasId, false);
emit CanvasSold(_canvasId, msg.value, sellOffer.seller, msg.sender);
//If the buyer have placed buy offer, refund it
BuyOffer memory offer = buyOffers[_canvasId];
if (offer.buyer == msg.sender) {
buyOffers[_canvasId] = BuyOffer(false, 0x0, 0);
if (offer.amount > 0) {
//refund offer
addPendingWithdrawal(offer.buyer, offer.amount);
}
}
}
/**
* @notice Offer canvas for sale for a minimal price.
* Anybody can buy it for an amount grater or equal to min price.
*/
function offerCanvasForSale(uint32 _canvasId, uint _minPrice) external {
_offerCanvasForSaleInternal(_canvasId, _minPrice, 0x0);
}
/**
* @notice Offer canvas for sale to a given address. Only that address
* is allowed to buy canvas for an amount grater or equal
* to minimal price.
*/
function offerCanvasForSaleToAddress(uint32 _canvasId, uint _minPrice, address _receiver) external {
_offerCanvasForSaleInternal(_canvasId, _minPrice, _receiver);
}
/**
* @notice Cancels previously made sell offer. Caller has to be an owner
* of the canvas. Function will fail if there is no sell offer
* for the canvas.
*/
function cancelSellOffer(uint32 _canvasId) external {
_cancelSellOfferInternal(_canvasId, true);
}
/**
* @notice Places buy offer for the canvas. It cannot be called by the owner of the canvas.
* New offer has to be bigger than existing offer. Returns ethers to the previous
* bidder, if any.
*/
function makeBuyOffer(uint32 _canvasId) external payable stateOwned(_canvasId) forceOwned(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
BuyOffer storage existing = buyOffers[_canvasId];
require(canvas.owner != msg.sender);
require(canvas.owner != 0x0);
require(msg.value > existing.amount);
if (existing.amount > 0) {
//refund previous buy offer.
addPendingWithdrawal(existing.buyer, existing.amount);
}
buyOffers[_canvasId] = BuyOffer(true, msg.sender, msg.value);
emit BuyOfferMade(_canvasId, msg.sender, msg.value);
}
/**
* @notice Cancels previously made buy offer. Caller has to be an author
* of the offer.
*/
function cancelBuyOffer(uint32 _canvasId) external stateOwned(_canvasId) forceOwned(_canvasId) {
BuyOffer memory offer = buyOffers[_canvasId];
require(offer.buyer == msg.sender);
buyOffers[_canvasId] = BuyOffer(false, 0x0, 0);
if (offer.amount > 0) {
//refund offer
addPendingWithdrawal(offer.buyer, offer.amount);
}
emit BuyOfferCancelled(_canvasId, offer.buyer, offer.amount);
}
/**
* @notice Accepts buy offer for the canvas. Caller has to be the owner
* of the canvas. You can specify minimal price, which is the
* protection against accidental calls.
*/
function acceptBuyOffer(uint32 _canvasId, uint _minPrice) external stateOwned(_canvasId) forceOwned(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
require(canvas.owner == msg.sender);
BuyOffer memory offer = buyOffers[_canvasId];
require(offer.hasOffer);
require(offer.amount > 0);
require(offer.buyer != 0x0);
require(offer.amount >= _minPrice);
uint toTransfer;
(, ,toTransfer) = _registerTrade(_canvasId, offer.amount);
addressToCount[canvas.owner]--;
addressToCount[offer.buyer]++;
canvas.owner = offer.buyer;
addPendingWithdrawal(msg.sender, toTransfer);
buyOffers[_canvasId] = BuyOffer(false, 0x0, 0);
canvasForSale[_canvasId] = SellOffer(false, 0x0, 0, 0x0);
emit CanvasSold(_canvasId, offer.amount, msg.sender, offer.buyer);
}
/**
* @notice Returns current buy offer for the canvas.
*/
function getCurrentBuyOffer(uint32 _canvasId)
external
view
returns (bool hasOffer, address buyer, uint amount) {
BuyOffer storage offer = buyOffers[_canvasId];
return (offer.hasOffer, offer.buyer, offer.amount);
}
/**
* @notice Returns current sell offer for the canvas.
*/
function getCurrentSellOffer(uint32 _canvasId)
external
view
returns (bool isForSale, address seller, uint minPrice, address onlySellTo) {
SellOffer storage offer = canvasForSale[_canvasId];
return (offer.isForSale, offer.seller, offer.minPrice, offer.onlySellTo);
}
function _offerCanvasForSaleInternal(uint32 _canvasId, uint _minPrice, address _receiver)
private
stateOwned(_canvasId)
forceOwned(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
require(canvas.owner == msg.sender);
require(_receiver != canvas.owner);
canvasForSale[_canvasId] = SellOffer(true, msg.sender, _minPrice, _receiver);
emit CanvasOfferedForSale(_canvasId, _minPrice, msg.sender, _receiver);
}
function _cancelSellOfferInternal(uint32 _canvasId, bool emitEvent)
private
stateOwned(_canvasId)
forceOwned(_canvasId) {
Canvas storage canvas = _getCanvas(_canvasId);
SellOffer memory oldOffer = canvasForSale[_canvasId];
require(canvas.owner == msg.sender);
require(oldOffer.isForSale);
//don't allow to cancel if there is no offer
canvasForSale[_canvasId] = SellOffer(false, msg.sender, 0, 0x0);
if (emitEvent) {
emit SellOfferCancelled(_canvasId, oldOffer.minPrice, oldOffer.seller, oldOffer.onlySellTo);
}
}
}
contract CryptoArt is CanvasMarket {
function getCanvasInfo(uint32 _canvasId) external view returns (
uint32 id,
string name,
uint32 paintedPixels,
uint8 canvasState,
uint initialBiddingFinishTime,
address owner,
address bookedFor
) {
Canvas storage canvas = _getCanvas(_canvasId);
return (_canvasId, canvas.name, canvas.paintedPixelsCount, getCanvasState(_canvasId),
canvas.initialBiddingFinishTime, canvas.owner, canvas.bookedFor);
}
function getCanvasByOwner(address _owner) external view returns (uint32[]) {
uint32[] memory result = new uint32[](canvases.length);
uint currentIndex = 0;
for (uint32 i = 0; i < canvases.length; i++) {
if (getCanvasState(i) == STATE_OWNED) {
Canvas storage canvas = _getCanvas(i);
if (canvas.owner == _owner) {
result[currentIndex] = i;
currentIndex++;
}
}
}
return _slice(result, 0, currentIndex);
}
/**
* @notice Returns array of canvas's ids. Returned canvases have sell offer.
* If includePrivateOffers is true, includes offers that are targeted
* only to one specified address.
*/
function getCanvasesWithSellOffer(bool includePrivateOffers) external view returns (uint32[]) {
uint32[] memory result = new uint32[](canvases.length);
uint currentIndex = 0;
for (uint32 i = 0; i < canvases.length; i++) {
SellOffer storage offer = canvasForSale[i];
if (offer.isForSale && (includePrivateOffers || offer.onlySellTo == 0x0)) {
result[currentIndex] = i;
currentIndex++;
}
}
return _slice(result, 0, currentIndex);
}
/**
* @notice Returns array of all the owners of all of pixels. If some pixel hasn't
* been painted yet, 0x0 address will be returned.
*/
function getCanvasPainters(uint32 _canvasId) external view returns (address[]) {
Canvas storage canvas = _getCanvas(_canvasId);
address[] memory result = new address[](PIXEL_COUNT);
for (uint32 i = 0; i < PIXEL_COUNT; i++) {
result[i] = canvas.pixels[i].painter;
}
return result;
}
}
|
Calculates how the money from selling canvas will be split. return Commission, sum of painters' rewards and a seller's profit./ We make sure that painters reward is divisible by PIXEL_COUNT. It is important to split reward across all the painters equally.check for the underflow
|
function splitTrade(uint _amount) public pure returns (
uint commission,
uint paintersRewards,
uint sellerProfit
){
uint _commission = _calculatePercent(_amount, COMMISSION);
uint _rewardPerPixel = _calculatePercent(_amount, TRADE_REWARD) / PIXEL_COUNT;
uint _paintersReward = _rewardPerPixel * PIXEL_COUNT;
uint _sellerProfit = _amount - _commission - _paintersReward;
require(_sellerProfit < _amount);
return (_commission, _paintersReward, _sellerProfit);
}
| 5,907,394 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _governance;
event GovernanceTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_governance = msgSender;
emit GovernanceTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _governance;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_governance == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit GovernanceTransferred(_governance, newOwner);
_governance = newOwner;
}
}
// File: contracts/strategies/StabilizeStrategyUSTFlashArbV2.sol
pragma solidity ^0.6.6;
// This is a strategy that takes advantage of arb opportunities for ust
// Users deposit ust into the strategy and the strategy will sell into usdt when above usdt and usdt into ust when below
// Selling will occur via Uniswap or Curve and buying WETH via Uniswap
// Half the profit earned from the sell will be used to buy WETH and split it between the treasury, executor and staking pool
// Half will remain
// This strategy also uses flash loans to take advantage of opportunities in price inversions between exchanges
// Strategy takes into account 0.3% slippage estimate for large sells on Uniswap
interface StabilizeStakingPool {
function notifyRewardAmount(uint256) external;
}
interface UniswapRouter {
function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory);
function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory);
function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out
}
interface CurvePool {
function get_dy_underlying(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange_underlying(int128, int128, uint256, uint256) external; // Exchange tokens
}
interface LendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
}
interface LendingPool {
function flashLoan(address, address[] calldata, uint256[] calldata, uint256[] calldata, address, bytes calldata params, uint16) external;
}
interface AggregatorV3Interface {
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
contract StabilizeStrategyUSTFlashArbV2 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
address public treasuryAddress; // Address of the treasury
address public stakingAddress; // Address to the STBZ staking pool
address public zsTokenAddress; // The address of the controlling zs-Token
uint256 constant DIVISION_FACTOR = 100000;
uint256 public lastTradeTime = 0;
uint256 public lastActionBalance = 0; // Balance before last deposit or withdraw
uint256 public maxPoolSize = 3000000e18; // The maximum amount of ust tokens this strategy can hold, 3 mil by default
uint256 public percentTradeTrigger = 10000; // 10% change in value will trigger a trade
uint256 public maxSlippage = 300; // 0.3% max slippage is ok
uint256 public maxPercentSell = 80000; // 80% of the tokens are sold to the cheapest token if slippage is ok on Uni
uint256 public maxAmountSell = 500000; // The maximum amount of tokens that can be sold at once
uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains
uint256 public percentExecutor = 10000; // 30000 = 30% of WETH goes to executor, 15% of total profit
uint256 public percentStakers = 50000; // 50% of non-depositors WETH goes to stakers, can be changed
uint256 public minTradeSplit = 20000; // If the balance is less than or equal to this, it trades the entire balance
uint256 public maxPercentStipend = 30000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent
uint256 public gasStipend = 1000000; // This is the gas units that are covered by executing a trade taken from the WETH profit
uint256[3] private flashParams; // Global parameters guiding the flash loan setup
uint256 constant minGain = 1e16; // Minimum amount of gain (0.01 coin) before buying WETH and splitting it
// Token information
// This strategy accepts frax and usdc
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
// Strategy specific variables
address constant UNISWAP_ROUTER_ADDRESS = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Address of Uniswap
address constant CURVE_UST_POOL = address(0x890f4e345B1dAED0367A877a1612f86A1f86985f);
address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle
address constant LENDING_POOL_ADDRESS_PROVIDER = address(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); // Provider for Aave addresses
constructor(
address _treasury,
address _staking,
address _zsToken
) public {
treasuryAddress = _treasury;
stakingAddress = _staking;
zsTokenAddress = _zsToken;
setupWithdrawTokens();
}
// Initialization functions
function setupWithdrawTokens() internal {
// Start with UST
IERC20 _token = IERC20(address(0xa47c8bf37f92aBed4A126BDA807A7b7498661acD));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
// USDT
_token = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
}
// Modifier
modifier onlyZSToken() {
require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token");
_;
}
// Read functions
function rewardTokensCount() external view returns (uint256) {
return tokenList.length;
}
function rewardTokenAddress(uint256 _pos) external view returns (address) {
require(_pos < tokenList.length,"No token at that position");
return address(tokenList[_pos].token);
}
function balance() public view returns (uint256) {
return getNormalizedTotalBalance(address(this));
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
uint256 _balance = 0;
for(uint256 i = 0; i < tokenList.length; i++){
uint256 _bal = tokenList[i].token.balanceOf(_address);
_bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
_balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
}
return _balance;
}
function withdrawTokenReserves() public view returns (address, uint256) {
// This function will return the address and amount of frax, then usdc
if(tokenList[0].token.balanceOf(address(this)) > 0){
return (address(tokenList[0].token), tokenList[0].token.balanceOf(address(this)));
}else if(tokenList[1].token.balanceOf(address(this)) > 0){
return (address(tokenList[1].token), tokenList[1].token.balanceOf(address(this)));
}else{
return (address(0), 0); // No balance
}
}
// Write functions
function enter() external onlyZSToken {
deposit(false);
}
function exit() external onlyZSToken {
// The ZS token vault is removing all tokens from this strategy
withdraw(_msgSender(),1,1, false);
}
function deposit(bool nonContract) public onlyZSToken {
// Only the ZS token can call the function
// No trading is performed on deposit
if(nonContract == true){ }
lastActionBalance = balance();
require(lastActionBalance <= maxPoolSize,"This strategy has reached its maximum balance");
}
function simulateExchange(address _inputToken, address _outputToken, uint256 _amount, bool _uniswap) internal view returns (uint256) {
if(_uniswap == true){
// Possible Uniswap routes, UST / USDT, USDT / ETH
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path;
if(_inputToken == address(tokenList[0].token) && _outputToken == WETH_ADDRESS){
// Selling UST for WETH, must go through USDT
path = new address[](3);
path[0] = _inputToken;
path[1] = address(tokenList[1].token);
path[2] = _outputToken;
}else{
path = new address[](2);
path[0] = _inputToken;
path[1] = _outputToken;
}
uint256[] memory estimates = router.getAmountsOut(_amount, path);
_amount = estimates[estimates.length - 1]; // This is the amount of WETH returned
return _amount;
}else{
// We are swapping via curve
CurvePool pool = CurvePool(CURVE_UST_POOL);
int128 inCurve = 0;
int128 outCurve = 0;
if(_inputToken == address(tokenList[1].token)){inCurve = 3;}
if(_outputToken == address(tokenList[1].token)){outCurve = 3;}
return pool.get_dy_underlying(inCurve, outCurve, _amount);
}
}
function exchange(address _inputToken, address _outputToken, uint256 _amount, bool _uniswap) internal {
if(_uniswap == true){
// Possible Uniswap routes, UST / USDT, USDT / ETH
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path;
if(_inputToken == address(tokenList[0].token) && _outputToken == WETH_ADDRESS){
// Selling UST for WETH, must go through USDT
path = new address[](3);
path[0] = _inputToken;
path[1] = address(tokenList[1].token);
path[2] = _outputToken;
}else{
path = new address[](2);
path[0] = _inputToken;
path[1] = _outputToken;
}
IERC20(_inputToken).safeApprove(UNISWAP_ROUTER_ADDRESS, 0);
IERC20(_inputToken).safeApprove(UNISWAP_ROUTER_ADDRESS, _amount);
router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token
return;
}else{
// We are swapping via curve
CurvePool pool = CurvePool(CURVE_UST_POOL);
int128 inCurve = 0;
int128 outCurve = 0;
if(_inputToken == address(tokenList[1].token)){inCurve = 3;}
if(_outputToken == address(tokenList[1].token)){outCurve = 3;}
IERC20(_inputToken).safeApprove(CURVE_UST_POOL, 0);
IERC20(_inputToken).safeApprove(CURVE_UST_POOL, _amount);
pool.exchange_underlying(inCurve, outCurve, _amount, 1);
}
}
function getCheaperToken() internal view returns (uint256, uint256, bool) {
// This will give us the ID of the cheapest token for both Uniswap and Curve
// We will estimate the return for trading 10000 UST
// The higher the return, the lower the price of the other token
// It will also suggest which exchange we should use, Uniswap or Curve
uint256 targetID_1 = 0; // Our target ID is UST first
uint256 targetID_2 = 0;
bool useUni = false;
uint256 ustAmount = uint256(10000).mul(10**tokenList[0].decimals);
// Now compare it to USDT on Uniswap
uint256 estimate = simulateExchange(address(tokenList[0].token),address(tokenList[1].token),ustAmount,true);
estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[1].decimals);
if(estimate > ustAmount){
// This token is worth less than the UST on Uniswap
targetID_1 = 1;
}
// Now on Curve
uint256 estimate2 = simulateExchange(address(tokenList[0].token),address(tokenList[1].token),ustAmount,false);
estimate2 = estimate2.mul(10**tokenList[0].decimals).div(10**tokenList[1].decimals);
if(estimate2 > ustAmount){
// This token is worth less than UST on curve
targetID_2 = 1;
}
// Now determine which exchange offers the better rate between the two
if(targetID_1 == targetID_2){
if(targetID_1 == 1){
// USDT is weaker token on both exchanges
if(estimate2 >= estimate){
// Get more USDT from Curve
useUni = false;
}else{
useUni = true;
}
}else{
// UST is weaker token on both exchanges
if(estimate2 > estimate){
// Get more UST from Uni
useUni = true;
}else{
useUni = false;
}
}
}else{
if(targetID_1 == 0){
// When we flash loan to increase our USDT, sell it on Uni as it is more valuable on there
useUni = true;
}else{
// When we flash loan to increase our USDT, sell it on Curve as it is more valuable there
useUni = false;
}
}
return (targetID_1, targetID_2, useUni);
}
function estimateSellAtMaxSlippage(uint256 originID, uint256 targetID, uint256 _balance) internal view returns (uint256) {
// This will estimate the amount that can be sold at the maximum slippage
// We discover the price then compare it to the actual return
// The estimate is based on a linear curve so not 100% representative of Uniswap but close enough
// It will use a 0.1% sell to discover the price first
uint256 minSellPercent = maxPercentSell.div(1000);
uint256 _amount = _balance.mul(minSellPercent).div(DIVISION_FACTOR);
if(_amount == 0){ return 0; } // Nothing to sell, can't calculate
uint256 _maxReturn = simulateExchange(address(tokenList[originID].token), address(tokenList[targetID].token), _amount, true);
_maxReturn = _maxReturn.mul(1000); // Without slippage, this would be our maximum return
// Now calculate the slippage at the max percent
_amount = _balance.mul(maxPercentSell).div(DIVISION_FACTOR);
uint256 _return = simulateExchange(address(tokenList[originID].token), address(tokenList[targetID].token), _amount, true);
if(_return >= _maxReturn){
// This shouldn't be possible
return _amount; // Sell the entire amount
}
// Calculate slippage
uint256 percentSlip = uint256(_maxReturn.mul(DIVISION_FACTOR)).sub(_return.mul(DIVISION_FACTOR)).div(_maxReturn);
if(percentSlip <= maxSlippage){
return _amount; // This is less than our maximum slippage, sell it all
}
return _amount.mul(maxSlippage).div(percentSlip); // This will be the sell amount at max slip
}
function estimateFlashLoanResult(uint256 point1, uint256 point2, uint256 _amount) internal view returns (uint256) {
// This will estimate the return of our flash loan minus the fee
uint256 fee = _amount.mul(90).div(DIVISION_FACTOR); // This is the Aave fee (0.09%)
uint256 gain = 0;
if(point2 > point1){
// USL price is lower than USDT on Uniswap, while higher on Curve
// Use the borrowed USDT to buy USL on Uniswap
gain = simulateExchange(address(tokenList[1].token), address(tokenList[0].token), _amount, true); // Receive USL
gain = simulateExchange(address(tokenList[0].token), address(tokenList[1].token), gain, false); // Receive USDT
}else{
// USL price higher than USDT on Uniswap while lower on Curve
gain = simulateExchange(address(tokenList[1].token), address(tokenList[0].token), _amount, false); // Receive USL
gain = simulateExchange(address(tokenList[0].token), address(tokenList[1].token), gain, true); // Receive USDT
}
if(gain > _amount.add(fee)){
// Positive return on the flash
gain = gain.sub(fee).sub(_amount); // Get the pure gain after returning the funds with a fee
return gain;
}else{
return 0; // Do not take out a flash loan as not enough gain
}
}
function performFlashLoan(uint256 point1, uint256 point2, uint256 _amount) internal returns (uint256) {
// Will call Aave
uint256 flashGain = tokenList[1].token.balanceOf(address(this));
flashParams[0] = 1; // Authorize flash loan receiving
flashParams[1] = point1;
flashParams[2] = point2;
// Call the flash loan
LendingPool lender = LendingPool(LendingPoolAddressesProvider(LENDING_POOL_ADDRESS_PROVIDER).getLendingPool()); // Load the lending pool
address[] memory assets = new address[](1);
assets[0] = address(tokenList[1].token);
uint256[] memory amounts = new uint256[](1);
amounts[0] = _amount; // The amount we want to borrow
uint256[] memory modes = new uint256[](1);
modes[0] = 0; // Revert if fail to return funds
bytes memory params = "";
lender.flashLoan(address(this), assets, amounts, modes, address(this), params, 0);
flashParams[0] = 0; // Deactivate flash loan receiving
uint256 newBal = tokenList[1].token.balanceOf(address(this));
require(newBal > flashGain, "Flash loan failed to increase balance");
flashGain = newBal.sub(flashGain);
uint256 payout = flashGain.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR);
if(payout > 0){
// Convert part to WETH
exchange(address(tokenList[1].token), WETH_ADDRESS, payout, true);
}
return flashGain;
}
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
)
external
returns (bool)
{
require(flashParams[0] == 1, "No flash loan authorized on this contract");
address lendingPool = LendingPoolAddressesProvider(LENDING_POOL_ADDRESS_PROVIDER).getLendingPool();
require(_msgSender() == lendingPool, "Not called from Aave");
require(initiator == address(this), "Not Authorized"); // Prevent other contracts from calling this function
if(params.length == 0){} // Removes the warning
flashParams[0] = 0; // Prevent a replay;
{
// Create inner scope to prevent stack too deep error
uint256 point1 = flashParams[1];
uint256 point2 = flashParams[2];
uint256 _bal;
// Swap the amounts to earn more
if(point2 > point1){
// USL price is lower than USDT on Uniswap, while higher on Curve
// Use the borrowed USDT to buy USL on Uniswap
_bal = tokenList[0].token.balanceOf(address(this));
exchange(address(tokenList[1].token), address(tokenList[0].token), amounts[0], true); // Receive USL
_bal = tokenList[0].token.balanceOf(address(this)).sub(_bal);
exchange(address(tokenList[0].token), address(tokenList[1].token), _bal, false); // Receive USDT
}else{
// USL price higher than USDT on Uniswap while lower on Curve
_bal = tokenList[0].token.balanceOf(address(this));
exchange(address(tokenList[1].token), address(tokenList[0].token), amounts[0], false); // Receive USL
_bal = tokenList[0].token.balanceOf(address(this)).sub(_bal);
exchange(address(tokenList[0].token), address(tokenList[1].token), _bal, true); // Receive USDT
}
}
// Authorize Aave to pull funds from this contract
// Approve the LendingPool contract allowance to *pull* the owed amount
for(uint256 i = 0; i < assets.length; i++) {
uint256 amountOwing = amounts[i].add(premiums[i]);
IERC20(assets[i]).safeApprove(lendingPool, 0);
IERC20(assets[i]).safeApprove(lendingPool, amountOwing);
}
return true;
}
function getFastGasPrice() internal view returns (uint256) {
AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS);
( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer
return uint256(intGasPrice);
}
function checkAndSwapTokens(address _executor) internal {
lastTradeTime = now;
// Now find our target token to sell into
(uint256 targetID_1, uint256 targetID_2, bool useUniswap) = getCheaperToken(); // Normally both these values should point to the same ID
uint256 targetID;
if(targetID_1 == targetID_2){
targetID = targetID_1;
}else{
// The fun part (flash laon)
// Since prices are inverse between the exchanges
// We will call Aave to borrow USDT, sell it for UST, sell UST on another exchange for more USDT than we original borrowed
// First determine borrow size at the max slippage
uint256 maxBorrow = uint256(1000000).mul(10**tokenList[1].decimals); // Predict based on $1million
maxBorrow = estimateSellAtMaxSlippage(1, 0, maxBorrow);
// Now estimate the return of the flash loan
if(estimateFlashLoanResult(targetID_1, targetID_2, maxBorrow) > 2){
// Flash loan will be profitable, borrow the funds
performFlashLoan(targetID_1, targetID_2, maxBorrow); // This will return USDT earned and exchange it for WETH
}
targetID = 0; // Sell whatever gains are possible for more UST
}
uint256 length = tokenList.length;
// Now sell all the other tokens into this token
uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase
bool _expectIncrease = false;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 sellBalance = 0;
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals); // Determine the maximum amount of tokens to sell at once
if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = tokenList[i].token.balanceOf(address(this));
}else{
if(useUniswap == true){
sellBalance = estimateSellAtMaxSlippage(i, targetID, tokenList[i].token.balanceOf(address(this))); // This will select a balance with a max slippage
}else{
// Curve supports larger sells
sellBalance = tokenList[i].token.balanceOf(address(this)).mul(maxPercentSell).div(DIVISION_FACTOR);
}
}
if(sellBalance > _maxTradeTarget){
// If greater than the maximum trade allowed, match it
sellBalance = _maxTradeTarget;
}
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
if(sellBalance > 0){
uint256 estimate = simulateExchange(address(tokenList[i].token), address(tokenList[targetID].token), sellBalance, useUniswap);
if(estimate > minReceiveBalance){
_expectIncrease = true;
exchange(address(tokenList[i].token), address(tokenList[targetID].token), sellBalance, useUniswap);
}
}
}
}
uint256 _newBalance = balance();
if(_expectIncrease == true){
// There may be rare scenarios where we don't gain any by calling this function
require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
}
uint256 gain = _newBalance.sub(_totalBalance);
IERC20 weth = IERC20(WETH_ADDRESS);
uint256 _wethBalance = weth.balanceOf(address(this));
if(gain >= minGain || _wethBalance > 0){
// Minimum gain required to buy WETH is about 0.01 tokens
if(gain >= minGain){
// Buy WETH from Uniswap with tokens
uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR);
sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){
// Sell some of our gained token for WETH
exchange(address(tokenList[targetID].token), WETH_ADDRESS, sellBalance, true);
_wethBalance = weth.balanceOf(address(this));
}
}
if(_wethBalance > 0){
// Split the rest between the stakers and such
// This is pure profit, figure out allocation
// Split the amount sent to the treasury, stakers and executor if one exists
if(_executor != address(0)){
// Executors will get a gas reimbursement in WETH and a percent of the remaining
uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested
if(gasFee > maxGasFee){
gasFee = maxGasFee; // Gas fee cannot be greater than the maximum
}
uint256 executorAmount = gasFee;
if(gasFee >= _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR)){
executorAmount = _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point
}else{
// Add the executor percent on top of gas fee
executorAmount = _wethBalance.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee);
}
if(executorAmount > 0){
weth.safeTransfer(_executor, executorAmount);
_wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract
}
}
if(_wethBalance > 0){
uint256 stakersAmount = _wethBalance.mul(percentStakers).div(DIVISION_FACTOR);
uint256 treasuryAmount = _wethBalance.sub(stakersAmount);
if(treasuryAmount > 0){
weth.safeTransfer(treasuryAddress, treasuryAmount);
}
if(stakersAmount > 0){
if(stakingAddress != address(0)){
weth.safeTransfer(stakingAddress, stakersAmount);
StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount);
}else{
// No staking pool selected, just send to the treasury
weth.safeTransfer(treasuryAddress, stakersAmount);
}
}
}
}
}
}
function expectedProfit(bool inWETHForExecutor) external view returns (uint256) {
// This view will return the amount of gain a forced swap will make on next call
// Now find our target token to sell into
(uint256 targetID_1, uint256 targetID_2, bool useUniswap) = getCheaperToken(); // Normally both these values should point to the same ID
uint256 targetID;
uint256 flashGain = 0;
if(targetID_1 == targetID_2){
targetID = targetID_1;
}else{
// The fun part (flash loan)
// Since prices are inverse between the exchanges
// We will call Aave to borrow USDT, sell it for UST, sell UST on another exchange for more USDT than we original borrowed
// First determine borrow size at the max slippage
uint256 maxBorrow = uint256(1000000).mul(10**tokenList[1].decimals); // Predict based on $1million
maxBorrow = estimateSellAtMaxSlippage(1, 0, maxBorrow);
// Now estimate the return of the flash loan
flashGain = estimateFlashLoanResult(targetID_1, targetID_2, maxBorrow);
if(flashGain > 0){
if(inWETHForExecutor == true){
flashGain = simulateExchange(address(tokenList[1].token), WETH_ADDRESS, flashGain.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR), true);
}else{
// Normalize it
flashGain = flashGain.mul(1e18).div(10**tokenList[1].decimals);
}
}
targetID = 0;
}
uint256 length = tokenList.length;
// Now simulate sell all the other tokens into this token
uint256 _normalizedGain = 0;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 sellBalance = 0;
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals); // Determine the maximum amount of tokens to sell at once
if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = tokenList[i].token.balanceOf(address(this));
}else{
if(useUniswap == true){
sellBalance = estimateSellAtMaxSlippage(i, targetID, tokenList[i].token.balanceOf(address(this))); // This will select a balance with a max slippage
}else{
// Curve supports larger sells
sellBalance = tokenList[i].token.balanceOf(address(this)).mul(maxPercentSell).div(DIVISION_FACTOR);
}
}
if(sellBalance > _maxTradeTarget){
// If greater than the maximum trade allowed, match it
sellBalance = _maxTradeTarget;
}
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
if(sellBalance > 0){
uint256 estimate = simulateExchange(address(tokenList[i].token), address(tokenList[targetID].token), sellBalance, useUniswap);
if(estimate > minReceiveBalance){
uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[targetID].decimals); // Normalized gain
_normalizedGain = _normalizedGain.add(_gain);
}
}
}
}
if(inWETHForExecutor == false){
return _normalizedGain.add(flashGain);
}else{
if(_normalizedGain.add(flashGain) == 0){
return 0;
}
// Calculate how much WETH the executor would make as profit
uint256 estimate = flashGain; // WETH earned from flashloan
if(_normalizedGain > 0){
uint256 sellBalance = _normalizedGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR);
sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
// Estimate output
estimate = estimate.add(simulateExchange(address(tokenList[targetID].token), WETH_ADDRESS, sellBalance, true));
}
// Now calculate the amount going to the executor
uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total
return estimate.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get max percent of total
}else{
estimate = estimate.sub(gasFee); // Subtract fee from remaining balance
return estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee); // Executor amount with fee added
}
}
}
function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) {
require(balance() > 0, "There are no tokens in this strategy");
if(nonContract == true){
if( _share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){
checkAndSwapTokens(_depositor);
}
}
uint256 withdrawAmount = 0;
uint256 _balance = balance();
if(_share < _total){
uint256 _myBalance = _balance.mul(_share).div(_total);
withdrawPerOrder(_depositor, _myBalance, false); // This will withdraw based on token price
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
withdrawPerOrder(_depositor, _balance, true);
withdrawAmount = _balance;
}
lastActionBalance = balance();
return withdrawAmount;
}
// This will withdraw the tokens from the contract based on their order
function withdrawPerOrder(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
uint256 length = tokenList.length;
if(_takeAll == true){
// Send the entire balance
for(uint256 i = 0; i < length; i++){
uint256 _bal = tokenList[i].token.balanceOf(address(this));
if(_bal > 0){
tokenList[i].token.safeTransfer(_receiver, _bal);
}
}
return;
}
for(uint256 i = 0; i < length; i++){
// Determine the balance left
uint256 _normalizedBalance = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
tokenList[i].token.safeTransfer(_receiver, tokenList[i].token.balanceOf(address(this)));
}
}else{
// Withdraw a partial amount of this token
if(_withdrawAmount > 0){
// Convert the withdraw amount to the token's decimal amount
uint256 _balance = _withdrawAmount.mul(10**tokenList[i].decimals).div(1e18);
_withdrawAmount = 0;
tokenList[i].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade) external {
// Function designed to promote trading with incentive. Users get 20% of WETH from profitable trades
require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent");
require(_msgSender() == tx.origin, "Contracts cannot interact with this function");
checkAndSwapTokens(_executor);
lastActionBalance = balance();
}
// Governance functions
function governanceSwapTokens() external onlyGovernance {
// This is function that force trade tokens at anytime. It can only be called by governance
checkAndSwapTokens(governance());
lastActionBalance = balance();
}
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
uint256[7] private _timelock_data;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(balance() > 0){ // Timelock only applies when balance exists
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeTreasury(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
}
function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) {
treasuryAddress = _timelock_address;
}
// --------------------
// Change the staking address
// --------------------
function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) {
stakingAddress = _timelock_address;
}
// --------------------
// Change the zsToken address
// --------------------
function startChangeZSToken(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 4;
_timelock_address = _address;
}
function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) {
zsTokenAddress = _timelock_address;
}
// --------------------
// Change the trading conditions used by the strategy
// --------------------
function startChangeTradingConditions(uint256 _pTradeTrigger, uint256 _pSellPercent, uint256 _mSellAmount, uint256 _minSplit, uint256 _maxStipend, uint256 _pMaxStipend, uint256 _pSlip) external onlyGovernance {
// Changes a lot of trading parameters in one call
require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 100000 && _pSlip <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 5;
_timelock_data[0] = _pTradeTrigger;
_timelock_data[1] = _pSellPercent;
_timelock_data[2] = _minSplit;
_timelock_data[3] = _maxStipend;
_timelock_data[4] = _pMaxStipend;
_timelock_data[5] = _pSlip;
_timelock_data[6] = _mSellAmount;
}
function finishChangeTradingConditions() external onlyGovernance timelockConditionsMet(5) {
percentTradeTrigger = _timelock_data[0];
maxPercentSell = _timelock_data[1];
minTradeSplit = _timelock_data[2];
gasStipend = _timelock_data[3];
maxPercentStipend = _timelock_data[4];
maxSlippage = _timelock_data[5];
maxAmountSell = _timelock_data[6];
}
// --------------------
// Change the strategy allocations between the parties
// --------------------
function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers, uint256 _maxPool) external onlyGovernance {
// Changes strategy allocations in one call
require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 6;
_timelock_data[0] = _pDepositors;
_timelock_data[1] = _pExecutor;
_timelock_data[2] = _pStakers;
_timelock_data[3] = _maxPool;
}
function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(6) {
percentDepositor = _timelock_data[0];
percentExecutor = _timelock_data[1];
percentStakers = _timelock_data[2];
maxPoolSize = _timelock_data[3];
}
// --------------------
}
|
This view will return the amount of gain a forced swap will make on next call Now find our target token to sell into The fun part (flash loan) Since prices are inverse between the exchanges We will call Aave to borrow USDT, sell it for UST, sell UST on another exchange for more USDT than we original borrowed First determine borrow size at the max slippage Now estimate the return of the flash loan Normalize it If balance is too small,sell all tokens at once Curve supports larger sells If greater than the maximum trade allowed, match it Calculate how much WETH the executor would make as profit Estimate output
|
function expectedProfit(bool inWETHForExecutor) external view returns (uint256) {
uint256 targetID;
uint256 flashGain = 0;
if(targetID_1 == targetID_2){
targetID = targetID_1;
maxBorrow = estimateSellAtMaxSlippage(1, 0, maxBorrow);
flashGain = estimateFlashLoanResult(targetID_1, targetID_2, maxBorrow);
if(flashGain > 0){
if(inWETHForExecutor == true){
flashGain = simulateExchange(address(tokenList[1].token), WETH_ADDRESS, flashGain.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR), true);
flashGain = flashGain.mul(1e18).div(10**tokenList[1].decimals);
}
}
targetID = 0;
}
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 sellBalance = 0;
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){
sellBalance = tokenList[i].token.balanceOf(address(this));
if(useUniswap == true){
sellBalance = tokenList[i].token.balanceOf(address(this)).mul(maxPercentSell).div(DIVISION_FACTOR);
}
}
if(sellBalance > _maxTradeTarget){
sellBalance = _maxTradeTarget;
}
if(sellBalance > 0){
uint256 estimate = simulateExchange(address(tokenList[i].token), address(tokenList[targetID].token), sellBalance, useUniswap);
if(estimate > minReceiveBalance){
_normalizedGain = _normalizedGain.add(_gain);
}
}
}
}
if(inWETHForExecutor == false){
return _normalizedGain.add(flashGain);
if(_normalizedGain.add(flashGain) == 0){
return 0;
}
if(_normalizedGain > 0){
uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR);
estimate = estimate.add(simulateExchange(address(tokenList[targetID].token), WETH_ADDRESS, sellBalance, true));
}
}
}
| 6,320,809 |
pragma solidity >=0.4.22 <0.7.0;
//declare contract
contract Election {
//model a candidate
struct Candidate {
uint id;
string name;
uint voteCount;
}
string Question; //Question
address EventAdmin;
uint256 constant NULL = 0;
string Qst;
//store accounts that have voted
mapping(address => bool) public voters;
mapping (string => bool) public voted;
//store candidate
//fetch candidate
mapping(uint =>Candidate) public candidates; //mapping is an associative array r a hash associative key value pairs with one another
//store candidates Count
uint public candidatesCount;
string public candidate;
modifier onlyOwner {
require(msg.sender == EventAdmin,'No access');
_;
}
//constructor
constructor () public {
addCandidate("NOTA");
EventAdmin = msg.sender;
}
function setQuestion(string memory theQuestion) public{
if(bytes(Qst).length == 0 )
{
Question = theQuestion;
Qst = Question;
}
}
function getCandidate (uint _candidateId) public view returns (uint _id, string memory _name, uint _voteCount) {
_id = candidates[_candidateId].id;
_name = candidates[_candidateId].name;
_voteCount = candidates[_candidateId].voteCount;
}
function getQuestion() public view returns(string memory) {
return Question;
}
function addCandidate (string memory _name) public { // private because not too be accessible by public interface of contract
candidatesCount ++;
candidates[candidatesCount] = Candidate({id: candidatesCount, name: _name, voteCount:0} );
}
function vote (uint _candidateId, string memory _mailId) public {
//user haven't voted before
//require(!voters[msg.sender],'User have voted before!!');
require(!voted[_mailId], 'User have voted before!!');
//valid candidate
require(_candidateId > 0 && _candidateId <= candidatesCount,'Invalid candidate');
voters[msg.sender] = true;
voted[_mailId] = true;
candidates[_candidateId].voteCount ++;
}
function hasVoted (string memory _mailId) public view returns (bool _voted) {
_voted = voted[_mailId];
}
}
|
user haven't voted beforerequire(!voters[msg.sender],'User have voted before!!');valid candidate
|
function vote (uint _candidateId, string memory _mailId) public {
require(!voted[_mailId], 'User have voted before!!');
require(_candidateId > 0 && _candidateId <= candidatesCount,'Invalid candidate');
voters[msg.sender] = true;
voted[_mailId] = true;
candidates[_candidateId].voteCount ++;
}
| 5,461,346 |
./partial_match/1/0xE3C67a3be126b6f41D66EAbB89F1e346Cd099195/sources/MiltonUsdt.sol
|
Interface for interaction with Joseph - smart contract responsible for managing ipTokens and ERC20 tokens in IPOR Protocol.
|
interface IJoseph {
function calculateExchangeRate() external view returns (uint256);
function provideLiquidity(uint256 assetAmount) external;
function redeem(uint256 ipTokenAmount) external;
function checkVaultReservesRatio() external view returns (uint256);
event ProvideLiquidity(
uint256 timestamp,
address from,
address to,
uint256 exchangeRate,
uint256 assetAmount,
uint256 ipTokenAmount
);
event Redeem(
uint256 timestamp,
address from,
address to,
uint256 exchangeRate,
uint256 assetAmount,
uint256 ipTokenAmount,
uint256 redeemFee,
uint256 redeemAmount
);
}
}
| 2,612,649 |
./full_match/44787/0x6cb63f11859E4e7930F550A724D3681F345c9FFf/sources/contracts/NFTForCarbonAuction.sol
|
ends the bidding without sending NFTs
|
function end() external {
_end();
emit End();
}
| 13,248,831 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "./IERC20.sol";
import "../access/Ownable.sol";
import "../interfaces/IUniswapV2Pair.sol";
import "../interfaces/IUniswapV2Factory.sol";
import "../interfaces/IUniswapV2Router02.sol";
contract Safe is IERC20, Ownable {
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcluded;
mapping(address => bool) private _isExcludedFromFee;
address[] private _excluded;
address private _burnPool = 0x0000000000000000000000000000000000000000;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 100_000_000_000;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _tBurnTotal;
string private _name;
string private _symbol;
uint8 private _decimals;
//2%
uint8 public _taxFee = 2;
uint8 private _previousTaxFee = _taxFee;
//2%
uint8 public _burnFee = 2;
uint8 private _previousBurnFee = _burnFee;
uint8 public _liquidityFee = 6;
uint8 private _previousLiquidityFee = _liquidityFee;
uint256 public _lpRewardFromLiquidity = 1;
uint256 public _maxTxAmount = 50000 * 10**18;
uint256 public totalLiquidityProviderRewards;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool public BurnLpTokensEnabled = false;
uint256 public TotalBurnedLpTokens;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = false;
uint256 private minTokensBeforeSwap = 8000;
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
event RewardLiquidityProviders(uint256 tokenAmount);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
/**
* @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 three of these values are immutable: they can only be set once during
* construction.
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router =
IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function setTaxFeePercent(uint8 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function setBurnFeePercent(uint8 burnFee) external onlyOwner() {
_burnFee = burnFee;
}
function setLiquidityFeePercent(uint8 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
function setLpRewardFromLiquidityPercent(uint256 percent)
external
onlyOwner()
{
_lpRewardFromLiquidity = percent;
}
function setMaxTxPercent(uint256 maxTxPercent, uint256 maxTxDecimals)
external
onlyOwner()
{
_maxTxAmount =
(_tTotal * (maxTxPercent)) /
(10**(uint256(maxTxDecimals) + 2));
}
function setBurnLpTokenEnabled(bool value) external onlyOwner() {
BurnLpTokensEnabled = value;
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
)
public
override
returns (bool)
{
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"ERC20: transfer amount exceeds allowance"
);
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender] + addedValue
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(
!_isExcluded[sender],
"Excluded addresses cannot call this function"
);
(uint256 rAmount, , , , , , ) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender] - (rAmount);
_rTotal = _rTotal - (rAmount);
_tFeeTotal = _tFeeTotal + (tAmount);
}
function withDrawLpTokens() public onlyOwner {
IUniswapV2Pair token = IUniswapV2Pair(uniswapV2Pair);
uint256 amount = token.balanceOf(address(this));
require(amount > 0, "Not enough LP tokens available to withdraw");
token.transfer(owner(), amount);
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
/**
* @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 this function is
* overloaded;
*
* 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 _tTotal;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount, , , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount)
public
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount / (currentRate);
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function totalBurn() public view returns (uint256) {
return _tBurnTotal;
}
function LpTokenBalance() public view returns (uint256) {
IUniswapV2Pair token = IUniswapV2Pair(uniswapV2Pair);
uint256 amount = token.balanceOf(address(this));
return amount;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
/**
* @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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
)
private
{
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner())
require(
amount <= _maxTxAmount,
"Transfer amount exceeds the maxTxAmount"
);
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
//calculate lp rewards
uint256 lpRewardAmount =
(contractTokenBalance * (_lpRewardFromLiquidity)) / (10**2);
//distribute rewards
_rewardLiquidityProviders(lpRewardAmount);
//add liquidity
swapAndLiquify(contractTokenBalance - (lpRewardAmount));
//burn lp tokens, hence locking the liquidity forever
if (BurnLpTokensEnabled) burnLpTokens();
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from, to, amount, takeFee);
}
/**
* @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
)
private
{
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
)
private
{
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
)
private
{
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tBurn,
uint256 tLiquidity
) = _getValues(tAmount);
uint256 rBurn = tBurn * (currentRate);
_rOwned[sender] = _rOwned[sender] - (rAmount);
_rOwned[recipient] = _rOwned[recipient] + (rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
)
private
{
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tBurn,
uint256 tLiquidity
) = _getValues(tAmount);
uint256 rBurn = tBurn * (currentRate);
_rOwned[sender] = _rOwned[sender] - (rAmount);
_tOwned[recipient] = _tOwned[recipient] + (tTransferAmount);
_rOwned[recipient] = _rOwned[recipient] + (rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
)
private
{
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tBurn,
uint256 tLiquidity
) = _getValues(tAmount);
uint256 rBurn = tBurn * (currentRate);
_tOwned[sender] = _tOwned[sender] - (tAmount);
_rOwned[sender] = _rOwned[sender] - (rAmount);
_rOwned[recipient] = _rOwned[recipient] + (rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
)
private
{
uint256 currentRate = _getRate();
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tBurn,
uint256 tLiquidity
) = _getValues(tAmount);
uint256 rBurn = tBurn * (currentRate);
_tOwned[sender] = _tOwned[sender] - (tAmount);
_rOwned[sender] = _rOwned[sender] - (rAmount);
_tOwned[recipient] = _tOwned[recipient] + (tTransferAmount);
_rOwned[recipient] = _rOwned[recipient] + (rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, rBurn, tFee, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(
uint256 rFee,
uint256 rBurn,
uint256 tFee,
uint256 tBurn
)
private
{
_rTotal = _rTotal - (rFee) - (rBurn);
_tFeeTotal = _tFeeTotal + (tFee);
_tBurnTotal = _tBurnTotal + (tBurn);
_tTotal = _tTotal - (tBurn);
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_burnFee = _previousBurnFee;
_liquidityFee = _previousLiquidityFee;
}
function removeAllFee() private {
if (_taxFee == 0 && _burnFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousBurnFee = _burnFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_burnFee = 0;
_liquidityFee = 0;
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
uint256 half = contractTokenBalance / (2);
uint256 otherHalf = contractTokenBalance - (half);
// 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 liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance - (initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity * (currentRate);
_rOwned[address(this)] = _rOwned[address(this)] + (rLiquidity);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)] + (tLiquidity);
}
function _rewardLiquidityProviders(uint256 liquidityRewards) private {
// avoid fee calling _tokenTransfer with false
_tokenTransfer(address(this), uniswapV2Pair, liquidityRewards, false);
IUniswapV2Pair(uniswapV2Pair).sync();
totalLiquidityProviderRewards =
totalLiquidityProviderRewards +
(liquidityRewards);
emit RewardLiquidityProviders(liquidityRewards);
}
function burnLpTokens() private {
IUniswapV2Pair _token = IUniswapV2Pair(uniswapV2Pair);
uint256 amount = _token.balanceOf(address(this));
TotalBurnedLpTokens = TotalBurnedLpTokens + (amount);
_token.transfer(_burnPool, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return (_amount * (_taxFee)) / (10**2);
}
function calculateBurnFee(uint256 _amount) private view returns (uint256) {
return (_amount * (_burnFee)) / (10**2);
}
function calculateLiquidityFee(uint256 _amount)
private
view
returns (uint256)
{
return (_amount * (_liquidityFee)) / (10**2);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply / (tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (
_rOwned[_excluded[i]] > rSupply ||
_tOwned[_excluded[i]] > tSupply
) return (_rTotal, _tTotal);
rSupply = rSupply - (_rOwned[_excluded[i]]);
tSupply = tSupply - (_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal / (_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(
uint256 tTransferAmount,
uint256 tFee,
uint256 tBurn,
uint256 tLiquidity
) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tBurn, tLiquidity, _getRate());
return (
rAmount,
rTransferAmount,
rFee,
tTransferAmount,
tFee,
tBurn,
tLiquidity
);
}
function _getTValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
uint256 tFee = calculateTaxFee(tAmount);
uint256 tBurn = calculateBurnFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount - (tFee) - (tBurn) - (tLiquidity);
return (tTransferAmount, tFee, tBurn, tLiquidity);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tBurn,
uint256 tLiquidity,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount * (currentRate);
uint256 rFee = tFee * (currentRate);
uint256 rBurn = tBurn * (currentRate);
uint256 rLiquidity = tLiquidity * (currentRate);
uint256 rTransferAmount = rAmount - (rFee) - (rBurn) - (rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
}
|
Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`./
|
function decreaseAllowance(address spender, uint256 subtractedValue)
public
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
| 5,432,441 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.