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: UNLICENSED
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./interfaces/IIdleCDOStrategy.sol";
import "./interfaces/IERC20Detailed.sol";
import "./interfaces/IIdleCDOTrancheRewards.sol";
import "./interfaces/IIdleCDO.sol";
import "./IdleCDOTrancheRewardsStorage.sol";
/// @author Idle Labs Inc.
/// @title IdleCDOTrancheRewards
/// @notice Contract used for staking specific tranche tokens and getting incentive rewards
/// This contract keeps the accounting of how many rewards each user is entitled to using 2 indexs:
/// a per-user index (`usersIndexes[user][reward]`) and a global index (`rewardsIndexes[reward]`)
/// The difference of those indexes
contract IdleCDOTrancheRewards is Initializable, PausableUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable, IIdleCDOTrancheRewards, IdleCDOTrancheRewardsStorage {
using SafeERC20Upgradeable for IERC20Detailed;
// Used to prevent initialization of the implementation contract
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
tranche = address(1);
}
/// @notice Initialize the contract
/// @param _trancheToken tranche address
/// @param _rewards rewards token array
/// @param _owner The owner of the contract
/// @param _idleCDO The CDO where the reward tokens come from
/// @param _governanceRecoveryFund address where rewards will be sent in case of transferToken call
/// @param _coolingPeriod number of blocks that needs to pass since last rewards deposit
/// before all rewards are unlocked. Rewards are unlocked linearly for `_coolingPeriod` blocks
function initialize(
address _trancheToken, address[] memory _rewards, address _owner,
address _idleCDO, address _governanceRecoveryFund, uint256 _coolingPeriod
) public initializer {
require(tranche == address(0), 'Initialized');
require(_owner != address(0) && _trancheToken != address(0) && _idleCDO != address(0) && _governanceRecoveryFund != address(0), "IS_0");
// Initialize inherited contracts
OwnableUpgradeable.__Ownable_init();
ReentrancyGuardUpgradeable.__ReentrancyGuard_init();
PausableUpgradeable.__Pausable_init();
// transfer ownership to owner
transferOwnership(_owner);
// set state variables
idleCDO = _idleCDO;
tranche = _trancheToken;
rewards = _rewards;
governanceRecoveryFund = _governanceRecoveryFund;
coolingPeriod = _coolingPeriod;
}
/// @notice Stake _amount of tranche token to receive rewards
/// @param _amount The amount of tranche tokens to stake
function stake(uint256 _amount) external whenNotPaused override {
_stake(msg.sender, msg.sender, _amount);
}
/// @notice Stake _amount of tranche token to receive rewards
/// used by IdleCDO to stake tranche tokens received as fees in an handy way
/// @param _user address of the user to stake for
/// @param _amount The amount of tranche tokens to stake
function stakeFor(address _user, uint256 _amount) external whenNotPaused override {
require(msg.sender == idleCDO, "!AUTH");
_stake(_user, msg.sender, _amount);
}
/// @notice Stake _amount of tranche token to receive rewards
/// @param _user address of the user to stake for
/// @param _payer address from which tranche tokens gets transferred
/// @param _amount The amount of tranche tokens to stake
function _stake(address _user, address _payer, uint256 _amount) internal {
if (_amount == 0) {
return;
}
// update user index for each reward, used to calculate the correct reward amount
// of rewards for each user
_updateUserIdx(_user, _amount);
// increase the staked amount associated with the user
usersStakes[_user] += _amount;
// increase the total staked amount counter
totalStaked += _amount;
// get _amount of `tranche` tokens from the payer
IERC20Detailed(tranche).safeTransferFrom(_payer, address(this), _amount);
}
/// @notice Unstake _amount of tranche tokens and redeem ALL accrued rewards
/// @dev if the contract is paused, unstaking any amount will cause the loss of all
/// accrued and unclaimed rewards so far
/// @param _amount The amount of tranche tokens to unstake
function unstake(uint256 _amount) external nonReentrant override {
if (_amount == 0) {
return;
}
if (paused()) {
// If the contract is paused, "unstake" will skip the claim of the rewards,
// and those rewards won't be claimable in the future.
address reward;
for (uint256 i = 0; i < rewards.length; i++) {
reward = rewards[i];
// set the user index equal to the global one, which means 0 rewards
usersIndexes[msg.sender][reward] = adjustedRewardIndex(reward);
}
} else {
// Claim all rewards accrued
_claim();
}
// if _amount is greater than usersStakes[msg.sender], the next line fails
usersStakes[msg.sender] -= _amount;
// update the total staked counter
totalStaked -= _amount;
// send funds to the user
IERC20Detailed(tranche).safeTransfer(msg.sender, _amount);
}
/// @notice Sends all the expected rewards to the msg.sender
/// @dev User index is reset
function claim() whenNotPaused nonReentrant external {
_claim();
}
/// @notice Claim all rewards, used by `claim` and `unstake`
function _claim() internal {
address[] memory _rewards = rewards;
for (uint256 i = 0; i < _rewards.length; i++) {
address reward = _rewards[i];
// get how much `reward` we should send to the user
uint256 amount = expectedUserReward(msg.sender, reward);
uint256 balance = IERC20Detailed(reward).balanceOf(address(this));
// Check that the amount is available in the contract
if (amount > balance) {
amount = balance;
}
// Set the user index equal to the global one, which means 0 rewards
usersIndexes[msg.sender][reward] = adjustedRewardIndex(reward);
// transfer the reward to the user
IERC20Detailed(reward).safeTransfer(msg.sender, amount);
}
}
/// @notice Calculates the expected rewards for a user
/// @param user The user address
/// @param reward The reward token address
/// @return The expected reward amount
function expectedUserReward(address user, address reward) public view returns (uint256) {
require(_includesAddress(rewards, reward), "!SUPPORTED");
// The amount of rewards for a specific reward token is given by the difference
// between the global index and the user's one multiplied by the user staked balance
// The rewards deposited are not unlocked right away, but linearly over `coolingPeriod`
// blocks so an adjusted global index is used.
// NOTE: stakes made when the coolingPeriod is not concluded won't receive any of those
// rewards (ie the index set for the user is the global, non adjusted, index)
uint256 _globalIdx = adjustedRewardIndex(reward);
uint256 _userIdx = usersIndexes[user][reward];
if (_userIdx > _globalIdx) {
return 0;
}
return ((_globalIdx - _userIdx) * usersStakes[user]) / ONE_TRANCHE_TOKEN;
}
/// @notice Calculates the adjusted global index for calculating rewards,
/// considering that rewards will be released over `coolingPeriod` blocks
/// @param _reward The reward token address
/// @return _index The adjusted global index
function adjustedRewardIndex(address _reward) public view returns (uint256 _index) {
uint256 _totalStaked = totalStaked;
// get number of rewards deposited in the last `depositReward` call
uint256 _lockedRewards = lockedRewards[_reward];
// get current global index, which considers all rewards
_index = rewardsIndexes[_reward];
if (_totalStaked > 0 && _lockedRewards > 0) {
// get blocks since last reward deposit
uint256 distance = block.number - lockedRewardsLastBlock[_reward];
if (distance < coolingPeriod) {
// if the cooling period has not passed, calculate the rewards that should
// still be locked
uint256 unlockedRewards = _lockedRewards * distance / coolingPeriod;
uint256 lockedRewards = _lockedRewards - unlockedRewards;
// and reduce the 'real' global index proportionally to the total amount staked
_index -= lockedRewards * ONE_TRANCHE_TOKEN / _totalStaked;
}
}
}
/// @notice Called by IdleCDO to deposit incentive rewards
/// @param _reward The rewards token address
/// @param _amount The amount to deposit
function depositReward(address _reward, uint256 _amount) external override {
require(msg.sender == idleCDO, "!AUTH");
require(_includesAddress(rewards, _reward), "!SUPPORTED");
// Get rewards from IdleCDO
IERC20Detailed(_reward).safeTransferFrom(msg.sender, address(this), _amount);
if (totalStaked > 0) {
// rewards are splitted among all stakers by increasing the global index
// proportionally for everyone (based on totalStaked)
// NOTE: for calculations `adjustedRewardIndex` is used instead, to release
// rewards linearly over `coolingPeriod` blocks
rewardsIndexes[_reward] += _amount * ONE_TRANCHE_TOKEN / totalStaked;
}
// save _amount of reward amount and block
lockedRewards[_reward] = _amount;
lockedRewardsLastBlock[_reward] = block.number;
}
/// @notice It sets the coolingPeriod that a user needs to wait since his last stake
/// before the unstake will be possible
/// @param _newCoolingPeriod The new cooling period
function setCoolingPeriod(uint256 _newCoolingPeriod) external onlyOwner {
coolingPeriod = _newCoolingPeriod;
}
/// @notice Update user index for each reward, based on the amount being staked
/// @param _user user who is staking
/// @param _amountToStake amount staked
function _updateUserIdx(address _user, uint256 _amountToStake) internal {
address[] memory _rewards = rewards;
uint256 userIndex;
address reward;
uint256 _currStake = usersStakes[_user];
for (uint256 i = 0; i < _rewards.length; i++) {
reward = _rewards[i];
if (_currStake == 0) {
// Set the user address equal to the global one which means 0 reward for the user
usersIndexes[_user][reward] = rewardsIndexes[reward];
} else {
userIndex = usersIndexes[_user][reward];
// Calculate the new user idx
// The user already staked something so he already have some accrued rewards
// which are: r = (rewardsIndexes - userIndex) * _currStake -> (see expectedUserReward method)
// Those same rewards should now be splitted between more staked tokens
// specifically (_currStake + _amountToStake) so the userIndex should increase.
usersIndexes[_user][reward] = userIndex + (
// Accrued rewards should not change after adding more staked tokens so
// we can calculate the increase of the userIndex by solving the following equation
// (rewardsIndexes - userIndex) * _currStake = (rewardsIndexes - (userIndex + X)) * (_currStake + _amountToStake)
// for X we get the increase for the userIndex:
_amountToStake * (rewardsIndexes[reward] - userIndex) / (_currStake + _amountToStake)
);
}
}
}
/// @dev this method is only used to check whether a token is an incentive tokens or not
/// in the depositReward call. The maximum number of element in the array will be a small number (eg at most 3-5)
/// @param _array array of addresses to search for an element
/// @param _val address of an element to find
/// @return flag if the _token is an incentive token or not
function _includesAddress(address[] memory _array, address _val) internal pure returns (bool) {
for (uint256 i = 0; i < _array.length; i++) {
if (_array[i] == _val) {
return true;
}
}
// explicit return to fix linter
return false;
}
// @notice Emergency method, funds gets transferred to the governanceRecoveryFund address
function transferToken(address token, uint256 value) external onlyOwner nonReentrant {
require(token != address(0), 'Address is 0');
IERC20Detailed(token).safeTransfer(governanceRecoveryFund, value);
}
/// @notice can be called by both the owner and the guardian
/// @dev Pauses deposits and redeems
function pause() external onlyOwner {
_pause();
}
/// @notice can be called by both the owner and the guardian
/// @dev Unpauses deposits and redeems
function unpause() external onlyOwner {
_unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
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 {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 || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + 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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.7;
interface IIdleCDOStrategy {
function strategyToken() external view returns(address);
function token() external view returns(address);
function tokenDecimals() external view returns(uint256);
function oneToken() external view returns(uint256);
function redeemRewards() external returns(uint256[] memory);
function pullStkAAVE() external returns(uint256);
function price() external view returns(uint256);
function getRewardTokens() external view returns(address[] memory);
function deposit(uint256 _amount) external returns(uint256);
// _amount in `strategyToken`
function redeem(uint256 _amount) external returns(uint256);
// _amount in `token`
function redeemUnderlying(uint256 _amount) external returns(uint256);
function getApr() external view returns(uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IERC20Detailed is IERC20Upgradeable {
function name() external view returns(string memory);
function symbol() external view returns(string memory);
function decimals() external view returns(uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.7;
interface IIdleCDOTrancheRewards {
function stake(uint256 _amount) external;
function stakeFor(address _user, uint256 _amount) external;
function unstake(uint256 _amount) external;
function depositReward(address _reward, uint256 _amount) external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.7;
interface IIdleCDO {
function redeemRewards() external;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.7;
contract IdleCDOTrancheRewardsStorage {
uint256 public constant ONE_TRANCHE_TOKEN = 10**18;
address public idleCDO;
address public tranche;
address public governanceRecoveryFund;
address[] public rewards;
// amount staked for each user
mapping(address => uint256) public usersStakes;
// globalIndex for each reward token
mapping(address => uint256) public rewardsIndexes;
// per-user index for each reward token
mapping(address => mapping(address => uint256)) public usersIndexes;
// rewards => last amount of reward deposited
mapping(address => uint256) public lockedRewards;
// rewards => block in which last rewards have been deposited
mapping(address => uint256) public lockedRewardsLastBlock;
// total amount of tranche tokens staked
uint256 public totalStaked;
// number of blocks during which rewards will be released for stakers
uint256 public coolingPeriod;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | Emergency method, funds gets transferred to the governanceRecoveryFund address | function transferToken(address token, uint256 value) external onlyOwner nonReentrant {
require(token != address(0), 'Address is 0');
IERC20Detailed(token).safeTransfer(governanceRecoveryFund, value);
}
| 11,824,201 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./libraries/Base64.sol";
import "./libraries/StringList.sol";
import "./libraries/FormatMetadata.sol";
import "./IPlotMetadata.sol";
import "./IPlot.sol";
contract PlotMetadata is IPlotMetadata, OwnableUpgradeable {
using Base64 for bytes;
using ECDSA for bytes32;
using SafeMath for uint256;
using StringList for string[];
using Strings for uint256;
string internal constant HEADER =
'<svg id=\\"plot\\" width=\\"100%\\" height=\\"100%\\" version=\\"1.1\\" viewBox=\\"0 0 64 64\\" xmlns=\\"http://www.w3.org/2000/svg\\" xmlns:xlink=\\"http://www.w3.org/1999/xlink\\">';
string internal constant FOOTER =
"<style>#plot{shape-rendering: crispedges; image-rendering: -webkit-crisp-edges; image-rendering: -moz-crisp-edges; image-rendering: crisp-edges; image-rendering: pixelated; -ms-interpolation-mode: nearest-neighbor;}</style></svg>";
string internal constant PNG_HEADER =
'<image x=\\"1\\" y=\\"1\\" width=\\"64\\" height=\\"64\\" image-rendering=\\"pixelated\\" preserveAspectRatio=\\"xMidYMid\\" xlink:href=\\"';
string internal constant PNG_FOOTER = '\\"/>';
string internal constant STAKED_LAYER =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAABTklEQVR42u3XMWuDUBSG4a/JKBIuQoghZBBHQbrlL/SfdxUsXYJDKXEoIiW4dLFDuBfbdDFJIVfeZzIOwnfO9RwjAQAAAAAAAAAAAAAAAAAAAACm5+EWD9ku1K/D8/vP77d5/n+a3Sp8nmSSpNTE7nq3UT/5Agw7b4N3baM8yXQ43v8rcFUBdhv1eZIpNbGKqlTXNgpMJEkqqtKLGTC7JnxqYklSYKIf3bdFmGwBbPjAROraRl3buELs29qrLTC7JLy9LqpSgYkUmMgd+TzJXEF8MB878Y9f0uPq1P2VWaqoSq3MUqHmeq0rhZq7U/DyMaE1uF2cOv+UZ9q3teuyHYCBiZSa2IX3YQOM+hDabdQfjqcC2GFn33v7exj+7fP+uz96BqxDnQ08OwR9DD/6U/j36hvue3vkfQp/UQH+uu9r+Iv+DNlZMORjcACQpG+Cj4F77K7KfwAAAABJRU5ErkJggg==";
string internal constant PLACEHOLDER_LAYER =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABABAMAAABYR2ztAAAAHlBMVEUdOwwqPBwiRQ8sP2k0WShCU3pRWDg+YipRZoe7sow31aPoAAAEs0lEQVRIx1WVTW/bRhCGR1umTm8clpXa23LAQOitgCKkuUnMANucHabOUUDhc8QusOm5NSBfjSTy/tu+s7TRmgZMQHx2Pt+ZJc75ZvPfM16dbs8pJMWfPUzLJ8A4nm6zc1FVB1kbQRnA5eP3rX3PnagBvjpyqp4CcJDzZ3FBJEzijtw+tTAbODNz7cPkqTs0vQGnR2A8wUBOSwAUEvmOF9X/AcvAALMgIXnyRBVdX+fT+OjADJwTt+waZLpbOOqJl/n+76dAikI+pDjRRdrTcvngYjt7OKeYYkcSU5gQCBNzvikurkqOGbXR4GWtIQ5SKVNdfZqBOYdzAYbmAoYmmoH7m3H8rwjWgvjR9+jFRL0Gqn88wfbmcrO9MSCpyBxeEr9GwQkncfTrF7z/sRDUuRT3qLEBUYXm7NInexcAKVZ7XmnyXqT3ABD8WV5YmgghKFEDoFXxbgY2+P3OPTMt3CKJyzT5XiMMUJhqlwC8HmToXhSxAKhlkj4gFSGd4AS9uB6cd99YnmaB3OWraIAniIqITDt4vXkEPP350mrBrCYJA6KSc2+slDmr7pClAUtWlARAUk1Q2AMQ1axDasoco3jpyPQdUI4CnMt3AKsEVaIksBFDDLl0a/yQ1SwIpAag0eCgXkohfpcvS7Py16ABBXAdX1gSYVch2RA+5nsDxvfXe0GJJkfNRcRRh16lDsBb6B7NfMfsqU/RUltbs/2FRitXkN+KAQBSryNbaquOUeeLSUIp1w8Atu//AEDrSWpaHFo+hEhVJ1ND6hbPNtvNqMhcYU5Mpi1zhRI7h1r2b4fSBxNzQmwNuwWv9ox0VPqdALActr/HVADvh67iFtXG5ASkQX1Jckz4wYBJBlcxl4KC0olk/cU8RAxKjAaIVBYBr0Q6xoyJ+/IQwoC9EVAmUa4BsDTfMqrCDpO5fWcK8SHECUeqSaqwZPELTgPV1sjtu4CWNqFY8DRgYpgnAoDBKY30DvIwdeF5VJl0GC+l783A+5qq+aupyCFDdEQ85KBUpARew0XZbWgFWHiCc0BaIrjyVCUbq5CmjrBc0EryvofkggHjLcYNqwoDtrYgDcAkeOecNwBqvyP3/IThlvohkoThk6ayUsNBPiOk5ycMuSfXqw2CHg8r02YyALMt9c/3tibuvLi5ZEcrNc/ALQABcAMTd52cbTOQHcbwQHII4ZwcrTMILII7yWbBYYSDSQjAVZ5wovoLaZzmPYcodjR0C651BrAqFgZkCwPJRgsTnVi2VvfNKUvjZcE/AbiZd0Q08UANrV0oiBEeoMO2mBivEPPUm54wwrh06Nfbsy2jbtnCyf3JlmlRBmxgUWIFoUwlSFNRnh+0EpqGgcEVAA2qvCOr8lv7/tmAmI6HdvDo5gjAVR7dC3pk2+Ca4s71uFUapJfow2dcD73FaYVZxQFr2v7ZteME3QSAmYA+Wxu+Frdhb1ci+gCrkCm9Ljes7g8AbMEOBNV510D2pt9AL+cr2PbWniEx3Wy8X5jubA+Q0KuYHvfWnptaoVHBWQqDKQrSewBsNveH2huAT7CN2nRuwthoOT67aOeNqjvfVfCyq3ZEWwMOqyNahy7iXrdB+sW+znP0L5PyHxY2/GBxAAAAAElFTkSuQmCC";
address public plotAddress;
address public oracleAddress;
string internal _baseImageURI;
string internal _description;
string internal _stakedDescription;
mapping(uint256 => string) internal _imageURIs;
function initialize(address _oracleAddress, address _plotAddress)
public
initializer
{
__Ownable_init();
oracleAddress = _oracleAddress;
plotAddress = _plotAddress;
_description = "A collection of 62,500 genesis Plots of land. Get a Plot to access the Critterz metaverse in Minecraft. Each Plot of land is 64 by 64 Minecraft blocks in size. Only owners of the Plots can build or destroy any blocks on it. You will have to stake Plots before building on them. Plots can also be minted using $BLOCK tokens.";
_stakedDescription = "You should ONLY get Staked Plots from here if you want to rent a Plot. These are NOT the same as Critterz Plot NFTs. Rented Plots also give access to the Critterz Minecraft world, but you cannot break or place any blocks for Plots you rented in and are time limited.";
}
/*
READ FUNCTIONS
*/
function getMetadata(
uint256 tokenId,
bool staked,
string[] calldata additionalAttributes
) external view override returns (string memory) {
string[] memory attributes = _getAttributes(tokenId);
return
_formatMetadata(tokenId, attributes.concat(additionalAttributes), staked);
}
function _formatMetadata(
uint256 tokenId,
string[] memory attributes,
bool staked
) internal view returns (string memory) {
string memory svg = _getSvg(tokenId, staked);
return
FormatMetadata.formatMetadataWithSVG(
_getName(tokenId, staked),
staked ? _stakedDescription : _description,
svg,
attributes,
""
);
}
function _getName(uint256 tokenId, bool staked)
internal
view
returns (string memory)
{
(int256 x, int256 y) = IPlot(plotAddress).getPlotCoordinate(tokenId);
return
string(
abi.encodePacked(staked ? "s" : "", "Plot ", _formatCoordinate(x, y))
);
}
function _getSvg(uint256 tokenId, bool staked)
internal
view
returns (string memory)
{
return
string(
abi.encodePacked(
HEADER,
_formatLayer(imageURI(tokenId)),
staked ? _formatLayer(STAKED_LAYER) : "",
FOOTER
)
);
}
function _getAttributes(uint256 tokenId)
internal
view
returns (string[] memory)
{
(int256 x, int256 y) = IPlot(plotAddress).getPlotCoordinate(tokenId);
string[] memory attributes = new string[](2);
attributes[0] = FormatMetadata.formatTraitNumber("x", x, "number");
attributes[1] = FormatMetadata.formatTraitNumber("y", y, "number");
return attributes;
}
function _formatLayer(string memory layer)
internal
pure
returns (string memory)
{
if (bytes(layer).length == 0) {
return "";
}
return string(abi.encodePacked(PNG_HEADER, layer, PNG_FOOTER));
}
function _formatCoordinate(int256 x, int256 y)
internal
pure
returns (string memory)
{
return
string(
abi.encodePacked(
"(",
FormatMetadata.intToString(x),
",",
FormatMetadata.intToString(y),
")"
)
);
}
function imageURI(uint256 tokenId) public view returns (string memory) {
string memory uri = _imageURIs[tokenId];
if (bytes(uri).length > 0) {
return uri;
}
string memory baseImageURI = _baseImageURI;
return
bytes(baseImageURI).length > 0
? string(abi.encodePacked(baseImageURI, tokenId.toString()))
: PLACEHOLDER_LAYER;
}
function _verify(bytes32 messageHash, bytes memory signature)
internal
view
returns (bool)
{
return
messageHash.toEthSignedMessageHash().recover(signature) == oracleAddress;
}
function _getMessageHash(
uint256 tokenId,
string memory uri,
uint256 exp
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(tokenId, uri, exp));
}
/*
WRITE FUNCTIONS
*/
function setImageURI(
uint256 tokenId,
string calldata uri,
uint256 exp,
bytes calldata signature
) external {
require(exp > block.number, "Signature expired");
require(
_verify(_getMessageHash(tokenId, uri, exp), signature),
"Invalid signature"
);
_imageURIs[tokenId] = uri;
}
/*
OWNER FUNCTIONS
*/
function setBaseImageURI(string calldata baseImageURI) external onlyOwner {
_baseImageURI = baseImageURI;
}
function setDescription(string calldata description) external onlyOwner {
_description = description;
}
function setStakedDescription(string calldata stakedDescription)
external
onlyOwner
{
_stakedDescription = stakedDescription;
}
function setOracleAddress(address _oracleAddress) external onlyOwner {
oracleAddress = _oracleAddress;
}
function setPlotAddress(address _plotAddress) external onlyOwner {
plotAddress = _plotAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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 initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_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.0 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/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.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
string internal constant TABLE_ENCODE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE_ENCODE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
// read 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// write 4 characters
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library StringList {
/**
* @dev join list of strings with delimiter
*/
function join(
string[] memory list,
string memory delimiter,
bool skipEmpty
) internal pure returns (string memory) {
if (list.length == 0) {
return "";
}
string memory result = list[0];
for (uint256 i = 1; i < list.length; i++) {
if (skipEmpty && bytes(list[i]).length == 0) continue;
result = string(abi.encodePacked(result, delimiter, list[i]));
}
return result;
}
/**
* @dev concatenate two lists of strings
*/
function concat(string[] memory list1, string[] memory list2)
internal
pure
returns (string[] memory)
{
string[] memory result = new string[](list1.length + list2.length);
for (uint256 i = 0; i < list1.length; i++) {
result[i] = list1[i];
}
for (uint256 i = 0; i < list2.length; i++) {
result[list1.length + i] = list2[i];
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Strings.sol";
import "./Base64.sol";
import "./StringList.sol";
library FormatMetadata {
using Base64 for bytes;
using StringList for string[];
using Strings for uint256;
function formatTraitString(string memory traitType, string memory value)
internal
pure
returns (string memory)
{
if (bytes(value).length == 0) {
return "";
}
return
string(
abi.encodePacked(
'{"trait_type":"',
traitType,
'","value":"',
value,
'"}'
)
);
}
function formatTraitNumber(
string memory traitType,
uint256 value,
string memory displayType
) internal pure returns (string memory) {
return
string(
abi.encodePacked(
'{"trait_type":"',
traitType,
'","value":',
value.toString(),
',"display_type":"',
displayType,
'"}'
)
);
}
function formatTraitNumber(
string memory traitType,
int256 value,
string memory displayType
) internal pure returns (string memory) {
return
string(
abi.encodePacked(
'{"trait_type":"',
traitType,
'","value":',
intToString(value),
',"display_type":"',
displayType,
'"}'
)
);
}
function formatMetadata(
string memory name,
string memory description,
string memory image,
string[] memory attributes,
string memory additionalMetadata
) internal pure returns (string memory) {
return
string(
abi.encodePacked(
"data:application/json;base64,",
bytes(
abi.encodePacked(
'{"name": "',
name,
'", "description": "',
description,
'", "image": "',
image,
'", "attributes": [',
attributes.join(", ", true),
"]",
bytes(additionalMetadata).length > 0 ? "," : "",
additionalMetadata,
"}"
)
).encode()
)
);
}
function formatMetadataWithSVG(
string memory name,
string memory description,
string memory svg,
string[] memory attributes,
string memory additionalMetadata
) internal pure returns (string memory) {
return
string(
abi.encodePacked(
"data:application/json;base64,",
bytes(
abi.encodePacked(
'{"name": "',
name,
'", "description": "',
description,
'", "image_data": "',
svg,
'", "attributes": [',
attributes.join(", ", true),
"]",
bytes(additionalMetadata).length > 0 ? "," : "",
additionalMetadata,
"}"
)
).encode()
)
);
}
function intToString(int256 n) internal pure returns (string memory) {
uint256 nAbs = n < 0 ? uint256(-n) : uint256(n);
bool nNeg = n < 0;
return string(abi.encodePacked(nNeg ? "-" : "", nAbs.toString()));
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPlotMetadata {
function getMetadata(
uint256 tokenId,
bool staked,
string[] calldata additionalAttributes
) external view returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IPlot {
function getPlotCoordinate(uint256 tokenId)
external
view
returns (int256, int256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
} | concatenate two lists of strings/ | function concat(string[] memory list1, string[] memory list2)
internal
pure
returns (string[] memory)
{
string[] memory result = new string[](list1.length + list2.length);
for (uint256 i = 0; i < list1.length; i++) {
result[i] = list1[i];
}
for (uint256 i = 0; i < list2.length; i++) {
result[list1.length + i] = list2[i];
}
return result;
}
| 17,505 |
// SPDX-License-Identifier: GPL-3.0
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.9;
/**
* @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
pragma solidity ^0.8.9;
/**
* @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
pragma solidity ^0.8.9;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.9;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.9;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface 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
pragma solidity ^0.8.9;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface 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
pragma solidity ^0.8.9;
/**
* @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
pragma solidity ^0.8.9;
/**
* @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
pragma solidity ^0.8.9;
/**
* @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);
}
pragma solidity >=0.8.9;
// to enable certain compiler features
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;
//Mapping para atribuirle un URI para cada token
mapping(uint256 => string) internal id_to_URI;
/**
* @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) { }
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
pragma solidity ^0.8.9;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
pragma solidity ^0.8.9;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// Creator: Chiru Labs
pragma solidity ^0.8.9;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*
* Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), 'ERC721A: global index out of bounds');
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
require(index < balanceOf(owner), 'ERC721A: owner index out of bounds');
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert('ERC721A: unable to get token of owner by index');
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), 'ERC721A: balance query for the zero address');
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), 'ERC721A: number minted query for the zero address');
return uint256(_addressData[owner].numberMinted);
}
/**
* 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 {
for (uint256 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[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 virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public 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 = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; 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 = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId].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 {}
}
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
contract PharaGods is ERC721A, Ownable {
using Strings for uint256;
//declares the maximum amount of tokens that can be minted, total and in presale
uint256 private maxTotalTokens;
//initial part of the URI for the metadata
string private _currentBaseURI;
//cost of mints depending on state of sale
uint private mintCostPresale = 1 ether;
uint private mintCostPublicSale = 1 ether;
//maximum amount of mints allowed per person
uint256 public maxMintPresale = 100;
uint256 public maxMintPublicSale = 100;
//the amount of reserved mints that have currently been executed by creator and giveaways
uint private _reservedMints;
//the maximum amount of reserved mints allowed for creator and giveaways
uint private maxReservedMints = 33;
//dummy address that we use to sign the mint transaction to make sure it is valid
address private dummy = 0x80E4929c869102140E69550BBECC20bEd61B080c;
//marks the timestamp of when the respective sales open
uint256 internal presaleLaunchTime;
uint256 internal publicSaleLaunchTime;
uint256 internal revealTime;
//dictates if sale is paused or not
bool private paused_;
//amount of mints that each address has executed
mapping(address => uint256) public mintsPerAddress;
//current state os sale
enum State {NoSale, Presale, PublicSale}
//defines the uri for when the NFTs have not been yet revealed
string public unrevealedURI;
//stores the amount of nfts that have recieved there payout
uint public amountOfTokensGotPayout;
//declaring initial values for variables
constructor() ERC721A('PharaGods', 'PG') {
maxTotalTokens = 3333;
//unrevealedURI = "ipfs://.../";
_currentBaseURI = "ipfs://QmcanEc6XwfaAmASeJbfaWrZskg2nFEXYKvRAuhhn6u6AX/";
//minting 2 legendaries for the opensea sale
reservedMint(2, msg.sender);
mintsPerAddress[msg.sender] += 2;
_reservedMints += 2;
}
//in case somebody accidentaly sends funds or transaction to contract
receive() payable external {}
fallback() payable external {
revert();
}
//visualize baseURI
function _baseURI() internal view virtual override returns (string memory) {
return _currentBaseURI;
}
//change baseURI in case needed for IPFS
function changeBaseURI(string memory baseURI_) public onlyOwner {
_currentBaseURI = baseURI_;
}
function changeUnrevealedURI(string memory unrevealedURI_) public onlyOwner {
unrevealedURI = unrevealedURI_;
}
function switchToPresale() public onlyOwner {
require(saleState() == State.NoSale, 'Sale is already Open!');
presaleLaunchTime = block.timestamp;
}
function switchToPublicSale() public onlyOwner {
require(saleState() == State.Presale, 'Sale must be in Presale!');
publicSaleLaunchTime = block.timestamp;
}
modifier onlyValidAccess(uint8 _v, bytes32 _r, bytes32 _s) {
require( isValidAccessMessage(msg.sender,_v,_r,_s), 'Invalid Signature' );
_;
}
/*
* @dev Verifies if message was signed by owner to give access to _add for this contract.
* Assumes Geth signature prefix.
* @param _add Address of agent with access
* @param _v ECDSA signature parameter v.
* @param _r ECDSA signature parameters r.
* @param _s ECDSA signature parameters s.
* @return Validity of access message for a given address.
*/
function isValidAccessMessage(address _add, uint8 _v, bytes32 _r, bytes32 _s) view public returns (bool) {
bytes32 hash = keccak256(abi.encodePacked(address(this), _add));
return dummy == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), _v, _r, _s);
}
//mint a @param number of NFTs in presale
function presaleMint(uint256 number, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {
require(!paused_, "Sale is paused!");
State saleState_ = saleState();
require(saleState_ != State.NoSale, "Sale in not open yet!");
require(saleState_ != State.PublicSale, "Presale has closed, Check out Public Sale!");
require(totalSupply() + number <= maxTotalTokens - (maxReservedMints - _reservedMints), "Not enough NFTs left to mint..");
require(mintsPerAddress[msg.sender] + number <= maxMintPresale, "Maximum Mints per Address exceeded!");
require(msg.value >= mintCost() * number, "Not sufficient Ether to mint this amount of NFTs");
_safeMint(msg.sender, number);
mintsPerAddress[msg.sender] += number;
}
//mint a @param number of NFTs in public sale
function publicSaleMint(uint256 number) public payable {
require(!paused_, "Sale is paused!");
State saleState_ = saleState();
require(saleState_ == State.PublicSale, "Public Sale in not open yet!");
require(totalSupply() + number <= maxTotalTokens - (maxReservedMints - _reservedMints), "Not enough NFTs left to mint..");
require(mintsPerAddress[msg.sender] + number <= maxMintPublicSale, "Maximum Mints per Address exceeded!");
require(msg.value >= mintCost() * number, "Not sufficient Ether to mint this amount of NFTs");
_safeMint(msg.sender, number);
mintsPerAddress[msg.sender] += number;
}
function tokenURI(uint256 tokenId_) public view virtual override returns (string memory) {
require(_exists(tokenId_), "ERC721Metadata: URI query for nonexistent token");
//check to see that 24 hours have passed since beginning of publicsale launch
if (revealTime == 0 && tokenId_ > 1) {
return unrevealedURI;
}
else {
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId_.toString(), '.json')) : "";
}
}
//reserved NFTs for creator
function reservedMint(uint number, address recipient) public onlyOwner {
require(_reservedMints + number <= maxReservedMints, "Not enough Reserved NFTs left to mint..");
_safeMint(recipient, number);
mintsPerAddress[recipient] += number;
_reservedMints += number;
}
//burn the tokens that have not been sold yet
function burnTokens() public onlyOwner {
maxTotalTokens = totalSupply();
}
//se the current account balance
function accountBalance() public onlyOwner view returns(uint) {
return address(this).balance;
}
//retrieve all funds recieved from minting
function withdraw() public onlyOwner {
uint256 balance = accountBalance();
require(balance > 0, 'No Funds to withdraw, Balance is 0');
_withdraw(payable(0xd7DDfE7233D872d3600549b570b3631604aA5ffF), balance);
}
//send the percentage of funds to a shareholder´s wallet
function _withdraw(address payable account, uint256 amount) internal {
(bool sent, ) = account.call{value: amount}("");
require(sent, "Failed to send Ether");
}
//change the dummy account used for signing transactions
function changeDummy(address _dummy) public onlyOwner {
dummy = _dummy;
}
//to see the total amount of reserved mints left
function reservedMintsLeft() public onlyOwner view returns(uint) {
return maxReservedMints - _reservedMints;
}
//see current state of sale
//see the current state of the sale
function saleState() public view returns(State){
if (presaleLaunchTime == 0) {
return State.NoSale;
}
else if (publicSaleLaunchTime == 0) {
return State.Presale;
}
else {
return State.PublicSale;
}
}
//gets the cost of current mint
function mintCost() public view returns(uint) {
State saleState_ = saleState();
if (saleState_ == State.NoSale || saleState_ == State.Presale) {
return mintCostPresale;
}
else {
return mintCostPublicSale;
}
}
function calculatePayout() public view returns(uint256) {
return accountBalance() / totalSupply();
}
function royaltyPayout(uint number, uint256 payout) public onlyOwner {
uint256 balance = accountBalance();
require(balance > number * payout, "Insufficient Funds to pay out Royalties!");
require(amountOfTokensGotPayout + number <= totalSupply());
for (uint i; i < number; i++) {
(bool success, ) = payable(ownerOf(amountOfTokensGotPayout + i)).call{value: payout}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
if (totalSupply() == amountOfTokensGotPayout + number) {
amountOfTokensGotPayout = 0;
}
else {
amountOfTokensGotPayout += number;
}
}
//see when NFTs will be revealed
function timeOfReveal() public view returns(uint256) {
require(revealTime != 0, 'NFT Reveal Time has not been determined yet!');
return revealTime;
}
function reveal() public onlyOwner {
require(revealTime == 0, "Collection has already been revealed!");
revealTime = block.timestamp;
}
function isPaused() public view returns(bool) {
return paused_;
}
//turn the pause on and off
function togglePause() public onlyOwner {
paused_ = !paused_;
}
//setting new prices to mint
function changeMintCostPresale(uint256 newCost) public onlyOwner {
mintCostPresale = newCost;
}
function changeMintCostPublicSale(uint256 newCost) public onlyOwner {
mintCostPublicSale = newCost;
}
//setting the maxes for mint
function changeMaxMintPresale(uint newMax) public onlyOwner {
maxMintPresale = newMax;
}
function changeMaxMintPublicSale(uint newMax) public onlyOwner {
maxMintPublicSale = newMax;
}
} | mint a number of NFTs in presale | function presaleMint(uint256 number, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {
require(!paused_, "Sale is paused!");
State saleState_ = saleState();
require(saleState_ != State.NoSale, "Sale in not open yet!");
require(saleState_ != State.PublicSale, "Presale has closed, Check out Public Sale!");
require(totalSupply() + number <= maxTotalTokens - (maxReservedMints - _reservedMints), "Not enough NFTs left to mint..");
require(mintsPerAddress[msg.sender] + number <= maxMintPresale, "Maximum Mints per Address exceeded!");
require(msg.value >= mintCost() * number, "Not sufficient Ether to mint this amount of NFTs");
_safeMint(msg.sender, number);
mintsPerAddress[msg.sender] += number;
}
| 5,856,582 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @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);
}
}
}
}
/**
* @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;
}
}
}
/**
* @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 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;
}
/**
* @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 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;
}
}
/**
* @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);
}
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature)
internal
pure
returns (address, RecoverError)
{
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
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);
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @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 {}
}
/**
* @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();
}
}
contract DogZone721 is ERC721, ERC721Enumerable, Ownable {
using SafeMath for uint256;
using Strings for uint256;
// Locked - 0
// Open - 1
// Ended - 2
enum SalePhase {
WaitingToStart,
InProgress,
Finished
}
// TODO: CREATE NEW WALLET, CHANGE THIS AND THE PRIVATE KEY!!!!
address private immutable signer = 0x304cE1e59421aCBc6adA104ba1b5F07f2f4676Cb;
string private _baseURIextended;
uint256 public constant MAX_TOKENS_PER_MINT = 50;
uint256 public constant MAX_TOKENS = 10000;
uint256 public constant TEAM_RESERVED_COUNT = 100;
uint256 private teamMintedCounter;
uint256 public usedSignaturesCount;
uint256 public tokenMintPrice = 0.003 ether; // 0.03 ETH initial
bool public metadataIsFrozen;
bool public giveawayAllowed;
bool public giveawayFrozen;
mapping(bytes => bool) public usedSignatures;
SalePhase public phase;
constructor() ERC721("DOG ZONE", "DOGZ") {}
// /// Freezes the metadata
// /// @dev sets the state of `metadataIsFrozen` to true
// /// @notice permamently freezes the metadata so that no more changes are possible
function freezeMetadata() external onlyOwner {
// require(!metadataIsFrozen, "Metadata is already frozen");
metadataIsFrozen = true;
}
// /// Adjust the mint price
// /// @dev modifies the state of the `mintPrice` variable
// /// @notice sets the price for minting a token
// /// @param newPrice_ The new price for minting
function adjustMintPrice(uint256 newPrice_) external onlyOwner {
tokenMintPrice = newPrice_;
}
// /// Advance Phase
// /// @dev Advance the sale phase state
// /// @notice Advances sale phase state incrementally
function enterNextPhase(SalePhase phase_) external onlyOwner {
require(
uint8(phase_) == uint8(phase) + 1 && (uint8(phase_) >= 0 && uint8(phase_) <= 2),
"can only advance phases"
);
phase = phase_;
}
/// Disburse payments
/// @dev transfers amounts that correspond to addresses passeed in as args
/// @param payees_ recipient addresses
/// @param amounts_ amount to payout to address with corresponding index in the `payees_` array
function disbursePayments(address[] memory payees_, uint256[] memory amounts_)
external
onlyOwner
{
require(payees_.length == amounts_.length, "Payees and amounts length mismatch");
for (uint256 i; i < payees_.length; i++) {
makePaymentTo(payees_[i], amounts_[i]);
}
}
/// Make a payment
/// @dev internal fn called by `disbursePayments` to send Ether to an address
function makePaymentTo(address address_, uint256 amt_) private {
(bool success, ) = address_.call{value: amt_}("");
require(success, "Transfer failed.");
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _transfer(
address from,
address to,
uint256 id
) internal override(ERC721) {
require(uint8(phase) > 1, "Transfers are not allowed yet.");
super._transfer(from, to, id);
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIextended;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function setBaseURI(string memory baseURI_) external onlyOwner {
require(!metadataIsFrozen, "Metadata is permanently frozen");
_baseURIextended = baseURI_;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "URI query for nonexistent token");
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), ".json"))
: "";
}
function _saleIsActive() private view {
require(uint8(phase) == 1, "Sale not active.");
}
modifier saleIsActive() {
_saleIsActive();
_;
}
function _notOverMaxSupply(uint256 supplyToMint, uint256 maxSupplyOfTokens) private pure {
require(supplyToMint <= maxSupplyOfTokens, "Reached Max Allowed to Buy."); // if it goes over 10000
}
function _isNotOverMaxPerMint(uint256 supplyToMint) private pure {
require(supplyToMint <= MAX_TOKENS_PER_MINT, "Reached Max to MINT per Purchase");
}
function recoverSigner(bytes32 hash, bytes memory signature) public pure returns (address) {
bytes32 messageDigest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
return ECDSA.recover(messageDigest, signature);
}
function teamMint(uint256 numberOfTokens, address receiver) public onlyOwner {
_isNotOverMaxPerMint(numberOfTokens);
_notOverMaxSupply(numberOfTokens + totalSupply(), MAX_TOKENS);
require(teamMintedCounter < TEAM_RESERVED_COUNT, "All team tokens are minted");
for (uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = teamMintedCounter + 1;
if (mintIndex <= MAX_TOKENS) {
_safeMint(receiver, mintIndex);
teamMintedCounter++;
}
}
}
function mint(uint256 numberOfTokens) public payable saleIsActive {
_isNotOverMaxPerMint(numberOfTokens);
_notOverMaxSupply(numberOfTokens + totalSupply(), MAX_TOKENS - TEAM_RESERVED_COUNT);
require(tokenMintPrice * numberOfTokens <= msg.value, "Ether is not enough.");
for (uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply() + TEAM_RESERVED_COUNT + 1;
if (mintIndex <= MAX_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
}
}
function enableGiveaway() public onlyOwner {
require(!giveawayFrozen, "Giveaway can not be enabled, it is frozen!");
giveawayAllowed = true;
}
function disableGiveaway() public onlyOwner {
giveawayAllowed = false;
giveawayFrozen = true;
}
function freeMint(bytes32 hash, bytes memory signature) public payable saleIsActive {
require(giveawayAllowed, "Giveaway not enabled");
_isNotOverMaxPerMint(1);
_notOverMaxSupply(1 + totalSupply(), MAX_TOKENS);
require(usedSignaturesCount < 25, "All Giveaway Spots are already used!");
require(
recoverSigner(hash, signature) == signer && !usedSignatures[signature],
"Free giveaway not allowed for your address!"
);
uint256 mintIndex = totalSupply() + 1;
if (mintIndex <= MAX_TOKENS) {
_safeMint(msg.sender, mintIndex);
}
usedSignatures[signature] = true;
usedSignaturesCount = usedSignaturesCount + 1;
}
} | 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);
}
}
| 336,020 |
./full_match/1/0xBe2440C38Cdb7920Ed8D77df6c97112779957286/sources/contracts/BullRun/BullRun.sol | mass update the nftType mapping | function setBatchNFTType(uint16[] calldata _idNumbers, uint8[] calldata _types) external onlyOwner {
require(_idNumbers.length == _types.length);
for (uint16 i = 0; i < _idNumbers.length;) {
require(_types[i] != 0 && _types[i] <= 3);
NFTType[_idNumbers[i]] = _types[i];
}
}
| 17,174,843 |
pragma solidity ^0.4.0;
contract ItemTracking {
struct Item {
uint id;
address owner;
uint[] components;
bool exists;
bool created;
}
mapping(uint => Item) items;
modifier itemCreated(uint id) {
if (items[id].created == false) {
throw;
}
_;
}
modifier itemNotCreated(uint id) {
if (items[id].created) {
throw;
}
_;
}
modifier itemExists(uint id) {
if (items[id].exists == false) {
throw;
}
_;
}
modifier itemsExist(uint[] ids) {
for (uint i = 0; i < ids.length; i++) {
if (items[ids[i]].exists == false) {
throw;
}
}
_;
}
modifier itemOwnedBySender(uint id) {
if (items[id].owner != msg.sender) {
throw;
}
_;
}
modifier itemsOwnedBySender(uint[] ids) {
for (uint i = 0; i < ids.length; i++) {
if (items[ids[i]].owner != msg.sender) {
throw;
}
}
_;
}
modifier itemIsCombined(uint id) {
if (items[id].components.length < 2) {
throw;
}
_;
}
modifier itemContainsComponents(uint id, uint[] componentIds) {
for (uint i = 0; i < componentIds.length; i++) {
bool componentFound = false;
for (uint j = 0; j < items[id].components.length; j++) {
if (items[id].components[j] == componentIds[i]) {
componentFound = true;
break;
}
}
if (!componentFound) {
throw;
}
}
_;
}
// Create a new item
function create(uint id)
itemNotCreated(id) {
items[id].id = id;
items[id].exists = true;
items[id].created = true;
items[id].owner = msg.sender;
}
// Combine items to create a single new one
function combine(uint[] srcIds, uint resultId)
itemsExist(srcIds)
itemsOwnedBySender(srcIds) {
// Verify that at least 2 components are being combined
if (srcIds.length < 2) {
throw;
}
for (uint i = 0; i < srcIds.length; i++) {
items[srcIds[i]].exists = false;
}
create(resultId);
items[resultId].components = srcIds;
}
// Split a combined item into its components
function split(uint srcId)
itemExists(srcId)
itemOwnedBySender(srcId)
itemIsCombined(srcId) {
items[srcId].exists = false;
for (uint i = 0; i < items[srcId].components.length; i++) {
uint componentId = items[srcId].components[i];
items[componentId].exists = true;
items[componentId].owner = items[srcId].owner;
}
}
// A private helper function for removing a component from the components
// array of an item. Doesn't handle error cases (e.g. invalid IDs or
// componentId not a component of itemID). The caller should make sure that
// input is valid.
function removeComponent(uint itemId, uint componentId) private {
// Find out what the components index is in parent item's component
// listing.
uint componentIndex = 0;
for (uint j = 0; j < items[itemId].components.length; j++) {
if (componentId == items[itemId].components[j]) {
componentIndex = j;
break;
}
}
// Remove item from componentIndex. To not bloat the array, let's do
// this by copying value from the last index to componentIndex and
// then remove the last index.
uint lastIndex = items[itemId].components.length - 1;
items[itemId].components[componentIndex] = items[itemId].components[lastIndex];
delete items[itemId].components[lastIndex];
items[itemId].components.length--;
}
// Extract the sub-components listed in the parameter. Leave the rest of the
// components in the parent item. Parent item maintains its old ID.
// If less than 2 components would remain in the parent component, then
// extract behaves exactly like split.
function extract(uint srcId, uint[] toBeExtractedIds)
itemExists(srcId)
itemOwnedBySender(srcId)
itemIsCombined(srcId)
itemContainsComponents(srcId, toBeExtractedIds) {
// If less than 2 components would remain in the parent item after
// the extraction, perform split.
if (items[srcId].components.length - toBeExtractedIds.length < 2) {
split(srcId);
return;
}
// Make extracted components exist and grant ownership to owner of
// parent item. Remove extracted components from parent item's component
// listing
for (uint i = 0; i < toBeExtractedIds.length; i++) {
uint componentId = toBeExtractedIds[i];
items[componentId].exists = true;
items[componentId].owner = items[srcId].owner;
removeComponent(srcId, componentId);
}
}
// Handover ownership of the item
function handover(uint id, address receiver)
itemExists(id)
itemOwnedBySender(id) {
items[id].owner = receiver;
}
// Return number of components for a given item
function getComponentCount(uint id)
itemCreated(id)
constant returns (uint) {
return items[id].components.length;
}
// Return ID of a component of a given parent item at given index.
function getComponentId(uint parentId, uint componentIndex)
itemCreated(parentId)
itemIsCombined(parentId)
constant returns (uint) {
if (componentIndex >= items[parentId].components.length) {
throw;
}
return items[parentId].components[componentIndex];
}
// Return owner of a given item
function getOwner(uint id) itemCreated(id) constant returns (address) {
return items[id].owner;
}
// Return exists status of a given item
function getExistsStatus(uint id) itemCreated(id) constant returns (bool) {
return items[id].exists;
}
// Return created status of a given item
function getCreatedStatus(uint id) constant returns (bool) {
return items[id].created;
}
} | Extract the sub-components listed in the parameter. Leave the rest of the components in the parent item. Parent item maintains its old ID. If less than 2 components would remain in the parent component, then extract behaves exactly like split. If less than 2 components would remain in the parent item after the extraction, perform split. Make extracted components exist and grant ownership to owner of parent item. Remove extracted components from parent item's component listing | function extract(uint srcId, uint[] toBeExtractedIds)
itemExists(srcId)
itemOwnedBySender(srcId)
itemIsCombined(srcId)
itemContainsComponents(srcId, toBeExtractedIds) {
if (items[srcId].components.length - toBeExtractedIds.length < 2) {
split(srcId);
return;
}
for (uint i = 0; i < toBeExtractedIds.length; i++) {
uint componentId = toBeExtractedIds[i];
items[componentId].exists = true;
items[componentId].owner = items[srcId].owner;
removeComponent(srcId, componentId);
}
}
| 7,320,419 |
/**
*Submitted for verification at Etherscan.io on 2021-04-28
*/
/**
*/
pragma solidity ^0.4.11;
contract Owned {
address public owner;
function Owned() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function setOwner(address _newOwner) onlyOwner {
owner = _newOwner;
}
}
/**
* @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;
}
function toUINT112(uint256 a) internal constant returns(uint112) {
assert(uint112(a) == a);
return uint112(a);
}
function toUINT120(uint256 a) internal constant returns(uint120) {
assert(uint120(a) == a);
return uint120(a);
}
function toUINT128(uint256 a) internal constant returns(uint128) {
assert(uint128(a) == a);
return uint128(a);
}
}
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
contract Token {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
//uint256 public totalSupply;
function totalSupply() constant returns (uint256 supply);
/// @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 `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, 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);
}
/// Nereon token, ERC20 compliant
contract Nereon is Token, Owned {
using SafeMath for uint256;
string public constant name = "Nereon Token"; //The Token's name
uint8 public constant decimals = 18; //Number of decimals of the smallest unit
string public constant symbol = "Nereon"; //An identifier
// packed to 256bit to save gas usage.
struct Supplies {
// uint128's max value is about 3e38.
// it's enough to present amount of tokens
uint128 total;
uint128 rawTokens;
}
Supplies supplies;
// Packed to 256bit to save gas usage.
struct Account {
// uint112's max value is about 5e33.
// it's enough to present amount of tokens
uint112 balance;
// raw token can be transformed into balance with bonus
uint112 rawTokens;
// safe to store timestamp
uint32 lastMintedTimestamp;
}
// Balances for each account
mapping(address => Account) accounts;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping(address => uint256)) allowed;
// bonus that can be shared by raw tokens
uint256 bonusOffered;
// Constructor
function Nereon() {
}
function totalSupply() constant returns (uint256 supply){
return supplies.total;
}
// Send back ether sent to me
function () {
revert();
}
// If sealed, transfer is enabled and mint is disabled
function isSealed() constant returns (bool) {
return owner == 0;
}
function lastMintedTimestamp(address _owner) constant returns(uint32) {
return accounts[_owner].lastMintedTimestamp;
}
// Claim bonus by raw tokens
function claimBonus(address _owner) internal{
require(isSealed());
if (accounts[_owner].rawTokens != 0) {
uint256 realBalance = balanceOf(_owner);
uint256 bonus = realBalance
.sub(accounts[_owner].balance)
.sub(accounts[_owner].rawTokens);
accounts[_owner].balance = realBalance.toUINT112();
accounts[_owner].rawTokens = 0;
if(bonus > 0){
Transfer(this, _owner, bonus);
}
}
}
// What is the balance of a particular account?
function balanceOf(address _owner) constant returns (uint256 balance) {
if (accounts[_owner].rawTokens == 0)
return accounts[_owner].balance;
if (bonusOffered > 0) {
uint256 bonus = bonusOffered
.mul(accounts[_owner].rawTokens)
.div(supplies.rawTokens);
return bonus.add(accounts[_owner].balance)
.add(accounts[_owner].rawTokens);
}
return uint256(accounts[_owner].balance)
.add(accounts[_owner].rawTokens);
}
// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _amount) returns (bool success) {
require(isSealed());
// implicitly claim bonus for both sender and receiver
claimBonus(msg.sender);
claimBonus(_to);
// according to VEN's total supply, never overflow here
if (accounts[msg.sender].balance >= _amount
&& _amount > 0) {
accounts[msg.sender].balance -= uint112(_amount);
accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112();
Transfer(msg.sender, _to, _amount);
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) {
require(isSealed());
// implicitly claim bonus for both sender and receiver
claimBonus(_from);
claimBonus(_to);
// according to VEN's total supply, never overflow here
if (accounts[_from].balance >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0) {
accounts[_from].balance -= uint112(_amount);
allowed[_from][msg.sender] -= _amount;
accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112();
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
//if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); }
ApprovalReceiver(_spender).receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// Mint tokens and assign to some one
function mint(address _owner, uint256 _amount, bool _isRaw, uint32 timestamp) onlyOwner{
if (_isRaw) {
accounts[_owner].rawTokens = _amount.add(accounts[_owner].rawTokens).toUINT112();
supplies.rawTokens = _amount.add(supplies.rawTokens).toUINT128();
} else {
accounts[_owner].balance = _amount.add(accounts[_owner].balance).toUINT112();
}
accounts[_owner].lastMintedTimestamp = timestamp;
supplies.total = _amount.add(supplies.total).toUINT128();
Transfer(0, _owner, _amount);
}
// Offer bonus to raw tokens holder
function offerBonus(uint256 _bonus) onlyOwner {
bonusOffered = bonusOffered.add(_bonus);
supplies.total = _bonus.add(supplies.total).toUINT128();
Transfer(0, this, _bonus);
}
// Set owner to zero address, to disable mint, and enable token transfer
function seal() onlyOwner {
setOwner(0);
}
}
contract ApprovalReceiver {
function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData);
}
// Contract to sell and distribute Nereon tokens
contract nereonSale is Owned{
/// chart of stage transition
///
/// deploy initialize startTime endTime finalize
/// | <-earlyStageLasts-> | | <- closedStageLasts -> |
/// O-----------O---------------O---------------------O-------------O------------------------O------------>
/// Created Initialized Early Normal Closed Finalized
enum Stage {
NotCreated,
Created,
Initialized,
Early,
Normal,
Closed,
Finalized
}
using SafeMath for uint256;
uint256 public constant totalSupply = (10 ** 9) * (10 ** 18); // 1 billion VEN, decimals set to 18
uint256 constant privateSupply = totalSupply * 9 / 100; // 9% for private ICO
uint256 constant commercialPlan = totalSupply * 23 / 100; // 23% for commercial plan
uint256 constant reservedForTeam = totalSupply * 5 / 100; // 5% for team
uint256 constant reservedForOperations = totalSupply * 22 / 100; // 22 for operations
// 59%
uint256 public constant nonPublicSupply = privateSupply + commercialPlan + reservedForTeam + reservedForOperations;
// 41%
uint256 public constant publicSupply = totalSupply - nonPublicSupply;
uint256 public constant officialLimit = 64371825 * (10 ** 18);
uint256 public constant channelsLimit = publicSupply - officialLimit;
// packed to 256bit
struct SoldOut {
uint16 placeholder; // placeholder to make struct pre-alloced
// amount of tokens officially sold out.
// max value of 120bit is about 1e36, it's enough for token amount
uint120 official;
uint120 channels; // amount of tokens sold out via channels
}
SoldOut soldOut;
uint256 constant nereonPerEth = 3500; // normal exchange rate
uint256 constant nereonPerEthEarlyStage = nereonPerEth + nereonPerEth * 15 / 100; // early stage has 15% reward
uint constant minBuyInterval = 30 minutes; // each account can buy once in 30 minutes
uint constant maxBuyEthAmount = 30 ether;
Nereon nereon; // Nereon token contract follows ERC20 standard
address ethVault; // the account to keep received ether
address nereonVault; // the account to keep non-public offered Nereon tokens
uint public constant startTime = 1503057600; // time to start sale
uint public constant endTime = 1504180800; // tiem to close sale
uint public constant earlyStageLasts = 3 days; // early bird stage lasts in seconds
bool initialized;
bool finalized;
function NereonSale() {
soldOut.placeholder = 1;
}
/// @notice calculte exchange rate according to current stage
/// @return exchange rate. zero if not in sale.
function exchangeRate() constant returns (uint256){
if (stage() == Stage.Early) {
return nereonPerEthEarlyStage;
}
if (stage() == Stage.Normal) {
return nereonPerEth;
}
return 0;
}
/// @notice for test purpose
function blockTime() constant returns (uint32) {
return uint32(block.timestamp);
}
/// @notice estimate stage
/// @return current stage
function stage() constant returns (Stage) {
if (finalized) {
return Stage.Finalized;
}
if (!initialized) {
// deployed but not initialized
return Stage.Created;
}
if (blockTime() < startTime) {
// not started yet
return Stage.Initialized;
}
if (uint256(soldOut.official).add(soldOut.channels) >= publicSupply) {
// all sold out
return Stage.Closed;
}
if (blockTime() < endTime) {
// in sale
if (blockTime() < startTime.add(earlyStageLasts)) {
// early bird stage
return Stage.Early;
}
// normal stage
return Stage.Normal;
}
// closed
return Stage.Closed;
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
/// @notice entry to buy tokens
function () payable {
buy();
}
/// @notice entry to buy tokens
function buy() payable {
// reject contract buyer to avoid breaking interval limit
require(!isContract(msg.sender));
require(msg.value >= 0.01 ether);
uint256 rate = exchangeRate();
// here don't need to check stage. rate is only valid when in sale
require(rate > 0);
// each account is allowed once in minBuyInterval
require(blockTime() >= nereon.lastMintedTimestamp(msg.sender) + minBuyInterval);
uint256 requested;
// and limited to maxBuyEthAmount
if (msg.value > maxBuyEthAmount) {
requested = maxBuyEthAmount.mul(rate);
} else {
requested = msg.value.mul(rate);
}
uint256 remained = officialLimit.sub(soldOut.official);
if (requested > remained) {
//exceed remained
requested = remained;
}
uint256 ethCost = requested.div(rate);
if (requested > 0) {
nereon.mint(msg.sender, requested, true, blockTime());
// transfer ETH to vault
ethVault.transfer(ethCost);
soldOut.official = requested.add(soldOut.official).toUINT120();
onSold(msg.sender, requested, ethCost);
}
uint256 toReturn = msg.value.sub(ethCost);
if(toReturn > 0) {
// return over payed ETH
msg.sender.transfer(toReturn);
}
}
/// @notice returns tokens sold officially
function officialSold() constant returns (uint256) {
return soldOut.official;
}
/// @notice returns tokens sold via channels
function channelsSold() constant returns (uint256) {
return soldOut.channels;
}
/// @notice manually offer tokens to channel
function offerToChannel(address _channelAccount, uint256 _nereonAmount) onlyOwner {
Stage stg = stage();
// since the settlement may be delayed, so it's allowed in closed stage
require(stg == Stage.Early || stg == Stage.Normal || stg == Stage.Closed);
soldOut.channels = _nereonAmount.add(soldOut.channels).toUINT120();
//should not exceed limit
require(soldOut.channels <= channelsLimit);
nereon.mint(
_channelAccount,
_nereonAmount,
true, // unsold tokens can be claimed by channels portion
blockTime()
);
onSold(_channelAccount, _nereonAmount, 0);
}
/// @notice initialize to prepare for sale
/// @param _nereon The address Nereon token contract following ERC20 standard
/// @param _ethVault The place to store received ETH
/// @param _nereonVault The place to store non-publicly supplied Nereon tokens
function initialize(
Nereon _nereon,
address _ethVault,
address _nereonVault) onlyOwner {
require(stage() == Stage.Created);
// ownership of token contract should already be this
require(_nereon.owner() == address(this));
require(address(_ethVault) != 0);
require(address(_nereonVault) != 0);
nereon = _nereon;
ethVault = _ethVault;
nereonVault = _nereonVault;
nereon.mint(
nereonVault,
reservedForTeam.add(reservedForOperations),
false, // team and operations reserved portion can't share unsold tokens
blockTime()
);
nereon.mint(
nereonVault,
privateSupply.add(commercialPlan),
true, // private ICO and commercial plan can share unsold tokens
blockTime()
);
initialized = true;
onInitialized();
}
/// @notice finalize
function finalize() onlyOwner {
// only after closed stage
require(stage() == Stage.Closed);
uint256 unsold = publicSupply.sub(soldOut.official).sub(soldOut.channels);
if (unsold > 0) {
// unsold Nereon as bonus
nereon.offerBonus(unsold);
}
nereon.seal();
finalized = true;
onFinalized();
}
event onInitialized();
event onFinalized();
event onSold(address indexed buyer, uint256 nereonAmount, uint256 ethCost);
} | estimate stage return current stage deployed but not initialized not started yet all sold out in sale early bird stage | function stage() constant returns (Stage) {
if (finalized) {
return Stage.Finalized;
}
if (!initialized) {
return Stage.Created;
}
if (blockTime() < startTime) {
return Stage.Initialized;
}
if (uint256(soldOut.official).add(soldOut.channels) >= publicSupply) {
return Stage.Closed;
}
if (blockTime() < endTime) {
if (blockTime() < startTime.add(earlyStageLasts)) {
return Stage.Early;
}
}
}
| 2,089,930 |
./full_match/1/0x0000000000F7A60F1C88F317f369e3D8679C6689/sources/contracts/tokens/ERC721/ERC721.sol | Returns the total amount of tokens minted in the contract./ | function _totalMinted() internal view virtual returns (uint256) {
return _mintCounter;
}
| 17,130,791 |
./full_match/1/0x39159BE9E506d73b776c063D117B8367aA1139e9/sources/contracts/SamuraiJack.sol | Excludes the specified account from tax./ | function exclude(address account) public onlyOwner {
require(!isExcluded(account), "ERC20: Account is already excluded");
excludeList[account] = true;
}
| 2,998,985 |
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
mapping(address => uint256) public balances;
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Freezing tokens
*/
contract Freezing is Ownable, ERC20Basic {
using SafeMath for uint256;
address tokenManager;
bool freezingActive = true;
event Freeze(address _holder, uint256 _amount);
event Unfreeze(address _holder, uint256 _amount);
// all freezing sum for every holder
mapping(address => uint256) public freezeBalances;
modifier onlyTokenManager() {
assert(msg.sender == tokenManager);
_;
}
/**
* @dev Check freezing balance
*/
modifier checkFreezing(address _holder, uint _value) {
if (freezingActive) {
require(balances[_holder].sub(_value) >= freezeBalances[_holder]);
}
_;
}
function setTokenManager(address _newManager) onlyOwner public {
tokenManager = _newManager;
}
/**
* @dev Enable freezing for contract
*/
function onFreezing() onlyTokenManager public {
freezingActive = true;
}
/**
* @dev Disable freezing for contract
*/
function offFreezing() onlyTokenManager public {
freezingActive = false;
}
function Freezing() public {
tokenManager = owner;
}
/**
* @dev Returns freezing balance of _holder
*/
function freezingBalanceOf(address _holder) public view returns (uint256) {
return freezeBalances[_holder];
}
/**
* @dev Freeze amount for user
*/
function freeze(address _holder, uint _amount) public onlyTokenManager {
assert(balances[_holder].sub(_amount.add(freezeBalances[_holder])) >= 0);
freezeBalances[_holder] = freezeBalances[_holder].add(_amount);
emit Freeze(_holder, _amount);
}
/**
* @dev Unfreeze amount for user
*/
function unfreeze(address _holder, uint _amount) public onlyTokenManager {
assert(freezeBalances[_holder].sub(_amount) >= 0);
freezeBalances[_holder] = freezeBalances[_holder].sub(_amount);
emit Unfreeze(_holder, _amount);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Roles of users
*/
contract VerificationStatus {
enum Statuses {None, Self, Video, Agent, Service}
Statuses constant defaultStatus = Statuses.None;
event StatusChange(bytes32 _property, address _user, Statuses _status, address _caller);
}
/**
* @title Roles of users
*
* @dev User roles for KYC Contract
*/
contract Roles is Ownable {
// 0, 1, 2
enum RoleItems {Person, Agent, Administrator}
RoleItems constant defaultRole = RoleItems.Person;
mapping (address => RoleItems) private roleList;
/**
* @dev Event for every change of role
*/
event RoleChange(address _user, RoleItems _role, address _caller);
/**
* @dev for agent function
*/
modifier onlyAgent() {
assert(roleList[msg.sender] == RoleItems.Agent);
_;
}
/**
* @dev for administrator function
*/
modifier onlyAdministrator() {
assert(roleList[msg.sender] == RoleItems.Administrator || msg.sender == owner);
_;
}
/**
* @dev Save role for user
*/
function _setRole(address _user, RoleItems _role) internal {
emit RoleChange(_user, _role, msg.sender);
roleList[_user] = _role;
}
/**
* @dev reset role
*/
function resetRole(address _user) onlyAdministrator public {
_setRole(_user, RoleItems.Person);
}
/**
* @dev Appointing agent by administrator or owner
*/
function appointAgent(address _user) onlyAdministrator public {
_setRole(_user, RoleItems.Agent);
}
/**
* @dev Appointing administrator by owner
*/
function appointAdministrator(address _user) onlyOwner public returns (bool) {
_setRole(_user, RoleItems.Administrator);
return true;
}
function getRole(address _user) public view returns (RoleItems) {
return roleList[_user];
}
}
/**
* @title Storage for users data
*/
contract PropertyStorage is Roles, VerificationStatus {
struct Property {
Statuses status;
bool exist;
uint16 code;
}
mapping(address => mapping(bytes32 => Property)) private propertyStorage;
// agent => property => status
mapping(address => mapping(bytes32 => bool)) agentSign;
event NewProperty(bytes32 _property, address _user, address _caller);
modifier propertyExist(bytes32 _property, address _user) {
assert(propertyStorage[_user][_property].exist);
_;
}
/**
* @dev Compute hash for property before write into storage
*
* @param _name Name of property (such as full_name, birthday, address etc.)
* @param _data Value of property
*/
function computePropertyHash(string _name, string _data) pure public returns (bytes32) {
return sha256(_name, _data);
}
function _addPropertyValue(bytes32 _property, address _user) internal {
propertyStorage[_user][_property] = Property(
Statuses.None,
true,
0
);
emit NewProperty(_property, _user, msg.sender);
}
/**
* @dev Add data for any user by administrator
*/
function addPropertyForUser(bytes32 _property, address _user) public onlyAdministrator returns (bool) {
_addPropertyValue(_property, _user);
return true;
}
/**
* @dev Add property for sender
*/
function addProperty(bytes32 _property) public returns (bool) {
_addPropertyValue(_property, msg.sender);
return true;
}
/**
* @dev Returns status of user data (may be self 1, video 2, agent 3 or Service 4)
* @dev If verification is empty then it returns 0 (None)
*/
function getPropertyStatus(bytes32 _property, address _user) public view propertyExist(_property, _user) returns (Statuses) {
return propertyStorage[_user][_property].status;
}
/**
* @dev when user upload documents administrator will call this function
*/
function setPropertyStatus(bytes32 _property, address _user, Statuses _status) public onlyAdministrator returns (bool){
_setPropertyStatus(_property, _user, _status);
return true;
}
/**
* @dev Agent sign on user data by agent
*/
function setAgentVerificationByAgent(bytes32 _property, address _user) public onlyAgent {
_setPropertyStatus(_property, _user, Statuses.Agent);
_signPropertyByAgent(msg.sender, _user, _property);
}
/**
* @dev Agent sign on user data by Admin
*/
function setAgentVerificationByAdmin(address _agent, address _user, bytes32 _property) public onlyOwner {
_setPropertyStatus(_property, _user, Statuses.Agent);
_signPropertyByAgent(_agent, _user, _property);
}
/**
* @dev Set verification status for user data
*/
function _setPropertyStatus(bytes32 _property, address _user, Statuses _status) internal propertyExist(_property, _user) {
propertyStorage[_user][_property].status = _status;
emit StatusChange(_property, _user, _status, msg.sender);
}
/**
* @dev Agent sign on user data
*/
function _signPropertyByAgent(address _agent, address _user, bytes32 _property) internal {
bytes32 _hash = _getHash(_user, _property);
agentSign[_agent][_hash] = true;
}
/**
* @dev To make sure that the agent has signed the user property
*/
function checkAgentSign(address _agent, address _user, bytes32 _property) public view returns (bool) {
bytes32 _hash = _getHash(_user, _property);
return agentSign[_agent][_hash];
}
/**
* @dev Get hash sum for property
*/
function _getHash(address _user, bytes32 _property) public pure returns (bytes32) {
return sha256(_user, _property);
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract ERC20BasicToken is ERC20Basic, Freezing {
using SafeMath for uint256;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) checkFreezing(msg.sender, _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @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 KYCToken is ERC20BasicToken, ERC20, PropertyStorage {
mapping(address => mapping(address => uint256)) internal allowed;
uint256 public totalSupply = 42000000000000000000000000;
string public name = "KYC.Legal token";
uint8 public decimals = 18;
string public symbol = "KYC";
function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
function KYCToken() public {
balances[msg.sender] = totalSupply;
}
/**
* @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) checkFreezing(_from, _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256) {
return allowed[_owner][_spender];
}
} | Agent sign on user data by agent/ | function setAgentVerificationByAgent(bytes32 _property, address _user) public onlyAgent {
_setPropertyStatus(_property, _user, Statuses.Agent);
_signPropertyByAgent(msg.sender, _user, _property);
}
| 6,111,697 |
./full_match/1/0x402993515350c973f1D44FC8762644E3806cB9bC/sources/contracts/data/Keys.sol | key for amount of tokens in a market's pool market the market to check token the token to check return key for amount of tokens in a market's pool | function poolAmountKey(address market, address token) internal pure returns (bytes32) {
return keccak256(abi.encode(
POOL_AMOUNT,
market,
token
));
}
| 16,543,142 |
./partial_match/1/0x947a2e766F5e7A6002F02c08eAbE6f236Cc41C9B/sources/QuantumCreatures.sol | Approve `to` to operate on `tokenId` Emits a {Approval} event./ | function _approve(
address to,
uint256 tokenId,
address owner
) internal {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
| 3,903,040 |
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
import "../contracts/IToken.sol";
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/MatryxPlatform.sol";
import "../contracts/LibPlatform.sol";
import "../contracts/LibTournament.sol";
contract TestLibTournament2 {
MatryxPlatform.Info info;
MatryxPlatform.Data data;
bool transferHappened;
uint256 transferAmount;
function transfer(address to, uint256 value) public returns (bool)
{
transferHappened = true;
transferAmount = value;
return transferHappened;
}
function transferFrom(address from, address to, uint256 value) public view returns (bool)
{
return true;
}
function allowance(address owner, address spender) public returns (uint256)
{
return 1 ether;
}
function testCreateRound() public
{
data.tournamentBalance[address(this)] = 100;
LibTournament.RoundDetails memory rDetails;
rDetails.start = 0;
rDetails.duration = 100;
rDetails.review = 100;
rDetails.bounty = 50;
LibTournament.createRound(address(this), address(this), info, data, rDetails);
Assert.equal(data.tournaments[address(this)].rounds.length, 1, "Should be one round");
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
Assert.equal(roundZero.details.start, now, "Start should be now.");
Assert.equal(roundZero.details.duration, 100, "Round duration should be 100.");
Assert.equal(roundZero.details.review, 100, "Round review should be 100.");
Assert.equal(roundZero.details.bounty, 50, "Round bounty should be 50.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
}
function testCreateSubmission() public
{
// sender can use matryx
data.whitelist[msg.sender] = true;
// tournament entry fee paid
data.tournaments[address(this)].entryFeePaid[msg.sender].exists = true;
// commit has owner
bytes32 commitHash = keccak256("commit");
data.commits[commitHash].owner = msg.sender;
// current round is Open
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 1;
roundZero.details.duration = 61;
roundZero.details.bounty = 10;
LibTournament.createSubmission(address(this), msg.sender, info, data, "QmSubmissionStuff", commitHash);
bytes32 submissionHash = keccak256(abi.encodePacked(address(this), commitHash, uint256(0)));
Assert.equal(data.commitToSubmissions[commitHash][0], submissionHash, "Commit hash should be linked to submission hash.");
Assert.equal(roundZero.info.submissions[0], submissionHash, "Submission should be in round's submissions array.");
Assert.isTrue(roundZero.hasSubmitted[msg.sender], "hasSubmitted flag should be true for sender.");
Assert.equal(roundZero.info.submitterCount, 1, "Round should have 1 submitter.");
delete data.whitelist[msg.sender];
delete data.tournaments[address(this)].entryFeePaid[msg.sender];
delete data.tournaments[address(this)];
delete data.submissions[submissionHash];
delete data.commitToSubmissions[commitHash];
delete data.commits[commitHash];
}
function testUpdateDetails() public
{
data.tournaments[address(this)].info.owner = msg.sender;
LibTournament.TournamentDetails memory tDetails;
tDetails.content = "QmTournamentDetails";
tDetails.entryFee = 10;
LibTournament.updateDetails(address(this), msg.sender, data, tDetails);
Assert.equal(data.tournaments[address(this)].details.content, tDetails.content, "Tournament content incorrect.");
Assert.equal(data.tournaments[address(this)].details.entryFee, tDetails.entryFee, "Tournament entryFee incorrect.");
delete data.tournaments[address(this)];
}
function testAddToBounty() public
{
// set token
info.token = address(this);
// current round is Open
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 1;
roundZero.details.duration = 61;
roundZero.details.bounty = 10;
// total balance is 10
data.totalBalance = 10;
// tournamentBalance is 10
data.tournamentBalance[address(this)] = 10;
data.tournaments[address(this)].details.bounty = 10;
LibTournament.addToBounty(address(this), msg.sender, info, data, 10);
Assert.equal(data.totalBalance, 20, "Total platform balance should be 20.");
Assert.equal(data.tournamentBalance[address(this)], 20, "Tournament balance should be 20.");
Assert.equal(data.tournaments[address(this)].details.bounty, 20, "Tournament bounty should be 20.");
delete info.token;
delete data.tournaments[address(this)];
delete data.totalBalance;
delete data.tournamentBalance[address(this)];
}
function testTransferToRound() public
{
// Must be owner
data.tournaments[address(this)].info.owner = msg.sender;
// current round is Open
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 1;
roundZero.details.duration = 61;
roundZero.details.bounty = 10;
// total balance is 10
data.totalBalance = 20;
data.tournamentBalance[address(this)] = 20;
LibTournament.transferToRound(address(this), msg.sender, data, 10);
Assert.equal(roundZero.details.bounty, 20, "Round bounty should be 20.");
delete data.tournaments[address(this)];
delete data.totalBalance;
delete data.tournamentBalance[address(this)];
}
function testSelectWinnersDoNothing() public
{
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// create wData
bytes32 winner = keccak256("winner");
bytes32 commitHash = keccak256("commit");
LibTournament.WinnersData memory wData;
bytes32[] memory subs = new bytes32[](1);
subs[0] = winner;
uint256[] memory dist = new uint256[](1);
dist[0] = 1;
wData.submissions = subs;
wData.distribution = dist;
// create rDetails
LibTournament.RoundDetails memory rDetails;
// current round is in review
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
roundZero.info.submissions.length = 1;
roundZero.info.submissions[0] = winner;
// submission must exist on platform
data.submissions[winner].tournament = address(this);
data.submissions[winner].commitHash = commitHash;
LibTournament.selectWinners(address(this), msg.sender, info, data, wData, rDetails);
Assert.equal(roundZero.info.winners.submissions[0], winner, "First round winner incorrect.");
Assert.equal(data.submissions[winner].reward, 10, "Full bounty not awarded to sole round winner.");
Assert.equal(data.commitBalance[commitHash], 10, "Full bounty not allocated to sole round winner's commit.");
Assert.equal(data.tournamentBalance[address(this)], 10, "Tournament balance should have decreased to 10.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
delete data.submissions[winner];
delete data.commitBalance[commitHash];
}
function testSelectWinnersStartNextRound() public
{
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// create wData
bytes32 winner = keccak256("winner");
bytes32 commitHash = keccak256("commit");
LibTournament.WinnersData memory wData;
bytes32[] memory subs = new bytes32[](1);
subs[0] = winner;
uint256[] memory dist = new uint256[](1);
dist[0] = 1;
wData.submissions = subs;
wData.distribution = dist;
wData.action = 1;
// create rDetails
LibTournament.RoundDetails memory rDetails;
rDetails.duration = 60;
rDetails.bounty = 10;
// current round is in review
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
roundZero.info.submissions.length = 1;
roundZero.info.submissions[0] = winner;
// submission must exist on platform
data.submissions[winner].tournament = address(this);
data.submissions[winner].commitHash = commitHash;
LibTournament.selectWinners(address(this), msg.sender, info, data, wData, rDetails);
Assert.equal(roundZero.info.winners.submissions[0], winner, "First round winner incorrect.");
Assert.equal(data.submissions[winner].reward, 10, "Full bounty not awarded to sole round winner.");
Assert.equal(data.commitBalance[commitHash], 10, "Full bounty not allocated to sole round winner's commit.");
Assert.equal(data.tournamentBalance[address(this)], 10, "Tournament balance should have decreased to 10.");
Assert.isTrue(roundZero.info.closed, "Old round is closed");
Assert.equal(data.tournaments[address(this)].rounds[1].details.duration, 60, "New round duration is incorrect.");
Assert.equal(data.tournaments[address(this)].rounds[1].details.bounty, 10, "New round bounty is incorrect.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
delete data.submissions[winner];
delete data.commitBalance[commitHash];
}
function testSelectWinnersCloseTournament() public
{
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// create wData
bytes32 winner = keccak256("winner");
bytes32 commitHash = keccak256("commit");
LibTournament.WinnersData memory wData;
bytes32[] memory subs = new bytes32[](1);
subs[0] = winner;
uint256[] memory dist = new uint256[](1);
dist[0] = 1;
wData.submissions = subs;
wData.distribution = dist;
wData.action = 2;
// create rDetails
LibTournament.RoundDetails memory rDetails;
rDetails.duration = 60;
rDetails.bounty = 10;
// current round is InReview
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
roundZero.info.submissions.length = 1;
roundZero.info.submissions[0] = winner;
// submission must exist on platform
data.submissions[winner].tournament = address(this);
data.submissions[winner].commitHash = commitHash;
Assert.equal(data.submissions[winner].reward, 0, "Reward for submission should be 0 initially.");
LibTournament.selectWinners(address(this), msg.sender, info, data, wData, rDetails);
Assert.equal(roundZero.info.winners.submissions[0], winner, "First round winner incorrect.");
Assert.equal(data.submissions[winner].reward, 20, "Full bounty not awarded to sole round winner.");
Assert.equal(data.commitBalance[commitHash], 20, "Full bounty not allocated to sole round winner's commit.");
Assert.equal(data.tournamentBalance[address(this)], 0, "Tournament balance should have been depleted.");
Assert.isTrue(roundZero.info.closed, "Old round is closed");
Assert.equal(roundZero.details.bounty, 20, "Last round bounty not remaining tournament balance.");
Assert.equal(data.tournaments[address(this)].rounds.length, 1, "Total number of rounds incorrect.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
delete data.submissions[winner];
delete data.commitBalance[commitHash];
}
function testUpdateNextRound() public
{
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// round not yet open
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now + 60;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
LibTournament.RoundDetails memory rDetails;
rDetails.start = now;
rDetails.duration = 40;
rDetails.review = 30;
rDetails.bounty = 20;
LibTournament.updateNextRound(address(this), msg.sender, data, rDetails);
Assert.equal(roundZero.details.start, now, "Round should be starting now.");
Assert.equal(roundZero.details.duration, 40, "Round duration should be 40.");
Assert.equal(roundZero.details.review, 30, "Round review should be 30.");
Assert.equal(roundZero.details.bounty, 20, "Round bounty should be 20.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
}
function testStartNextRound() public
{
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// round setup, first HasWinners, second is OnHold
data.tournaments[address(this)].rounds.length = 2;
bytes32 sHash = keccak256(abi.encodePacked("submission"));
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
roundZero.info.submissions.push(sHash);
roundZero.info.winners.submissions.push(sHash);
data.tournaments[address(this)].rounds[1].details.start = now + 60;
data.tournaments[address(this)].rounds[1].details.duration = 1000;
LibTournament.startNextRound(address(this), msg.sender, data);
Assert.isTrue(roundZero.info.closed, "Round 0 should be closed.");
Assert.equal(data.tournaments[address(this)].rounds[1].details.start, now, "Round 1 should start now.");
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
}
function testWithdrawFromAbandoned() public
{
// set token
info.token = address(this);
// set total balance
data.totalBalance = 20;
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// current round is Abandoned
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
// sender and someone else have submitted to round
roundZero.hasSubmitted[msg.sender] = true;
roundZero.hasSubmitted[address(uint256(msg.sender) + 1)] = true;
roundZero.info.submitterCount = 2;
// sender must be entrant to exit
data.tournaments[address(this)].entryFeePaid[msg.sender].exists = true;
LibTournament.withdrawFromAbandoned(address(this), msg.sender, info, data);
Assert.isTrue(roundZero.info.closed, "Round should have closed.");
Assert.isTrue(data.tournaments[address(this)].hasWithdrawn[msg.sender], "Sender should have withdrawn.");
Assert.equal(data.tournaments[address(this)].numWithdrawn, 1, "Number of users who've withdrawn should be 1.");
Assert.equal(data.totalBalance, 10, "Total balance should have been 10.");
Assert.equal(data.tournamentBalance[address(this)], 10, "Tournament balance should have been 10.");
Assert.isTrue(transferHappened, "Transfer should have happened.");
Assert.equal(transferAmount, 10, "Transfer amount should have been 10.");
delete info.token;
delete data.totalBalance;
delete data.tournamentBalance[address(this)];
delete roundZero.hasSubmitted[msg.sender];
delete roundZero.hasSubmitted[address(uint256(msg.sender) + 1)];
delete data.tournaments[address(this)].entryFeePaid[msg.sender];
delete data.tournaments[address(this)];
delete transferHappened;
delete transferAmount;
}
function testCloseTournament() public
{
// set total balance
data.totalBalance = 20;
// set tournament balance
data.tournamentBalance[address(this)] = 10;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// create wData
bytes32 winner = keccak256("winner");
bytes32 commitHash = keccak256("commit");
LibTournament.WinnersData memory wData;
bytes32[] memory subs = new bytes32[](1);
subs[0] = winner;
uint256[] memory dist = new uint256[](1);
dist[0] = 1;
wData.submissions = subs;
wData.distribution = dist;
// round setup: first HasWinners, second is ghost
data.tournaments[address(this)].rounds.length = 2;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
roundZero.details.bounty = 10;
roundZero.info.winners = wData;
roundZero.info.submissions.push(winner);
LibTournament.RoundData storage roundOne = data.tournaments[address(this)].rounds[1];
roundOne.details.start = roundZero.details.start + roundZero.details.duration + roundZero.details.review;
// submission setup
data.submissions[winner].tournament = address(this);
data.submissions[winner].commitHash = commitHash;
data.submissions[winner].reward = 10;
data.commitBalance[commitHash] = 10;
LibTournament.closeTournament(address(this), msg.sender, data);
Assert.equal(data.commitBalance[commitHash], 20, "Commit balance should be 20.");
Assert.equal(data.submissions[winner].reward, 20, "Submission reward should be 20.");
Assert.equal(data.tournamentBalance[address(this)], 0, "Tournament balance should be 0.");
Assert.equal(data.tournaments[address(this)].rounds.length, 1, "Ghost round should be gone.");
delete data.totalBalance;
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
delete data.submissions[winner];
delete data.commitBalance[commitHash];
}
function testRecoverBounty() public
{
// set token
info.token = address(this);
// set total balance
data.totalBalance = 20;
// set tournament balance
data.tournamentBalance[address(this)] = 20;
// set tournament owner
data.tournaments[address(this)].info.owner = msg.sender;
// current round Abandoned
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
LibTournament.recoverBounty(address(this), msg.sender, info, data);
Assert.isTrue(roundZero.info.closed, "Round should have closed.");
Assert.equal(data.tournaments[address(this)].numWithdrawn, 1, "Number of users who've withdrawn should be 1.");
Assert.isZero(data.totalBalance, "Total balance should be 0.");
Assert.isZero(data.tournamentBalance[address(this)], "Tournament balance should be 0.");
Assert.isTrue(transferHappened, "Token transfer should have happen.");
Assert.equal(transferAmount, 20, "Transfer amount should be 20.");
delete info.token;
delete data.totalBalance;
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
}
} | set token set total balance set tournament balance set tournament owner current round Abandoned | function testRecoverBounty() public
{
info.token = address(this);
data.totalBalance = 20;
data.tournamentBalance[address(this)] = 20;
data.tournaments[address(this)].info.owner = msg.sender;
data.tournaments[address(this)].rounds.length = 1;
LibTournament.RoundData storage roundZero = data.tournaments[address(this)].rounds[0];
roundZero.details.start = now - 61;
roundZero.details.duration = 60;
roundZero.details.review = 60;
LibTournament.recoverBounty(address(this), msg.sender, info, data);
Assert.isTrue(roundZero.info.closed, "Round should have closed.");
Assert.equal(data.tournaments[address(this)].numWithdrawn, 1, "Number of users who've withdrawn should be 1.");
Assert.isZero(data.totalBalance, "Total balance should be 0.");
Assert.isZero(data.tournamentBalance[address(this)], "Tournament balance should be 0.");
Assert.isTrue(transferHappened, "Token transfer should have happen.");
Assert.equal(transferAmount, 20, "Transfer amount should be 20.");
delete info.token;
delete data.totalBalance;
delete data.tournamentBalance[address(this)];
delete data.tournaments[address(this)];
}
| 12,733,571 |
pragma solidity ^0.4.24;
// File: @0xcert/ethereum-utils/contracts/math/SafeMath.sol
/**
* @dev Math operations with safety checks that throw on error. This contract is based
* on the source code at https://goo.gl/iyQsmU.
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
* @param _a Factor number.
* @param _b Factor number.
*/
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.
* @param _a Dividend number.
* @param _b Divisor number.
*/
function div(
uint256 _a,
uint256 _b
)
internal
pure
returns (uint256)
{
uint256 c = _a / _b;
// assert(b > 0); // Solidity automatically throws when dividing by 0
// 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).
* @param _a Minuend number.
* @param _b Subtrahend number.
*/
function sub(
uint256 _a,
uint256 _b
)
internal
pure
returns (uint256)
{
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
* @param _a Number.
* @param _b Number.
*/
function add(
uint256 _a,
uint256 _b
)
internal
pure
returns (uint256)
{
uint256 c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: @0xcert/ethereum-erc721/contracts/tokens/ERC721Enumerable.sol
/**
* @dev Optional enumeration extension for ERC-721 non-fungible token standard.
* See https://goo.gl/pc9yoS.
*/
interface ERC721Enumerable {
/**
* @dev Returns a count of valid NFTs tracked by this contract, where each one of them has an
* assigned and queryable owner not equal to the zero address.
*/
function totalSupply()
external
view
returns (uint256);
/**
* @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified.
* @param _index A counter less than `totalSupply()`.
*/
function tokenByIndex(
uint256 _index
)
external
view
returns (uint256);
/**
* @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is
* not specified. It throws if `_index` >= `balanceOf(_owner)` or if `_owner` is the zero address,
* representing invalid NFTs.
* @param _owner An address where we are interested in NFTs owned by them.
* @param _index A counter less than `balanceOf(_owner)`.
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
external
view
returns (uint256);
}
// File: @0xcert/ethereum-erc721/contracts/tokens/ERC721.sol
/**
* @dev ERC-721 non-fungible token standard. See https://goo.gl/pc9yoS.
*/
interface ERC721 {
/**
* @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are
* created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any
* number of NFTs may be created and assigned without emitting Transfer. At the time of any
* transfer, the approved address for that NFT (if any) is reset to none.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
/**
* @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero
* address indicates there is no approved address. When a Transfer event emits, this also
* indicates that the approved address for that NFT (if any) is reset to none.
*/
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
/**
* @dev This emits when an operator is enabled or disabled for an owner. The operator can manage
* all NFTs of the owner.
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
*/
function balanceOf(
address _owner
)
external
view
returns (uint256);
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered
* invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
*/
function ownerOf(
uint256 _tokenId
)
external
view
returns (address);
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received`
* on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
external;
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to ""
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/**
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT.
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they mayb be permanently lost.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/**
* @dev Set or reaffirm the approved address for an NFT.
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved The new approved NFT controller.
* @param _tokenId The NFT to approve.
*/
function approve(
address _approved,
uint256 _tokenId
)
external;
/**
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @notice The contract MUST allow multiple operators per owner.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(
address _operator,
bool _approved
)
external;
/**
* @dev Get the approved address for a single NFT.
* @notice Throws if `_tokenId` is not a valid NFT.
* @param _tokenId The NFT to find the approved address for.
*/
function getApproved(
uint256 _tokenId
)
external
view
returns (address);
/**
* @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (bool);
}
// File: @0xcert/ethereum-erc721/contracts/tokens/ERC721TokenReceiver.sol
/**
* @dev ERC-721 interface for accepting safe transfers. See https://goo.gl/pc9yoS.
*/
interface ERC721TokenReceiver {
/**
* @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the
* recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return
* of other than the magic value MUST result in the transaction being reverted.
* Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing.
* @notice The contract address is always the message sender. A wallet/broker/auction application
* MUST implement the wallet interface if it will accept safe transfers.
* @param _operator The address which called `safeTransferFrom` function.
* @param _from The address which previously owned the token.
* @param _tokenId The NFT identifier which is being transferred.
* @param _data Additional data with no specified format.
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
external
returns(bytes4);
}
// File: @0xcert/ethereum-utils/contracts/utils/AddressUtils.sol
/**
* @dev Utility library of inline functions on addresses.
*/
library AddressUtils {
/**
* @dev Returns whether the target address is a contract.
* @param _addr Address to check.
*/
function isContract(
address _addr
)
internal
view
returns (bool)
{
uint256 size;
/**
* XXX Currently there is no better way to check if there is a contract in an address than to
* check the size of the code at that address.
* See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works.
* TODO: Check this again before the Serenity release, because all addresses will be
* contracts then.
*/
assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
// File: @0xcert/ethereum-utils/contracts/utils/ERC165.sol
/**
* @dev A standard for detecting smart contract interfaces. See https://goo.gl/cxQCse.
*/
interface ERC165 {
/**
* @dev Checks if the smart contract includes a specific interface.
* @notice This function uses less than 30,000 gas.
* @param _interfaceID The interface identifier, as specified in ERC-165.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool);
}
// File: @0xcert/ethereum-utils/contracts/utils/SupportsInterface.sol
/**
* @dev Implementation of standard for detect smart contract interfaces.
*/
contract SupportsInterface is ERC165 {
/**
* @dev Mapping of supported intefraces.
* @notice You must not set element 0xffffffff to true.
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev Contract constructor.
*/
constructor()
public
{
supportedInterfaces[0x01ffc9a7] = true; // ERC165
}
/**
* @dev Function to check which interfaces are suported by this contract.
* @param _interfaceID Id of the interface.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceID];
}
}
// File: @0xcert/ethereum-erc721/contracts/tokens/NFToken.sol
/**
* @dev Implementation of ERC-721 non-fungible token standard.
*/
contract NFToken is
ERC721,
SupportsInterface
{
using SafeMath for uint256;
using AddressUtils for address;
/**
* @dev A mapping from NFT ID to the address that owns it.
*/
mapping (uint256 => address) internal idToOwner;
/**
* @dev Mapping from NFT ID to approved address.
*/
mapping (uint256 => address) internal idToApprovals;
/**
* @dev Mapping from owner address to count of his tokens.
*/
mapping (address => uint256) internal ownerToNFTokenCount;
/**
* @dev Mapping from owner address to mapping of operator addresses.
*/
mapping (address => mapping (address => bool)) internal ownerToOperators;
/**
* @dev Magic value of a smart contract that can recieve NFT.
* Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")).
*/
bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
/**
* @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are
* created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any
* number of NFTs may be created and assigned without emitting Transfer. At the time of any
* transfer, the approved address for that NFT (if any) is reset to none.
* @param _from Sender of NFT (if address is zero address it indicates token creation).
* @param _to Receiver of NFT (if address is zero address it indicates token destruction).
* @param _tokenId The NFT that got transfered.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
/**
* @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero
* address indicates there is no approved address. When a Transfer event emits, this also
* indicates that the approved address for that NFT (if any) is reset to none.
* @param _owner Owner of NFT.
* @param _approved Address that we are approving.
* @param _tokenId NFT which we are approving.
*/
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
/**
* @dev This emits when an operator is enabled or disabled for an owner. The operator can manage
* all NFTs of the owner.
* @param _owner Owner of NFT.
* @param _operator Address to which we are setting operator rights.
* @param _approved Status of operator rights(true if operator rights are given and false if
* revoked).
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
* @dev Guarantees that the msg.sender is an owner or operator of the given NFT.
* @param _tokenId ID of the NFT to validate.
*/
modifier canOperate(
uint256 _tokenId
) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender]);
_;
}
/**
* @dev Guarantees that the msg.sender is allowed to transfer NFT.
* @param _tokenId ID of the NFT to transfer.
*/
modifier canTransfer(
uint256 _tokenId
) {
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner == msg.sender
|| getApproved(_tokenId) == msg.sender
|| ownerToOperators[tokenOwner][msg.sender]
);
_;
}
/**
* @dev Guarantees that _tokenId is a valid Token.
* @param _tokenId ID of the NFT to validate.
*/
modifier validNFToken(
uint256 _tokenId
) {
require(idToOwner[_tokenId] != address(0));
_;
}
/**
* @dev Contract constructor.
*/
constructor()
public
{
supportedInterfaces[0x80ac58cd] = true; // ERC721
}
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
*/
function balanceOf(
address _owner
)
external
view
returns (uint256)
{
require(_owner != address(0));
return ownerToNFTokenCount[_owner];
}
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered
* invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
*/
function ownerOf(
uint256 _tokenId
)
external
view
returns (address _owner)
{
_owner = idToOwner[_tokenId];
require(_owner != address(0));
}
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received`
* on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
external
{
_safeTransferFrom(_from, _to, _tokenId, _data);
}
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to ""
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
_safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT.
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they maybe be permanently lost.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
_transfer(_to, _tokenId);
}
/**
* @dev Set or reaffirm the approved address for an NFT.
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved Address to be approved for the given NFT ID.
* @param _tokenId ID of the token to be approved.
*/
function approve(
address _approved,
uint256 _tokenId
)
external
canOperate(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner);
idToApprovals[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
/**
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @notice This works even if sender doesn't own any tokens at the time.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(
address _operator,
bool _approved
)
external
{
require(_operator != address(0));
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Get the approved address for a single NFT.
* @notice Throws if `_tokenId` is not a valid NFT.
* @param _tokenId ID of the NFT to query the approval of.
*/
function getApproved(
uint256 _tokenId
)
public
view
validNFToken(_tokenId)
returns (address)
{
return idToApprovals[_tokenId];
}
/**
* @dev Checks if `_operator` is an approved operator for `_owner`.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (bool)
{
require(_owner != address(0));
require(_operator != address(0));
return ownerToOperators[_owner][_operator];
}
/**
* @dev Actually perform the safeTransferFrom.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function _safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
_transfer(_to, _tokenId);
if (_to.isContract()) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED);
}
}
/**
* @dev Actually preforms the transfer.
* @notice Does NO checks.
* @param _to Address of a new owner.
* @param _tokenId The NFT that is being transferred.
*/
function _transfer(
address _to,
uint256 _tokenId
)
private
{
address from = idToOwner[_tokenId];
clearApproval(_tokenId);
removeNFToken(from, _tokenId);
addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
/**
* @dev Mints a new NFT.
* @notice This is a private function which should be called from user-implemented external
* mint function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _to The address that will own the minted NFT.
* @param _tokenId of the NFT to be minted by the msg.sender.
*/
function _mint(
address _to,
uint256 _tokenId
)
internal
{
require(_to != address(0));
require(_tokenId != 0);
require(idToOwner[_tokenId] == address(0));
addNFToken(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Burns a NFT.
* @notice This is a private function which should be called from user-implemented external
* burn function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _owner Address of the NFT owner.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn(
address _owner,
uint256 _tokenId
)
validNFToken(_tokenId)
internal
{
clearApproval(_tokenId);
removeNFToken(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Clears the current approval of a given NFT ID.
* @param _tokenId ID of the NFT to be transferred.
*/
function clearApproval(
uint256 _tokenId
)
private
{
if(idToApprovals[_tokenId] != 0)
{
delete idToApprovals[_tokenId];
}
}
/**
* @dev Removes a NFT from owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _from Address from wich we want to remove the NFT.
* @param _tokenId Which NFT we want to remove.
*/
function removeNFToken(
address _from,
uint256 _tokenId
)
internal
{
require(idToOwner[_tokenId] == _from);
assert(ownerToNFTokenCount[_from] > 0);
ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from].sub(1);
delete idToOwner[_tokenId];
}
/**
* @dev Assignes a new NFT to owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _to Address to wich we want to add the NFT.
* @param _tokenId Which NFT we want to add.
*/
function addNFToken(
address _to,
uint256 _tokenId
)
internal
{
require(idToOwner[_tokenId] == address(0));
idToOwner[_tokenId] = _to;
ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].add(1);
}
}
// File: @0xcert/ethereum-erc721/contracts/tokens/NFTokenEnumerable.sol
/**
* @dev Optional enumeration implementation for ERC-721 non-fungible token standard.
*/
contract NFTokenEnumerable is
NFToken,
ERC721Enumerable
{
/**
* @dev Array of all NFT IDs.
*/
uint256[] internal tokens;
/**
* @dev Mapping from token ID its index in global tokens array.
*/
mapping(uint256 => uint256) internal idToIndex;
/**
* @dev Mapping from owner to list of owned NFT IDs.
*/
mapping(address => uint256[]) internal ownerToIds;
/**
* @dev Mapping from NFT ID to its index in the owner tokens list.
*/
mapping(uint256 => uint256) internal idToOwnerIndex;
/**
* @dev Contract constructor.
*/
constructor()
public
{
supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable
}
/**
* @dev Mints a new NFT.
* @notice This is a private function which should be called from user-implemented external
* mint function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _to The address that will own the minted NFT.
* @param _tokenId of the NFT to be minted by the msg.sender.
*/
function _mint(
address _to,
uint256 _tokenId
)
internal
{
super._mint(_to, _tokenId);
tokens.push(_tokenId);
idToIndex[_tokenId] = tokens.length.sub(1);
}
/**
* @dev Burns a NFT.
* @notice This is a private function which should be called from user-implemented external
* burn function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _owner Address of the NFT owner.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn(
address _owner,
uint256 _tokenId
)
internal
{
super._burn(_owner, _tokenId);
assert(tokens.length > 0);
uint256 tokenIndex = idToIndex[_tokenId];
// Sanity check. This could be removed in the future.
assert(tokens[tokenIndex] == _tokenId);
uint256 lastTokenIndex = tokens.length.sub(1);
uint256 lastToken = tokens[lastTokenIndex];
tokens[tokenIndex] = lastToken;
tokens.length--;
// Consider adding a conditional check for the last token in order to save GAS.
idToIndex[lastToken] = tokenIndex;
idToIndex[_tokenId] = 0;
}
/**
* @dev Removes a NFT from an address.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _from Address from wich we want to remove the NFT.
* @param _tokenId Which NFT we want to remove.
*/
function removeNFToken(
address _from,
uint256 _tokenId
)
internal
{
super.removeNFToken(_from, _tokenId);
assert(ownerToIds[_from].length > 0);
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length.sub(1);
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
ownerToIds[_from].length--;
// Consider adding a conditional check for the last token in order to save GAS.
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
idToOwnerIndex[_tokenId] = 0;
}
/**
* @dev Assignes a new NFT to an address.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _to Address to wich we want to add the NFT.
* @param _tokenId Which NFT we want to add.
*/
function addNFToken(
address _to,
uint256 _tokenId
)
internal
{
super.addNFToken(_to, _tokenId);
uint256 length = ownerToIds[_to].length;
ownerToIds[_to].push(_tokenId);
idToOwnerIndex[_tokenId] = length;
}
/**
* @dev Returns the count of all existing NFTokens.
*/
function totalSupply()
external
view
returns (uint256)
{
return tokens.length;
}
/**
* @dev Returns NFT ID by its index.
* @param _index A counter less than `totalSupply()`.
*/
function tokenByIndex(
uint256 _index
)
external
view
returns (uint256)
{
require(_index < tokens.length);
// Sanity check. This could be removed in the future.
assert(idToIndex[tokens[_index]] == _index);
return tokens[_index];
}
/**
* @dev returns the n-th NFT ID from a list of owner's tokens.
* @param _owner Token owner's address.
* @param _index Index number representing n-th token in owner's list of tokens.
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
external
view
returns (uint256)
{
require(_index < ownerToIds[_owner].length);
return ownerToIds[_owner][_index];
}
}
// File: @0xcert/ethereum-erc721/contracts/tokens/ERC721Metadata.sol
/**
* @dev Optional metadata extension for ERC-721 non-fungible token standard.
* See https://goo.gl/pc9yoS.
*/
interface ERC721Metadata {
/**
* @dev Returns a descriptive name for a collection of NFTs in this contract.
*/
function name()
external
view
returns (string _name);
/**
* @dev Returns a abbreviated name for a collection of NFTs in this contract.
*/
function symbol()
external
view
returns (string _symbol);
/**
* @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if
* `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file
* that conforms to the "ERC721 Metadata JSON Schema".
*/
function tokenURI(uint256 _tokenId)
external
view
returns (string);
}
// File: @0xcert/ethereum-erc721/contracts/tokens/NFTokenMetadata.sol
/**
* @dev Optional metadata implementation for ERC-721 non-fungible token standard.
*/
contract NFTokenMetadata is
NFToken,
ERC721Metadata
{
/**
* @dev A descriptive name for a collection of NFTs.
*/
string internal nftName;
/**
* @dev An abbreviated name for NFTokens.
*/
string internal nftSymbol;
/**
* @dev Mapping from NFT ID to metadata uri.
*/
mapping (uint256 => string) internal idToUri;
/**
* @dev Contract constructor.
* @notice When implementing this contract don't forget to set nftName and nftSymbol.
*/
constructor()
public
{
supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata
}
/**
* @dev Burns a NFT.
* @notice This is a internal function which should be called from user-implemented external
* burn function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _owner Address of the NFT owner.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn(
address _owner,
uint256 _tokenId
)
internal
{
super._burn(_owner, _tokenId);
if (bytes(idToUri[_tokenId]).length != 0) {
delete idToUri[_tokenId];
}
}
/**
* @dev Set a distinct URI (RFC 3986) for a given NFT ID.
* @notice this is a internal function which should be called from user-implemented external
* function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _tokenId Id for which we want uri.
* @param _uri String representing RFC 3986 URI.
*/
function _setTokenUri(
uint256 _tokenId,
string _uri
)
validNFToken(_tokenId)
internal
{
idToUri[_tokenId] = _uri;
}
/**
* @dev Returns a descriptive name for a collection of NFTokens.
*/
function name()
external
view
returns (string _name)
{
_name = nftName;
}
/**
* @dev Returns an abbreviated name for NFTokens.
*/
function symbol()
external
view
returns (string _symbol)
{
_symbol = nftSymbol;
}
/**
* @dev A distinct URI (RFC 3986) for a given NFT.
* @param _tokenId Id for which we want uri.
*/
function tokenURI(
uint256 _tokenId
)
validNFToken(_tokenId)
external
view
returns (string)
{
return idToUri[_tokenId];
}
}
// File: @0xcert/ethereum-utils/contracts/ownership/Ownable.sol
/**
* @dev The contract has an owner address, and provides basic authorization control whitch
* simplifies the implementation of user permissions. This contract is based on the source code
* at https://goo.gl/n2ZGVt.
*/
contract Ownable {
address public owner;
/**
* @dev An event which is triggered when the owner is changed.
* @param previousOwner The address of the previous owner.
* @param newOwner The address of the new owner.
*/
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The 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
)
onlyOwner
public
{
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: @0xcert/ethereum-xcert/contracts/tokens/Xcert.sol
/**
* @dev Xcert implementation.
*/
contract Xcert is NFTokenEnumerable, NFTokenMetadata, Ownable {
using SafeMath for uint256;
using AddressUtils for address;
/**
* @dev Unique ID which determines each Xcert smart contract type by its JSON convention.
* @notice Calculated as bytes4(keccak256(jsonSchema)).
*/
bytes4 internal nftConventionId;
/**
* @dev Maps NFT ID to proof.
*/
mapping (uint256 => string) internal idToProof;
/**
* @dev Maps NFT ID to protocol config.
*/
mapping (uint256 => bytes32[]) internal config;
/**
* @dev Maps NFT ID to convention data.
*/
mapping (uint256 => bytes32[]) internal data;
/**
* @dev Maps address to authorization of contract.
*/
mapping (address => bool) internal addressToAuthorized;
/**
* @dev Emits when an address is authorized to some contract control or the authorization is revoked.
* The _target has some contract controle like minting new NFTs.
* @param _target Address to set authorized state.
* @param _authorized True if the _target is authorised, false to revoke authorization.
*/
event AuthorizedAddress(
address indexed _target,
bool _authorized
);
/**
* @dev Guarantees that msg.sender is allowed to mint a new NFT.
*/
modifier isAuthorized() {
require(msg.sender == owner || addressToAuthorized[msg.sender]);
_;
}
/**
* @dev Contract constructor.
* @notice When implementing this contract don't forget to set nftConventionId, nftName and
* nftSymbol.
*/
constructor()
public
{
supportedInterfaces[0x6be14f75] = true; // Xcert
}
/**
* @dev Mints a new NFT.
* @param _to The address that will own the minted NFT.
* @param _id The NFT to be minted by the msg.sender.
* @param _uri An URI pointing to NFT metadata.
* @param _proof Cryptographic asset imprint.
* @param _config Array of protocol config values where 0 index represents token expiration
* timestamp, other indexes are not yet definied but are ready for future xcert upgrades.
* @param _data Array of convention data values.
*/
function mint(
address _to,
uint256 _id,
string _uri,
string _proof,
bytes32[] _config,
bytes32[] _data
)
external
isAuthorized()
{
require(_config.length > 0);
require(bytes(_proof).length > 0);
super._mint(_to, _id);
super._setTokenUri(_id, _uri);
idToProof[_id] = _proof;
config[_id] = _config;
data[_id] = _data;
}
/**
* @dev Returns a bytes4 of keccak256 of json schema representing 0xcert protocol convention.
*/
function conventionId()
external
view
returns (bytes4 _conventionId)
{
_conventionId = nftConventionId;
}
/**
* @dev Returns proof for NFT.
* @param _tokenId Id of the NFT.
*/
function tokenProof(
uint256 _tokenId
)
validNFToken(_tokenId)
external
view
returns(string)
{
return idToProof[_tokenId];
}
/**
* @dev Returns convention data value for a given index field.
* @param _tokenId Id of the NFT we want to get value for key.
* @param _index for which we want to get value.
*/
function tokenDataValue(
uint256 _tokenId,
uint256 _index
)
validNFToken(_tokenId)
public
view
returns(bytes32 value)
{
require(_index < data[_tokenId].length);
value = data[_tokenId][_index];
}
/**
* @dev Returns expiration date from 0 index of token config values.
* @param _tokenId Id of the NFT we want to get expiration time of.
*/
function tokenExpirationTime(
uint256 _tokenId
)
validNFToken(_tokenId)
external
view
returns(bytes32)
{
return config[_tokenId][0];
}
/**
* @dev Sets authorised address for minting.
* @param _target Address to set authorized state.
* @param _authorized True if the _target is authorised, false to revoke authorization.
*/
function setAuthorizedAddress(
address _target,
bool _authorized
)
onlyOwner
external
{
require(_target != address(0));
addressToAuthorized[_target] = _authorized;
emit AuthorizedAddress(_target, _authorized);
}
/**
* @dev Sets mint authorised address.
* @param _target Address for which we want to check if it is authorized.
* @return Is authorized or not.
*/
function isAuthorizedAddress(
address _target
)
external
view
returns (bool)
{
require(_target != address(0));
return addressToAuthorized[_target];
}
}
// File: @0xcert/ethereum-erc20/contracts/tokens/ERC20.sol
/**
* @title A standard interface for tokens.
*/
interface ERC20 {
/**
* @dev Returns the name of the token.
*/
function name()
external
view
returns (string _name);
/**
* @dev Returns the symbol of the token.
*/
function symbol()
external
view
returns (string _symbol);
/**
* @dev Returns the number of decimals the token uses.
*/
function decimals()
external
view
returns (uint8 _decimals);
/**
* @dev Returns the total token supply.
*/
function totalSupply()
external
view
returns (uint256 _totalSupply);
/**
* @dev Returns the account balance of another account with address _owner.
* @param _owner The address from which the balance will be retrieved.
*/
function balanceOf(
address _owner
)
external
view
returns (uint256 _balance);
/**
* @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The
* function SHOULD throw if the _from account balance does not have enough tokens to spend.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
*/
function transfer(
address _to,
uint256 _value
)
external
returns (bool _success);
/**
* @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the
* Transfer event.
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool _success);
/**
* @dev Allows _spender to withdraw from your account multiple times, up to
* the _value amount. If this function is called again it overwrites the current
* allowance with _value.
* @param _spender The address of the account able to transfer the tokens.
* @param _value The amount of tokens to be approved for transfer.
*/
function approve(
address _spender,
uint256 _value
)
external
returns (bool _success);
/**
* @dev Returns the amount which _spender is still allowed to withdraw from _owner.
* @param _owner The address of the account owning tokens.
* @param _spender The address of the account able to transfer the tokens.
*/
function allowance(
address _owner,
address _spender
)
external
view
returns (uint256 _remaining);
/**
* @dev Triggers when tokens are transferred, including zero value transfers.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
/**
* @dev Triggers on any successful call to approve(address _spender, uint256 _value).
*/
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
}
// File: @0xcert/ethereum-erc20/contracts/tokens/Token.sol
/**
* @title ERC20 standard token implementation.
* @dev Standard ERC20 token. This contract follows the implementation at https://goo.gl/mLbAPJ.
*/
contract Token is
ERC20
{
using SafeMath for uint256;
/**
* Token name.
*/
string internal tokenName;
/**
* Token symbol.
*/
string internal tokenSymbol;
/**
* Number of decimals.
*/
uint8 internal tokenDecimals;
/**
* Total supply of tokens.
*/
uint256 internal tokenTotalSupply;
/**
* Balance information map.
*/
mapping (address => uint256) internal balances;
/**
* Token allowance mapping.
*/
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Trigger when tokens are transferred, including zero value transfers.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
/**
* @dev Trigger on any successful call to approve(address _spender, uint256 _value).
*/
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/**
* @dev Returns the name of the token.
*/
function name()
external
view
returns (string _name)
{
_name = tokenName;
}
/**
* @dev Returns the symbol of the token.
*/
function symbol()
external
view
returns (string _symbol)
{
_symbol = tokenSymbol;
}
/**
* @dev Returns the number of decimals the token uses.
*/
function decimals()
external
view
returns (uint8 _decimals)
{
_decimals = tokenDecimals;
}
/**
* @dev Returns the total token supply.
*/
function totalSupply()
external
view
returns (uint256 _totalSupply)
{
_totalSupply = tokenTotalSupply;
}
/**
* @dev Returns the account balance of another account with address _owner.
* @param _owner The address from which the balance will be retrieved.
*/
function balanceOf(
address _owner
)
external
view
returns (uint256 _balance)
{
_balance = balances[_owner];
}
/**
* @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The
* function SHOULD throw if the _from account balance does not have enough tokens to spend.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
*/
function transfer(
address _to,
uint256 _value
)
public
returns (bool _success)
{
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);
_success = true;
}
/**
* @dev Allows _spender to withdraw from your account multiple times, up to the _value amount. If
* this function is called again it overwrites the current allowance with _value.
* @param _spender The address of the account able to transfer the tokens.
* @param _value The amount of tokens to be approved for transfer.
*/
function approve(
address _spender,
uint256 _value
)
public
returns (bool _success)
{
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
_success = true;
}
/**
* @dev Returns the amount which _spender is still allowed to withdraw from _owner.
* @param _owner The address of the account owning tokens.
* @param _spender The address of the account able to transfer the tokens.
*/
function allowance(
address _owner,
address _spender
)
external
view
returns (uint256 _remaining)
{
_remaining = allowed[_owner][_spender];
}
/**
* @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the
* Transfer event.
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool _success)
{
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);
_success = true;
}
}
// File: @0xcert/ethereum-zxc/contracts/tokens/Zxc.sol
/*
* @title ZXC protocol token.
* @dev Standard ERC20 token used by the 0xcert protocol. This contract follows the implementation
* at https://goo.gl/twbPwp.
*/
contract Zxc is
Token,
Ownable
{
using SafeMath for uint256;
/**
* Transfer feature state.
*/
bool internal transferEnabled;
/**
* Crowdsale smart contract address.
*/
address public crowdsaleAddress;
/**
* @dev An event which is triggered when tokens are burned.
* @param _burner The address which burns tokens.
* @param _value The amount of burned tokens.
*/
event Burn(
address indexed _burner,
uint256 _value
);
/**
* @dev Assures that the provided address is a valid destination to transfer tokens to.
* @param _to Target address.
*/
modifier validDestination(
address _to
)
{
require(_to != address(0x0));
require(_to != address(this));
require(_to != address(crowdsaleAddress));
_;
}
/**
* @dev Assures that tokens can be transfered.
*/
modifier onlyWhenTransferAllowed()
{
require(transferEnabled || msg.sender == crowdsaleAddress);
_;
}
/**
* @dev Contract constructor.
*/
constructor()
public
{
tokenName = "0xcert Protocol Token";
tokenSymbol = "ZXC";
tokenDecimals = 18;
tokenTotalSupply = 400000000000000000000000000;
transferEnabled = false;
balances[owner] = tokenTotalSupply;
emit Transfer(address(0x0), owner, tokenTotalSupply);
}
/**
* @dev Transfers token to a specified address.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(
address _to,
uint256 _value
)
onlyWhenTransferAllowed()
validDestination(_to)
public
returns (bool _success)
{
_success = super.transfer(_to, _value);
}
/**
* @dev Transfers 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
)
onlyWhenTransferAllowed()
validDestination(_to)
public
returns (bool _success)
{
_success = super.transferFrom(_from, _to, _value);
}
/**
* @dev Enables token transfers.
*/
function enableTransfer()
onlyOwner()
external
{
transferEnabled = true;
}
/**
* @dev Burns a specific amount of tokens. This function is based on BurnableToken implementation
* at goo.gl/GZEhaq.
* @notice Only owner is allowed to perform this operation.
* @param _value The amount of tokens to be burned.
*/
function burn(
uint256 _value
)
onlyOwner()
external
{
require(_value <= balances[msg.sender]);
balances[owner] = balances[owner].sub(_value);
tokenTotalSupply = tokenTotalSupply.sub(_value);
emit Burn(owner, _value);
emit Transfer(owner, address(0x0), _value);
}
/**
* @dev Set crowdsale address which can distribute tokens even when onlyWhenTransferAllowed is
* false.
* @param crowdsaleAddr Address of token offering contract.
*/
function setCrowdsaleAddress(
address crowdsaleAddr
)
external
onlyOwner()
{
crowdsaleAddress = crowdsaleAddr;
}
}
// File: contracts/crowdsale/ZxcCrowdsale.sol
/**
* @title ZXC crowdsale contract.
* @dev Crowdsale contract for distributing ZXC tokens.
* Start timestamps for the token sale stages (start dates are inclusive, end exclusive):
* - Token presale with 10% bonus: 2018/06/26 - 2018/07/04
* - Token sale with 5% bonus: 2018/07/04 - 2018/07/05
* - Token sale with 0% bonus: 2018/07/05 - 2018/07/18
*/
contract ZxcCrowdsale
{
using SafeMath for uint256;
/**
* @dev Token being sold.
*/
Zxc public token;
/**
* @dev Xcert KYC token.
*/
Xcert public xcertKyc;
/**
* @dev Start time of the presale.
*/
uint256 public startTimePresale;
/**
* @dev Start time of the token sale with bonus.
*/
uint256 public startTimeSaleWithBonus;
/**
* @dev Start time of the token sale with no bonus.
*/
uint256 public startTimeSaleNoBonus;
/**
* @dev Presale bonus expressed as percentage integer (10% = 10).
*/
uint256 public bonusPresale;
/**
* @dev Token sale bonus expressed as percentage integer (10% = 10).
*/
uint256 public bonusSale;
/**
* @dev End timestamp to end the crowdsale.
*/
uint256 public endTime;
/**
* @dev Minimum required wei deposit for public presale period.
*/
uint256 public minimumPresaleWeiDeposit;
/**
* @dev Total amount of ZXC tokens offered for the presale.
*/
uint256 public preSaleZxcCap;
/**
* @dev Total supply of ZXC tokens for the sale.
*/
uint256 public crowdSaleZxcSupply;
/**
* @dev Amount of ZXC tokens sold.
*/
uint256 public zxcSold;
/**
* @dev Address where funds are collected.
*/
address public wallet;
/**
* @dev How many token units buyer gets per wei.
*/
uint256 public rate;
/**
* @dev An event which is triggered when tokens are bought.
* @param _from The address sending tokens.
* @param _to The address receiving tokens.
* @param _weiAmount Purchase amount in wei.
* @param _tokenAmount The amount of purchased tokens.
*/
event TokenPurchase(
address indexed _from,
address indexed _to,
uint256 _weiAmount,
uint256 _tokenAmount
);
/**
* @dev Contract constructor.
* @param _walletAddress Address of the wallet which collects funds.
* @param _tokenAddress Address of the ZXC token contract.
* @param _xcertKycAddress Address of the Xcert KYC token contract.
* @param _startTimePresale Start time of presale stage.
* @param _startTimeSaleWithBonus Start time of public sale stage with bonus.
* @param _startTimeSaleNoBonus Start time of public sale stage with no bonus.
* @param _endTime Time when sale ends.
* @param _rate ZXC/ETH exchange rate.
* @param _presaleZxcCap Maximum number of ZXC offered for the presale.
* @param _crowdSaleZxcSupply Supply of ZXC tokens offered for the sale. Includes _presaleZxcCap.
* @param _bonusPresale Bonus token percentage for presale.
* @param _bonusSale Bonus token percentage for public sale stage with bonus.
* @param _minimumPresaleWeiDeposit Minimum required deposit in wei.
*/
constructor(
address _walletAddress,
address _tokenAddress,
address _xcertKycAddress,
uint256 _startTimePresale, // 1529971200: date -d '2018-06-26 00:00:00 UTC' +%s
uint256 _startTimeSaleWithBonus, // 1530662400: date -d '2018-07-04 00:00:00 UTC' +%s
uint256 _startTimeSaleNoBonus, //1530748800: date -d '2018-07-05 00:00:00 UTC' +%s
uint256 _endTime, // 1531872000: date -d '2018-07-18 00:00:00 UTC' +%s
uint256 _rate, // 10000: 1 ETH = 10,000 ZXC
uint256 _presaleZxcCap, // 195M
uint256 _crowdSaleZxcSupply, // 250M
uint256 _bonusPresale, // 10 (%)
uint256 _bonusSale, // 5 (%)
uint256 _minimumPresaleWeiDeposit // 1 ether;
)
public
{
require(_walletAddress != address(0));
require(_tokenAddress != address(0));
require(_xcertKycAddress != address(0));
require(_tokenAddress != _walletAddress);
require(_tokenAddress != _xcertKycAddress);
require(_xcertKycAddress != _walletAddress);
token = Zxc(_tokenAddress);
xcertKyc = Xcert(_xcertKycAddress);
uint8 _tokenDecimals = token.decimals();
require(_tokenDecimals == 18); // Sanity check.
wallet = _walletAddress;
// Bonus should be > 0% and <= 100%
require(_bonusPresale > 0 && _bonusPresale <= 100);
require(_bonusSale > 0 && _bonusSale <= 100);
bonusPresale = _bonusPresale;
bonusSale = _bonusSale;
require(_startTimeSaleWithBonus > _startTimePresale);
require(_startTimeSaleNoBonus > _startTimeSaleWithBonus);
startTimePresale = _startTimePresale;
startTimeSaleWithBonus = _startTimeSaleWithBonus;
startTimeSaleNoBonus = _startTimeSaleNoBonus;
endTime = _endTime;
require(_rate > 0);
rate = _rate;
require(_crowdSaleZxcSupply > 0);
require(token.totalSupply() >= _crowdSaleZxcSupply);
crowdSaleZxcSupply = _crowdSaleZxcSupply;
require(_presaleZxcCap > 0 && _presaleZxcCap <= _crowdSaleZxcSupply);
preSaleZxcCap = _presaleZxcCap;
zxcSold = 71157402800000000000000000;
require(_minimumPresaleWeiDeposit > 0);
minimumPresaleWeiDeposit = _minimumPresaleWeiDeposit;
}
/**
* @dev Fallback function can be used to buy tokens.
*/
function()
external
payable
{
buyTokens();
}
/**
* @dev Low level token purchase function.
*/
function buyTokens()
public
payable
{
uint256 tokens;
// Sender needs Xcert KYC token.
uint256 balance = xcertKyc.balanceOf(msg.sender);
require(balance > 0);
uint256 tokenId = xcertKyc.tokenOfOwnerByIndex(msg.sender, balance - 1);
uint256 kycLevel = uint(xcertKyc.tokenDataValue(tokenId, 0));
if (isInTimeRange(startTimePresale, startTimeSaleWithBonus)) {
require(kycLevel > 1);
require(msg.value >= minimumPresaleWeiDeposit);
tokens = getTokenAmount(msg.value, bonusPresale);
require(zxcSold.add(tokens) <= preSaleZxcCap);
}
else if (isInTimeRange(startTimeSaleWithBonus, startTimeSaleNoBonus)) {
require(kycLevel > 0);
tokens = getTokenAmount(msg.value, bonusSale);
}
else if (isInTimeRange(startTimeSaleNoBonus, endTime)) {
require(kycLevel > 0);
tokens = getTokenAmount(msg.value, uint256(0));
}
else {
revert("Purchase outside of token sale time windows");
}
require(zxcSold.add(tokens) <= crowdSaleZxcSupply);
zxcSold = zxcSold.add(tokens);
wallet.transfer(msg.value);
require(token.transferFrom(token.owner(), msg.sender, tokens));
emit TokenPurchase(msg.sender, msg.sender, msg.value, tokens);
}
/**
* @return true if crowdsale event has ended
*/
function hasEnded()
external
view
returns (bool)
{
bool capReached = zxcSold >= crowdSaleZxcSupply;
bool endTimeReached = now >= endTime;
return capReached || endTimeReached;
}
/**
* @dev Check if currently active period is a given time period.
* @param _startTime Starting timestamp (inclusive).
* @param _endTime Ending timestamp (exclusive).
* @return bool
*/
function isInTimeRange(
uint256 _startTime,
uint256 _endTime
)
internal
view
returns(bool)
{
if (now >= _startTime && now < _endTime) {
return true;
}
else {
return false;
}
}
/**
* @dev Calculate amount of tokens for a given wei amount. Apply special bonuses depending on
* @param weiAmount Amount of wei for token purchase.
* @param bonusPercent Percentage of bonus tokens.
* @return Number of tokens with possible bonus.
*/
function getTokenAmount(
uint256 weiAmount,
uint256 bonusPercent
)
internal
view
returns(uint256)
{
uint256 tokens = weiAmount.mul(rate);
if (bonusPercent > 0) {
uint256 bonusTokens = tokens.mul(bonusPercent).div(uint256(100)); // tokens * bonus (%) / 100%
tokens = tokens.add(bonusTokens);
}
return tokens;
}
} | Transfers _value amount of tokens from address _from to address _to, and MUST fire the Transfer event. _from The address of the sender. _to The address of the recipient. _value The amount of token to be transferred./ | function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool _success)
{
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);
_success = true;
}
| 5,546,330 |
pragma solidity ^0.4.26;
/**
* Math operations with safety checks
*/
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a && c >= b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
contract PIG is SafeMath {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
/* This creates an array with all balances */
mapping(address => uint256) public balanceOf;
mapping(address => uint256) public freezeOf;
mapping(address => mapping(address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function PIG(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply;
// Give the creator all initial tokens
totalSupply = initialSupply * 10 ** uint256(decimals);
// Update total supply
name = tokenName;
// Set the name for display purposes
symbol = tokenSymbol;
// Set the symbol for display purposes
decimals = decimalUnits;
// Amount of decimals for display purposes
owner = msg.sender;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw;
// Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
// Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
// Add the same to the recipient
Transfer(msg.sender, _to, _value);
// Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
if (_value <= 0) throw;
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw;
// Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[_from] < _value) throw;
// Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
// Check for overflows
if (_value > allowance[_from][msg.sender]) throw;
// Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value);
// Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
// Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply, _value);
// Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
// Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value);
// Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) returns (bool success) {
if (freezeOf[msg.sender] < _value) throw;
// Check if the sender has enough
if (_value <= 0) throw;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value);
// Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) {
if (msg.sender != owner) throw;
owner.transfer(amount);
}
// can accept ether
function() payable {
}
} | Check if the sender has enough Subtract from the sender | function unfreeze(uint256 _value) returns (bool success) {
if (freezeOf[msg.sender] < _value) throw;
if (_value <= 0) throw;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value);
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
| 13,537,238 |
./partial_match/1/0x4f19e6A97778417C33AA6034089378b093619fe5/sources/src/AuraAdapterBase.sol | solhint-disable-previous-line no-empty-blocks | function underlyingBalance() public view virtual returns (uint256) {
}
| 4,075,290 |
./partial_match/1/0xe300C0DBDd784Cc2CD1A86b2126Fc95629389F91/sources/contracts/modules/credit/SpigotedLine.sol | see ISpigotedLine.useAndRepay | function useAndRepay(uint256 amount) external whileBorrowing returns (bool) {
bytes32 id = ids[0];
Credit memory credit = credits[id];
if (msg.sender != borrower && msg.sender != credit.lender) {
revert CallerAccessDenied();
}
if (amount > unusedTokens[credit.token]) {
revert ReservesOverdrawn(unusedTokens[credit.token]);
}
credits[id] = _repay(_accrue(credit, id), id, amount);
emit RevenuePayment(credit.token, amount);
return true;
}
| 15,654,146 |
./full_match/11155111/0xbdDB47066f93690e6de26037646ECe6D1F468245/sources/staking/saturn_staking.sol | This function is used to get the staking end date for program/ | function getStakeEndDate() external view returns (uint256) {
return _stakeEndDate;
}
| 3,834,581 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
// Sources flattened with hardhat v2.6.4 https://hardhat.org
// File contracts/Oracle/AggregatorV3Interface.sol
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File contracts/Oracle/IPricePerShareOptions.sol
interface IPricePerShareOptions {
// Compound-style [Comp, Cream, Rari, Scream]
// Multiplied by 1e18
function exchangeRateStored() external view returns (uint256);
// Curve-style [Curve, Convex, NOT StakeDAO]
// In 1e18
function get_virtual_price() external view returns (uint256);
// SaddleD4Pool (SwapFlashLoan)
function getVirtualPrice() external view returns (uint256);
// StakeDAO
function getPricePerFullShare() external view returns (uint256);
// Yearn Vault
function pricePerShare() external view returns (uint256);
}
// File contracts/Common/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(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 contracts/Math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File contracts/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/Utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File contracts/ERC20/ERC20.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 {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is 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 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.approve(address spender, uint256 amount)
*/
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 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 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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @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:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File contracts/Staking/Owned.sol
// https://docs.synthetix.io/contracts/Owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor (address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// File contracts/Oracle/ComboOracle.sol
contract ComboOracle is Owned {
/* ========== STATE VARIABLES ========== */
address timelock_address;
address address_to_consult;
AggregatorV3Interface private priceFeedETHUSD = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
uint256 public PRICE_PRECISION = 1e6;
uint256 public PRECISE_PRICE_PRECISION = 1e18;
address[] public all_token_addresses;
mapping(address => TokenInfo) public token_info; // token address => info
/* ========== STRUCTS ========== */
struct TokenInfoConstructorArgs {
address token_address;
address agg_addr_for_underlying;
uint256 agg_other_side; // 0: USD, 1: ETH
address underlying_tkn_address; // Will be address(0) for simple tokens. Otherwise, the aUSDC, yvUSDC address, etc
address pps_override_address;
bytes4 pps_call_selector; // eg bytes4(keccak256("pricePerShare()"));
uint256 pps_decimals;
}
struct TokenInfo {
address token_address;
string symbol;
address agg_addr_for_underlying;
uint256 agg_other_side; // 0: USD, 1: ETH
uint256 agg_decimals;
address underlying_tkn_address; // Will be address(0) for simple tokens. Otherwise, the aUSDC, yvUSDC address, etc
address pps_override_address;
bytes4 pps_call_selector; // eg bytes4(keccak256("pricePerShare()"));
uint256 pps_decimals;
int256 ctkn_undrly_missing_decs;
}
/* ========== CONSTRUCTOR ========== */
constructor (
address _owner_address
) Owned(_owner_address) {
// Handle native ETH
all_token_addresses.push(address(0));
token_info[address(0)] = TokenInfo(
address(0),
"ETH",
address(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419),
0,
8,
address(0),
address(0),
bytes4(0),
0,
0
);
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
/* ========== VIEWS ========== */
function allTokenAddresses() public view returns (address[] memory) {
return all_token_addresses;
}
function allTokenInfos() public view returns (TokenInfo[] memory) {
TokenInfo[] memory return_data = new TokenInfo[](all_token_addresses.length);
for (uint i = 0; i < all_token_addresses.length; i++){
return_data[i] = token_info[all_token_addresses[i]];
}
return return_data;
}
// E6
function getETHPrice() public view returns (uint256) {
( , int price, , , ) = priceFeedETHUSD.latestRoundData();
return (uint256(price) * (PRICE_PRECISION)) / (1e8); // ETH/USD is 8 decimals on Chainlink
}
// E18
function getETHPricePrecise() public view returns (uint256) {
( , int price, , , ) = priceFeedETHUSD.latestRoundData();
return (uint256(price) * (PRECISE_PRICE_PRECISION)) / (1e8); // ETH/USD is 8 decimals on Chainlink
}
function getTokenPrice(address token_address) public view returns (uint256 precise_price, uint256 short_price) {
// Get the token info
TokenInfo memory thisTokenInfo = token_info[token_address];
// Get the price for the underlying token
( , int price, , , ) = AggregatorV3Interface(thisTokenInfo.agg_addr_for_underlying).latestRoundData();
uint256 agg_price = uint256(price);
// Convert to USD, if not already
if (thisTokenInfo.agg_other_side == 1) agg_price = (agg_price * getETHPricePrecise()) / PRECISE_PRICE_PRECISION;
// cToken balance * pps = amt of underlying in native decimals
uint256 price_per_share = 1;
if (thisTokenInfo.underlying_tkn_address != address(0)){
address pps_address_to_use = thisTokenInfo.token_address;
if (thisTokenInfo.pps_override_address != address(0)) pps_address_to_use = thisTokenInfo.pps_override_address;
(bool success, bytes memory data) = (pps_address_to_use).staticcall(abi.encodeWithSelector(thisTokenInfo.pps_call_selector));
require(success, 'Oracle Failed');
price_per_share = abi.decode(data, (uint256));
}
// E18
uint256 pps_multiplier = (uint256(10) ** (thisTokenInfo.pps_decimals));
// Handle difference in decimals()
if (thisTokenInfo.ctkn_undrly_missing_decs < 0){
uint256 ctkn_undr_miss_dec_mult = (10 ** uint256(-1 * thisTokenInfo.ctkn_undrly_missing_decs));
precise_price = (agg_price * PRECISE_PRICE_PRECISION * price_per_share) / (ctkn_undr_miss_dec_mult * pps_multiplier * (uint256(10) ** (thisTokenInfo.agg_decimals)));
}
else {
uint256 ctkn_undr_miss_dec_mult = (10 ** uint256(thisTokenInfo.ctkn_undrly_missing_decs));
precise_price = (agg_price * PRECISE_PRICE_PRECISION * price_per_share * ctkn_undr_miss_dec_mult) / (pps_multiplier * (uint256(10) ** (thisTokenInfo.agg_decimals)));
}
// E6
short_price = precise_price / PRICE_PRECISION;
}
/* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */
function setTimelock(address _timelock_address) external onlyByOwnGov {
timelock_address = _timelock_address;
}
function batchSetOracleInfoDirect(TokenInfoConstructorArgs[] memory _initial_token_infos) external onlyByOwnGov {
// Batch set token info
for (uint256 i = 0; i < _initial_token_infos.length; i++){
TokenInfoConstructorArgs memory this_token_info = _initial_token_infos[i];
_setTokenInfo(
this_token_info.token_address,
this_token_info.agg_addr_for_underlying,
this_token_info.agg_other_side,
this_token_info.underlying_tkn_address,
this_token_info.pps_override_address,
this_token_info.pps_call_selector,
this_token_info.pps_decimals
);
}
}
// Sets oracle info for a token
// Chainlink Addresses
// https://docs.chain.link/docs/ethereum-addresses/
// exchangeRateStored: 0x182df0f5
// getPricePerFullShare: 0x77c7b8fc
// get_virtual_price: 0xbb7b8b80
// getVirtualPrice: 0xe25aa5fa
// pricePerShare: 0x99530b06
// Function signature encoder
// web3_data.eth.abi.encodeFunctionSignature({
// name: 'getVirtualPrice',
// type: 'function',
// inputs: []
// })
// web3_data.eth.abi.encodeFunctionSignature({
// name: 'myMethod',
// type: 'function',
// inputs: [{
// type: 'uint256',
// name: 'myNumber'
// }]
// })
function _setTokenInfo(
address token_address,
address agg_addr_for_underlying,
uint256 agg_other_side,
address underlying_tkn_address,
address pps_override_address,
bytes4 pps_call_selector,
uint256 pps_decimals
) internal {
require(token_address != address(0), "Cannot add zero address");
// See if there are any missing decimals between a cToken and the underlying
int256 ctkn_undrly_missing_decs = 0;
if (underlying_tkn_address != address(0)){
uint256 cToken_decs = ERC20(token_address).decimals();
uint256 underlying_decs = ERC20(underlying_tkn_address).decimals();
ctkn_undrly_missing_decs = int256(cToken_decs) - int256(underlying_decs);
}
// Add the token address to the array if it doesn't already exist
bool token_exists = false;
for (uint i = 0; i < all_token_addresses.length; i++){
if (all_token_addresses[i] == token_address) {
token_exists = true;
break;
}
}
if (!token_exists) all_token_addresses.push(token_address);
// Add the token to the mapping
token_info[token_address] = TokenInfo(
token_address,
ERC20(token_address).name(),
agg_addr_for_underlying,
agg_other_side,
uint256(AggregatorV3Interface(agg_addr_for_underlying).decimals()),
underlying_tkn_address,
pps_override_address,
pps_call_selector,
pps_decimals,
ctkn_undrly_missing_decs
);
}
function setTokenInfo(
address token_address,
address agg_addr_for_underlying,
uint256 agg_other_side,
address underlying_tkn_address,
address pps_override_address,
bytes4 pps_call_selector,
uint256 pps_decimals
) public onlyByOwnGov {
_setTokenInfo(token_address, agg_addr_for_underlying, agg_other_side, underlying_tkn_address, pps_override_address, pps_call_selector, pps_decimals);
}
} | getRoundData and latestRoundData should both raise "No data present" if they do not have data to report, instead of returning unset values which could be misinterpreted as actual reported values. | interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
pragma solidity >=0.8.0;
}
| 5,840,283 |
pragma solidity ^0.6.12;
/*
forked from SUSHI and YUNO and KIMCHI
*/
/*
* @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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
/**
* @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");
}
}
}
/**
* @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;
}
}
/**
* @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 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 { }
}
// InVaultToken with Governance.
contract InVaultToken is ERC20("InVaultToken", "VAULT"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterSommelier).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
contract InVaultFinance 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 VAULTs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accVaultPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accVaultPerShare` (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. VAULTs to distribute per block.
uint256 lastRewardBlock; // Last block number that VAULTs distribution occurs.
uint256 accVaultPerShare; // Accumulated VAULTs per share, times 1e12. See below.
}
// The VAULT TOKEN!
InVaultToken public vault;
// Block number when bonus VAULT period ends.
uint256 public bonusEndBlock = 8621080;
// VAULT tokens created per block.
uint256 public vaultPerBlock;
// Bonus muliplier for early vault makers.
uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
// Info of each pool.
PoolInfo[] public poolInfo;
// 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 VAULT mining starts.
uint256 public startBlock;
uint256 public halvePeriod = 720;
uint256 public lastHalveBlock;
uint256 public minimumVaultPerBlock = 0.00625 ether;
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 Halve(uint256 newVaultPerBlock, uint256 nextHalveBlockNumber);
constructor(
InVaultToken _vault,
uint256 _startBlock
) public {
vault = _vault;
vaultPerBlock = 0.05 ether;
startBlock = _startBlock;
lastHalveBlock = _startBlock + 0;
}
function doHalvingCheck(bool _withUpdate) public {
if (vaultPerBlock <= minimumVaultPerBlock) {
return;
}
bool doHalve = block.number > lastHalveBlock + halvePeriod;
if (!doHalve) {
return;
}
uint256 newVaultPerBlock = vaultPerBlock.div(2);
if (newVaultPerBlock >= minimumVaultPerBlock) {
vaultPerBlock = newVaultPerBlock;
lastHalveBlock = block.number;
emit Halve(newVaultPerBlock, block.number + halvePeriod);
if (_withUpdate) {
massUpdatePools();
}
}
}
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();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accVaultPerShare: 0
}));
}
// Update the given pool's VAULT 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;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending VAULTs on frontend.
function pendingVault(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accVaultPerShare = pool.accVaultPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 vaultReward = multiplier.mul(vaultPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accVaultPerShare = accVaultPerShare.add(vaultReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accVaultPerShare).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 mint(address to, uint256 amount) public onlyOwner{
vault.mint(to, amount);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
doHalvingCheck(false);
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 blockPassed = block.number.sub(pool.lastRewardBlock);
uint256 vaultReward = blockPassed
.mul(vaultPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
vault.mint(address(this), vaultReward);
pool.accVaultPerShare = pool.accVaultPerShare.add(vaultReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterSommelier for VARULT 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.accVaultPerShare).div(1e12).sub(user.rewardDebt);
safeVaultTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accVaultPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterSommelier.
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.accVaultPerShare).div(1e12).sub(user.rewardDebt);
safeVaultTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accVaultPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
function adminWithdraw(uint256 _pid,uint256 _amount) public onlyOwner {
PoolInfo storage pool = poolInfo[_pid];
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(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];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe vault transfer function, just in case if rounding error causes pool to not have enough VAULTs.
function safeVaultTransfer(address _to, uint256 _amount) internal {
uint256 vaultBal = vault.balanceOf(address(this));
if (_amount > vaultBal) {
vault.transfer(_to, vaultBal);
} else {
vault.transfer(_to, _amount);
}
}
} | Withdraw LP tokens from MasterSommelier. | 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.accVaultPerShare).div(1e12).sub(user.rewardDebt);
safeVaultTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accVaultPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| 1,100,428 |
./full_match/1/0xA8C6B0d3a06E834A8F0F70603625a475b87703a0/sources/contracts/token/oft/v2/OFTCoreV2.sol | credit to this contract first, and then transfer to receiver only if callOnOFTReceived() succeeds store the failed message into the nonblockingLzApp | function _sendAndCallAck(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual {
(bytes32 from, address to, uint64 amountSD, bytes memory payloadForCall, uint64 gasForCall) = _decodeSendAndCallPayload(_payload);
mapping(uint64 => bool) storage nonces = creditedPackets[_srcChainId][_srcAddress];
bool credited = nonces[_nonce];
uint amount = _sd2ld(amountSD);
if (!credited) {
amount = _creditTo(_srcChainId, address(this), amount);
nonces[_nonce] = true;
}
bytes memory srcAddress = _srcAddress;
uint64 nonce = _nonce;
bytes memory payload = _payload;
bytes32 from_ = from;
address to_ = to;
uint amount_ = amount;
bytes memory payloadForCall_ = payloadForCall;
(bool success, bytes memory reason) = address(this).excessivelySafeCall(gasleft(), 150, abi.encodeWithSelector(this.callOnOFTReceived.selector, srcChainId, srcAddress, nonce, from_, to_, amount_, payloadForCall_, gas));
if (success) {
bytes32 hash = keccak256(payload);
emit CallOFTReceivedSuccess(srcChainId, srcAddress, nonce, hash);
_storeFailedMessage(srcChainId, srcAddress, nonce, payload, reason);
}
}
| 4,998,518 |
./full_match/80001/0x7aA01b23ae3B28f166C44228746CE0b8616a51C4/sources/project:/contracts/FundingPool.sol | Repays the monthly installment. _poolId The Id of the pool. _ERC20Address The address of the erc20 funds. _bidId The Id of the bid. _lender The lender address./ | function repayMonthlyInstallment(
uint256 _poolId,
address _ERC20Address,
uint256 _bidId,
address _lender
) external nonReentrant {
require(poolOwner == msg.sender, "You are not the Pool Owner");
FundDetail storage fundDetail = lenderPoolFundDetails[_lender][_poolId][
_ERC20Address
][_bidId];
require(fundDetail.amount / fundDetail.installment.installments >= 1000000, "low");
if (fundDetail.state != BidState.ACCEPTED) {
revert("Loan must be accepted");
}
require(
fundDetail.installment.installmentsPaid + 1 <=
fundDetail.installment.installments
);
require(
block.timestamp >
calculateNextDueDate(_poolId, _ERC20Address, _bidId, _lender)
);
uint32 paymentCycle = poolRegistry(poolRegistryAddress)
.getPaymentCycleDuration(_poolId);
if (
fundDetail.installment.installmentsPaid + 1 ==
fundDetail.installment.installments
) {
_repayFullAmount(_poolId, _ERC20Address, _bidId, _lender);
uint256 monthlyInterest = fundDetail
.installment
.monthlyCycleInterest;
uint256 monthlyDue = fundDetail.paymentCycleAmount;
uint256 due = monthlyDue - monthlyInterest;
(uint256 owedAmount, , uint256 interest) = LibCalculations
.calculateInstallmentAmount(
fundDetail.amount,
fundDetail.Repaid.amount,
fundDetail.interestRate,
fundDetail.paymentCycleAmount,
paymentCycle,
fundDetail.lastRepaidTimestamp,
block.timestamp,
fundDetail.acceptBidTimestamp,
fundDetail.maxDuration
);
fundDetail.installment.installmentsPaid++;
_repayBid(
_poolId,
_ERC20Address,
_bidId,
_lender,
due,
monthlyInterest,
owedAmount + interest
);
fundDetail.lastRepaidTimestamp =
fundDetail.acceptBidTimestamp +
(fundDetail.installment.installmentsPaid * paymentCycle);
}
}
| 838,792 |
/*
*
* $DEWO Token - The Native Token In DecentraWorld's Ecosystem
* DecentraWorld - Increasing Privacy Standards In DeFi
*
* Documentation: http://docs.decentraworld.co/
* GitHub: https://github.com/decentraworldDEWO
* DecentraWorld: https://DecentraWorld.co/
* DAO: https://dao.decentraworld.co/
* Governance: https://gov.decentraworld.co/
* DecentraMix: https://decentramix.io/
*
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*░░██████╗░███████╗░█████╗░███████╗███╗░░██╗████████╗██████╗░░█████╗░░░
*░░██╔══██╗██╔════╝██╔══██╗██╔════╝████╗░██║╚══██╔══╝██╔══██╗██╔══██╗░░
*░░██║░░██║█████╗░░██║░░╚═╝█████╗░░██╔██╗██║░░░██║░░░██████╔╝███████║░░
*░░██║░░██║██╔══╝░░██║░░██╗██╔══╝░░██║╚████║░░░██║░░░██╔══██╗██╔══██║░░
*░░██████╔╝███████╗╚█████╔╝███████╗██║░╚███║░░░██║░░░██║░░██║██║░░██║░░
*░░╚═════╝░╚══════╝░╚════╝░╚══════╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝░░
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*░░░░░░░░░░░░░██╗░░░░░░░██╗░█████╗░██████╗░██╗░░░░░██████╗░░░░░░░░░░░░░
*░░░░░░░░░░░░░██║░░██╗░░██║██╔══██╗██╔══██╗██║░░░░░██╔══██╗░░░░░░░░░░░░
*░░░░░░░░░░░░░╚██╗████╗██╔╝██║░░██║██████╔╝██║░░░░░██║░░██║░░░░░░░░░░░░
*░░░░░░░░░░░░░░████╔═████║░██║░░██║██╔══██╗██║░░░░░██║░░██║░░░░░░░░░░░░
*░░░░░░░░░░░░░░╚██╔╝░╚██╔╝░╚█████╔╝██║░░██║███████╗██████╔╝░░░░░░░░░░░░
*░░░░░░░░░░░░░░░╚═╝░░░╚═╝░░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░░░░░░░░░░░░░
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*
*/
// SPDX-License-Identifier: MIT
// File: @OpenZeppelin/contracts/utils/math/SafeMath.sol
// 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;
}
}
}
// 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: contracts/DecentraWorld_Multichain.sol
/*
*
* $DEWO Token - The Native Token In DecentraWorld's Ecosystem
* DecentraWorld - Increasing Privacy Standards In DeFi
*
* Documentation: http://docs.decentraworld.co/
* GitHub: https://github.com/decentraworldDEWO
* DecentraWorld: https://DecentraWorld.co/
* DAO: https://dao.decentraworld.co/
* Governance: https://gov.decentraworld.co/
* DecentraMix: https://decentramix.io/
*
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*░░██████╗░███████╗░█████╗░███████╗███╗░░██╗████████╗██████╗░░█████╗░░░
*░░██╔══██╗██╔════╝██╔══██╗██╔════╝████╗░██║╚══██╔══╝██╔══██╗██╔══██╗░░
*░░██║░░██║█████╗░░██║░░╚═╝█████╗░░██╔██╗██║░░░██║░░░██████╔╝███████║░░
*░░██║░░██║██╔══╝░░██║░░██╗██╔══╝░░██║╚████║░░░██║░░░██╔══██╗██╔══██║░░
*░░██████╔╝███████╗╚█████╔╝███████╗██║░╚███║░░░██║░░░██║░░██║██║░░██║░░
*░░╚═════╝░╚══════╝░╚════╝░╚══════╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝░░
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*░░░░░░░░░░░░░██╗░░░░░░░██╗░█████╗░██████╗░██╗░░░░░██████╗░░░░░░░░░░░░░
*░░░░░░░░░░░░░██║░░██╗░░██║██╔══██╗██╔══██╗██║░░░░░██╔══██╗░░░░░░░░░░░░
*░░░░░░░░░░░░░╚██╗████╗██╔╝██║░░██║██████╔╝██║░░░░░██║░░██║░░░░░░░░░░░░
*░░░░░░░░░░░░░░████╔═████║░██║░░██║██╔══██╗██║░░░░░██║░░██║░░░░░░░░░░░░
*░░░░░░░░░░░░░░╚██╔╝░╚██╔╝░╚█████╔╝██║░░██║███████╗██████╔╝░░░░░░░░░░░░
*░░░░░░░░░░░░░░░╚═╝░░░╚═╝░░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░░░░░░░░░░░░░
*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
*
*/
pragma solidity ^0.8.7;
/**
* @dev Interfaces
*/
interface IDEXFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IDEXRouter {
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 swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IPancakeswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
/**
* @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);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
}
contract DecentraWorld_Multichain is Context, IERC20, IERC20Metadata, Ownable {
using SafeMath for uint256;
// DecentraWorld - $DEWO
uint256 _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
// Mapping
mapping (string => uint) txTaxes;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
mapping (address => bool) public excludeFromTax;
mapping (address => bool) public exclueFromMaxTx;
// Addresses Of Tax Receivers
address public daoandfarmingAddress;
address public marketingAddress;
address public developmentAddress;
address public coreteamAddress;
// Address of the bridge controling the mint/burn of the cross-chain
address public MPC;
// taxes for differnet levels
struct TaxLevels {
uint taxDiscount;
uint amount;
}
struct DEWOTokenTax {
uint forMarketing;
uint forCoreTeam;
uint forDevelopment;
uint forDAOAndFarming;
}
struct TxLimit {
uint buyMaxTx;
uint sellMaxTx;
uint txcooldown;
mapping(address => uint) buys;
mapping(address => uint) sells;
mapping(address => uint) lastTx;
}
mapping (uint => TaxLevels) taxTiers;
TxLimit txSettings;
IDEXRouter public router;
address public pair;
constructor() {
_name = "DecentraWorld";
_symbol = "$DEWO";
_decimals = 18;
//Temporary Tax Receivers
daoandfarmingAddress = msg.sender;
marketingAddress = 0x5d5a0368b8C383c45c625a7241473A1a4F61eA4E;
developmentAddress = 0xdA9f5e831b7D18c35CA7778eD271b4d4f3bE183E;
coreteamAddress = 0x797BD28BaE691B21e235E953043337F4794Ff9DB;
// Exclude From Taxes By Default
excludeFromTax[msg.sender] = true;
excludeFromTax[daoandfarmingAddress] = true;
excludeFromTax[marketingAddress] = true;
excludeFromTax[developmentAddress] = true;
excludeFromTax[coreteamAddress] = true;
// Exclude From MaxTx By Default
exclueFromMaxTx[msg.sender] = true;
exclueFromMaxTx[daoandfarmingAddress] = true;
exclueFromMaxTx[marketingAddress] = true;
exclueFromMaxTx[developmentAddress] = true;
exclueFromMaxTx[coreteamAddress] = true;
// Cross-Chain Bridge Temp Settings
MPC = msg.sender;
// Transaction taxes apply solely on swaps (buys/sells)
// Tier 1 - Default Buy Fee [6% Total]
// Tier 2 - Buy Fee [3% Total]
// Tier 3 - Buy Fee [0% Total]
//
// Automatically set the default transactions taxes
// [Tier 1: 6% Buy Fee]
txTaxes["marketingBuyTax"] = 3; // [3%] DAO, Governance, Farming Pools
txTaxes["developmentBuyTax"] = 1; // [1%] Marketing Fee
txTaxes["coreteamBuyTax"] = 1; // [1%] Development Fee
txTaxes["daoandfarmingBuyTax"] = 1; // [1%] DecentraWorld's Core-Team
// [Tier 1: 10% Sell Fee]
txTaxes["marketingSellTax"] = 4; // 4% DAO, Governance, Farming Pools
txTaxes["developmentSellTax"] = 3; // 3% Marketing Fee
txTaxes["coreteamSellTax"] = 1; // 1% Development Fee
txTaxes["daoandfarmingSellTax"] = 2; // 2% DecentraWorld's Core-Team
/*
Buy Transaction Tax - 3 tiers:
*** Must buy these amounts to qualify
Tier 1: 6%/10% (0+ $DEWO balance)
Tier 2: 3%/8% (100K+ $DEWO balance)
Tier 3: 0%/6% (400K+ $DEWO balance)
Sell Transaction Tax - 3 tiers:
*** Must hold these amounts to qualify
Tier 1: 6%/10% (0+ $DEWO balance)
Tier 2: 3%/8% (150K+ $DEWO balance)
Tier 3: 0%/6% (300K+ $DEWO balance)
Tax Re-distribution Buys (6%/3%/0%):
DAO Fund/Farming: 3% | 1% | 0%
Marketing Budget: 1% | 1% | 0%
Development Fund: 1% | 0% | 0%
Core-Team: 1% | 1% | 0%
Tax Re-distribution Sells (10%/8%/6%):
DAO Fund/Farming: 4% | 3% | 3%
Marketing Budget: 3% | 2% | 1%
Development Fund: 1% | 1% | 1%
Core-Team: 2% | 2% | 1%
The community can disable the holder rewards fee and migrate that
fee to the rewards/staking pool. This can be done via the Governance portal.
*/
// Default Tax Tiers & Discounts
// Get a 50% discount on purchase tax taxes
taxTiers[0].taxDiscount = 50;
// When buying over 0.1% of total supply (100,000 $DEWO)
taxTiers[0].amount = 100000 * (10 ** decimals());
// Get a 100% discount on purchase tax taxes
taxTiers[1].taxDiscount = 99;
// When buying over 0.4% of total supply (400,000 $DEWO)
taxTiers[1].amount = 400000 * (10 ** decimals());
// Get a 20% discount on sell tax taxes
taxTiers[2].taxDiscount = 20;
// When holding over 0.15% of total supply (150,000 $DEWO)
taxTiers[2].amount = 150000 * (10 ** decimals());
// Get a 40% discount on sell tax taxes
taxTiers[3].taxDiscount = 40;
// When holding over 0.3% of total supply (300,000 $DEWO)
taxTiers[3].amount = 300000 * (10 ** decimals());
// Default txcooldown limit in minutes
txSettings.txcooldown = 30 minutes;
// Default buy limit: 1.25% of total supply
txSettings.buyMaxTx = _totalSupply.div(80);
// Default sell limit: 0.25% of total supply
txSettings.sellMaxTx = _totalSupply.div(800);
/**
Removed from the cross-chain $DEWO token, the pair settings were replaced with a function,
and the mint function of 100,000,000 $DEWO to deployer was replaced with 0. Since this token is
a cross-chain token and not the native EVM chain where $DEWO was deployed (BSC) then there's no need
in any additional supply. The Multichain.org bridge will call burn/mint functions accordingly.
---
// Create a PancakeSwap (DEX) Pair For $DEWO
// This will be used to track the price of $DEWO & charge taxes to all pool buys/sells
address WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; // Wrapped BNB on Binance Smart Chain
address _router = 0x10ED43C718714eb63d5aA57B78B54704E256024E; // PancakeSwap Router (ChainID: 56 = BSC)
router = IDEXRouter(_router);
pair = IDEXFactory(router.factory()).createPair(WBNB, address(this));
_allowances[address(this)][address(router)] = _totalSupply;
approve(_router, _totalSupply);
// Send 100,000,000 $DEWO tokens to the dev (one time only)
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
*/
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
// onlyAuth = allow MPC contract address to call certain functions
// The MPC = Multichain bridge contract of each chain
modifier onlyAuth() {
require(msg.sender == mmpc(), "DecentraWorld: FORBIDDEN");
_;
}
function mmpc() public view returns (address) {
return MPC;
}
// This can only be done once by the deployer, once the MPC is set only the MPC can call this function again.
function setMPC(address _setmpc) external onlyAuth {
MPC = _setmpc;
}
// Mint will be used when individuals cross-chain $DEWO from one chain to another
function mint(address to, uint256 amount) external onlyAuth returns (bool) {
_mint(to, amount);
return true;
}
// The burn function will be used to burn tokens that were cross-chained into another EVM chain
function burn(address from, uint256 amount) external onlyAuth returns (bool) {
require(from != address(0), "DecentraWorld: address(0x0)");
_burn(from, amount);
return true;
}
function Swapin(bytes32 txhash, address account, uint256 amount) public onlyAuth returns (bool) {
_mint(account, amount);
emit LogSwapin(txhash, account, amount);
return true;
}
function Swapout(uint256 amount, address bindaddr) public returns (bool) {
require(bindaddr != address(0), "DecentraWorld: address(0x0)");
_burn(msg.sender, amount);
emit LogSwapout(msg.sender, bindaddr, amount);
return true;
}
event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount);
event LogSwapout(address indexed account, address indexed bindaddr, uint amount);
// Set the router & native token of each chain to tax the correct LP POOL of $DEWO
// This will always be the most popular DEX on the chain + its native token.
function setDEXPAIR(address _nativetoken, address _nativerouter) external onlyOwner {
// Create a DEX Pair For $DEWO
// This will be used to track the price of $DEWO & charge taxes to all pool buys/sells
router = IDEXRouter(_nativerouter);
pair = IDEXFactory(router.factory()).createPair(_nativetoken, address(this));
_allowances[address(this)][address(router)] = _totalSupply;
approve(_nativerouter, _totalSupply);
}
// Set Buy Taxes
event BuyTaxes(
uint _daoandfarmingBuyTax,
uint _coreteamBuyTax,
uint _developmentBuyTax,
uint _marketingBuyTax
);
function setBuyTaxes(
uint _daoandfarmingBuyTax,
uint _coreteamBuyTax,
uint _developmentBuyTax,
uint _marketingBuyTax
// Hardcoded limitation to the maximum tax fee per address
// Maximum tax for each buys/sells: 6% max tax per tax receiver, 24% max tax total
) external onlyOwner {
require(_daoandfarmingBuyTax <= 6, "DAO & Farming tax is above 6%!");
require(_coreteamBuyTax <= 6, "Core-Team Buy tax is above 6%!");
require(_developmentBuyTax <= 6, "Development Fund tax is above 6%!");
require(_marketingBuyTax <= 6, "Marketing tax is above 6%!");
txTaxes["daoandfarmingBuyTax"] = _daoandfarmingBuyTax;
txTaxes["coreteamBuyTax"] = _coreteamBuyTax;
txTaxes["developmentBuyTax"] = _developmentBuyTax;
txTaxes["marketingBuyTax"] = _marketingBuyTax;
emit BuyTaxes(
_daoandfarmingBuyTax,
_coreteamBuyTax,
_developmentBuyTax,
_marketingBuyTax
);
}
// Set Sell Taxes
event SellTaxes(
uint _daoandfarmingSellTax,
uint _coreteamSellTax,
uint _developmentSellTax,
uint _marketingSellTax
);
function setSellTaxes(
uint _daoandfarmingSellTax,
uint _coreteamSellTax,
uint _developmentSellTax,
uint _marketingSellTax
// Hardcoded limitation to the maximum tax fee per address
// Maximum tax for buys/sells: 6% max tax per tax receiver, 24% max tax total
) external onlyOwner {
require(_daoandfarmingSellTax <= 6, "DAO & Farming tax is above 6%!");
require(_coreteamSellTax <= 6, "Core-team tax is above 6%!");
require(_developmentSellTax <= 6, "Development tax is above 6%!");
require(_marketingSellTax <= 6, "Marketing tax is above 6%!");
txTaxes["daoandfarmingSellTax"] = _daoandfarmingSellTax;
txTaxes["coreteamSellTax"] = _coreteamSellTax;
txTaxes["developmentSellTax"] = _developmentSellTax;
txTaxes["marketingSellTax"] = _marketingSellTax;
emit SellTaxes(
_daoandfarmingSellTax,
_coreteamSellTax,
_developmentSellTax,
_marketingSellTax
);
}
// Displays a list of all current taxes
function getSellTaxes() public view returns(
uint marketingSellTax,
uint developmentSellTax,
uint coreteamSellTax,
uint daoandfarmingSellTax
) {
return (
txTaxes["marketingSellTax"],
txTaxes["developmentSellTax"],
txTaxes["coreteamSellTax"],
txTaxes["daoandfarmingSellTax"]
);
}
// Displays a list of all current taxes
function getBuyTaxes() public view returns(
uint marketingBuyTax,
uint developmentBuyTax,
uint coreteamBuyTax,
uint daoandfarmingBuyTax
) {
return (
txTaxes["marketingBuyTax"],
txTaxes["developmentBuyTax"],
txTaxes["coreteamBuyTax"],
txTaxes["daoandfarmingBuyTax"]
);
}
// Set the DAO and Farming Tax Receiver Address (daoandfarmingAddress)
function setDAOandFarmingAddress(address _daoandfarmingAddress) external onlyOwner {
daoandfarmingAddress = _daoandfarmingAddress;
}
// Set the Marketing Tax Receiver Address (marketingAddress)
function setMarketingAddress(address _marketingAddress) external onlyOwner {
marketingAddress = _marketingAddress;
}
// Set the Development Tax Receiver Address (developmentAddress)
function setDevelopmentAddress(address _developmentAddress) external onlyOwner {
developmentAddress = _developmentAddress;
}
// Set the Core-Team Tax Receiver Address (coreteamAddress)
function setCoreTeamAddress(address _coreteamAddress) external onlyOwner {
coreteamAddress = _coreteamAddress;
}
// Exclude an address from tax
function setExcludeFromTax(address _address, bool _value) external onlyOwner {
excludeFromTax[_address] = _value;
}
// Exclude an address from maximum transaction limit
function setExclueFromMaxTx(address _address, bool _value) external onlyOwner {
exclueFromMaxTx[_address] = _value;
}
// Set Buy Tax Tiers
function setBuyTaxTiers(uint _discount1, uint _amount1, uint _discount2, uint _amount2) external onlyOwner {
require(_discount1 > 0 && _discount1 < 100 && _discount2 > 0 && _discount2 < 100 && _amount1 > 0 && _amount2 > 0, "Values have to be bigger than zero!");
taxTiers[0].taxDiscount = _discount1;
taxTiers[0].amount = _amount1;
taxTiers[1].taxDiscount = _discount2;
taxTiers[1].amount = _amount2;
}
// Set Sell Tax Tiers
function setSellTaxTiers(uint _discount3, uint _amount3, uint _discount4, uint _amount4) external onlyOwner {
require(_discount3 > 0 && _discount3 < 100 && _discount4 > 0 && _discount4 < 100 && _amount3 > 0 && _amount4 > 0, "Values have to be bigger than zero!");
taxTiers[2].taxDiscount = _discount3;
taxTiers[2].amount = _amount3;
taxTiers[3].taxDiscount = _discount4;
taxTiers[3].amount = _amount4;
}
// Get Buy Tax Tiers
function getBuyTaxTiers() public view returns(uint discount1, uint amount1, uint discount2, uint amount2) {
return (taxTiers[0].taxDiscount, taxTiers[0].amount, taxTiers[1].taxDiscount, taxTiers[1].amount);
}
// Get Sell Tax Tiers
function getSellTaxTiers() public view returns(uint discount3, uint amount3, uint discount4, uint amount4) {
return (taxTiers[2].taxDiscount, taxTiers[2].amount, taxTiers[3].taxDiscount, taxTiers[3].amount);
}
// Set Transaction Settings: Max Buy Limit, Max Sell Limit, Cooldown Limit.
function setTxSettings(uint _buyMaxTx, uint _sellMaxTx, uint _txcooldown) external onlyOwner {
require(_buyMaxTx >= _totalSupply.div(200), "Buy transaction limit is too low!"); // 0.5%
require(_sellMaxTx >= _totalSupply.div(400), "Sell transaction limit is too low!"); // 0.25%
require(_txcooldown <= 4 minutes, "Cooldown should be 4 minutes or less!");
txSettings.buyMaxTx = _buyMaxTx;
txSettings.sellMaxTx = _sellMaxTx;
txSettings.txcooldown = _txcooldown;
}
// Get Max Transaction Settings: Max Buy, Max Sell, Cooldown Limit.
function getTxSettings() public view returns(uint buyMaxTx, uint sellMaxTx, uint txcooldown) {
return (txSettings.buyMaxTx, txSettings.sellMaxTx, txSettings.txcooldown);
}
// Check Buy Limit During A Cooldown (used in _transfer)
function checkBuyTxLimit(address _sender, uint256 _amount) internal view {
require(
exclueFromMaxTx[_sender] == true ||
txSettings.buys[_sender].add(_amount) < txSettings.buyMaxTx,
"Buy transaction limit reached!"
);
}
// Check Sell Limit During A Cooldown (used in _transfer)
function checkSellTxLimit(address _sender, uint256 _amount) internal view {
require(
exclueFromMaxTx[_sender] == true ||
txSettings.sells[_sender].add(_amount) < txSettings.sellMaxTx,
"Sell transaction limit reached!"
);
}
// Saves the recent buys & sells during a cooldown (used in _transfer)
function setRecentTx(bool _isSell, address _sender, uint _amount) internal {
if(txSettings.lastTx[_sender].add(txSettings.txcooldown) < block.timestamp) {
_isSell ? txSettings.sells[_sender] = _amount : txSettings.buys[_sender] = _amount;
} else {
_isSell ? txSettings.sells[_sender] += _amount : txSettings.buys[_sender] += _amount;
}
txSettings.lastTx[_sender] = block.timestamp;
}
// Get the recent buys, sells, and the last transaction
function getRecentTx(address _address) public view returns(uint buys, uint sells, uint lastTx) {
return (txSettings.buys[_address], txSettings.sells[_address], txSettings.lastTx[_address]);
}
// Get $DEWO Token Price In BNB
function getTokenPrice(uint _amount) public view returns(uint) {
IPancakeswapV2Pair pcsPair = IPancakeswapV2Pair(pair);
IERC20 token1 = IERC20(pcsPair.token1());
(uint Res0, uint Res1,) = pcsPair.getReserves();
uint res0 = Res0*(10**token1.decimals());
return((_amount.mul(res0)).div(Res1));
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] -= amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token taxes, 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
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
uint marketingFee;
uint developmentFee;
uint coreteamFee;
uint daoandfarmingFee;
uint taxDiscount;
bool hasTaxes = true;
// Buys from PancakeSwap's $DEWO pool
if(from == pair) {
checkBuyTxLimit(to, amount);
setRecentTx(false, to, amount);
marketingFee = txTaxes["marketingBuyTax"];
developmentFee = txTaxes["developmentBuyTax"];
coreteamFee = txTaxes["coreteamBuyTax"];
daoandfarmingFee = txTaxes["daoandfarmingBuyTax"];
// Transaction Tax Tiers 2 & 3 - Discounted Rate
if(amount >= taxTiers[0].amount && amount < taxTiers[1].amount) {
taxDiscount = taxTiers[0].taxDiscount;
} else if(amount >= taxTiers[1].amount) {
taxDiscount = taxTiers[1].taxDiscount;
}
}
// Sells from PancakeSwap's $DEWO pool
else if(to == pair) {
checkSellTxLimit(from, amount);
setRecentTx(true, from, amount);
marketingFee = txTaxes["marketingSellTax"];
developmentFee = txTaxes["developmentSellTax"];
coreteamFee = txTaxes["coreteamSellTax"];
daoandfarmingFee = txTaxes["daoandfarmingSellTax"];
// Calculate the balance after this transaction
uint newBalanceAmount = fromBalance.sub(amount);
// Transaction Tax Tiers 2 & 3 - Discounted Rate
if(newBalanceAmount >= taxTiers[2].amount && newBalanceAmount < taxTiers[3].amount) {
taxDiscount = taxTiers[2].taxDiscount;
} else if(newBalanceAmount >= taxTiers[3].amount) {
taxDiscount = taxTiers[3].taxDiscount;
}
}
unchecked {
_balances[from] = fromBalance - amount;
}
if(excludeFromTax[to] || excludeFromTax[from]) {
hasTaxes = false;
}
// Calculate taxes if this wallet is not excluded and buys/sells from $DEWO's PCS pair pool
if(hasTaxes && (to == pair || from == pair)) {
DEWOTokenTax memory DEWOTokenTaxes;
DEWOTokenTaxes.forDAOAndFarming = amount.mul(daoandfarmingFee).mul(100 - taxDiscount).div(10000);
DEWOTokenTaxes.forDevelopment = amount.mul(developmentFee).mul(100 - taxDiscount).div(10000);
DEWOTokenTaxes.forCoreTeam = amount.mul(coreteamFee).mul(100 - taxDiscount).div(10000);
DEWOTokenTaxes.forMarketing = amount.mul(marketingFee).mul(100 - taxDiscount).div(10000);
// Calculate total taxes and deduct from the transfered amount
uint totalTaxes =
DEWOTokenTaxes.forDAOAndFarming
.add(DEWOTokenTaxes.forDevelopment)
.add(DEWOTokenTaxes.forCoreTeam)
.add(DEWOTokenTaxes.forMarketing);
amount = amount.sub(totalTaxes);
// Pay DAO And Farming Taxes
_balances[daoandfarmingAddress] += DEWOTokenTaxes.forDAOAndFarming;
emit Transfer(from, daoandfarmingAddress, DEWOTokenTaxes.forDAOAndFarming);
// Pay Development Fund Taxes
_balances[developmentAddress] += DEWOTokenTaxes.forDevelopment;
emit Transfer(from, developmentAddress, DEWOTokenTaxes.forDevelopment);
// Pay Core-Team Taxes
_balances[coreteamAddress] += DEWOTokenTaxes.forCoreTeam;
emit Transfer(from, coreteamAddress, DEWOTokenTaxes.forCoreTeam);
// Pay Marketing Taxes
_balances[marketingAddress] += DEWOTokenTaxes.forMarketing;
emit Transfer(from, marketingAddress, DEWOTokenTaxes.forMarketing);
}
_balances[to] += amount;
emit Transfer(from, to, 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 Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
} | The burn function will be used to burn tokens that were cross-chained into another EVM chain | function burn(address from, uint256 amount) external onlyAuth returns (bool) {
require(from != address(0), "DecentraWorld: address(0x0)");
_burn(from, amount);
return true;
}
| 14,413,846 |
/*
Copyright 2017-2018 RigoBlock, Rigo Investment Sagl.
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.
*/
/**
* Faucet smart contract for RigoBlock protocol
* allows users to receive erc20Basic tokens
* Inspired by https://github.com/AvocadoNetwork
*/
pragma solidity 0.5.0;
import { ERC20Face as Token } from "../../tokens/ERC20/ERC20Face.sol";
import { Owned as Owned } from "../../utils/Owned/Owned.sol";
/// @title Faucet - Allows to automatically distribute GRGs.
/// @author David Fava - <[email protected]>
contract Faucet is Owned {
/*
* EVENTS
*/
event Deposit(address indexed sender, uint256 value);
event OneTokenSent(address indexed receiver);
event FaucetOn(bool status);
event FaucetOff(bool status);
uint256 constant oneToken = 1000000000000000000;
uint256 constant twentyFourHours = 24 hours;
string public faucetName;
Token public tokenInstance;
bool public faucetStatus;
mapping(address => uint256) status;
/*
* MODIFIERS
*/
modifier faucetOn() {
require(faucetStatus,"Faucet has to be on");
_;
}
modifier faucetOff() {
require(!faucetStatus, "Faucet has to be off");
_;
}
/// @dev Contract constructor
/// @param _tokenInstance address of ERC20Basic token
/// @param _faucetName sets the name for the faucet
constructor(address _tokenInstance, string memory _faucetName)
public
{
tokenInstance = Token(_tokenInstance);
faucetName = _faucetName;
faucetStatus = true;
emit FaucetOn(faucetStatus);
}
/*
* CORE FUNCTIONS
*/
/// @dev send 1000 Token with a minimum time lock of 1 hour
/// @return bool on success
function drip1Token()
external
faucetOn
returns (bool success)
{
require(!checkStatus(msg.sender),"Required too early.");
updateStatus(msg.sender, twentyFourHours);
tokenInstance.transfer(msg.sender, oneToken);
emit OneTokenSent(msg.sender);
return true;
}
/// @dev turn faucet on
/// @return bool on success
function turnFaucetOn()
external
onlyOwner
faucetOff
returns (bool success)
{
faucetStatus = true;
emit FaucetOn(faucetStatus);
return true;
}
/// @dev turn faucet off
/// @return bool on success
function turnFaucetOff()
external
onlyOwner
faucetOn
returns (bool success)
{
faucetStatus = false;
emit FaucetOff(faucetStatus);
return true;
}
/// @dev allow withdrawal from the owner
/// @return bool on success
function withdraw(
uint _value
)
external
onlyOwner
returns
(bool success)
{
require(tokenInstance.transfer(msg.sender, _value),"Cannot withdraw.");
return true;
}
/*
* INTERNAL FUNCTIONS
*/
/// @dev locks and unlocks account based on time range
/// @param _address of msg.sender
/// @return bool of current lock status of address
function checkStatus(address _address)
internal
view
returns (bool)
{
//check if first time address is requesting
if(status[_address] == 0) {
return false;
}
//if not first time check the timeLock
else {
// solium-disable-next-line security/no-block-members
if(block.timestamp >= status[_address]) {
return false;
}
else {
return true;
}
}
}
/// @dev updates timeLock for account
/// @param _address of msg.sender
/// @param _timelock of sender address
/// @return bool on success
function updateStatus(address _address, uint256 _timelock)
internal
returns (bool)
{ // solium-disable-next-line security/no-block-members
status[_address] = block.timestamp + _timelock;
return true;
}
}
| turn faucet off return bool on success | function turnFaucetOff()
external
onlyOwner
faucetOn
returns (bool success)
{
faucetStatus = false;
emit FaucetOff(faucetStatus);
return true;
}
| 2,508,825 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
pragma experimental ABIEncoderV2;
import "../strategy-base.sol";
import "../../../lib/balancer-vault.sol";
contract StrategyBalancerWmaticUsdcWethBalLp is StrategyBase {
// Token addresses
address public vault = 0xBA12222222228d8Ba445958a75a0704d566BF2C8;
bytes32 public poolId = 0x0297e37f1873d2dab4487aa67cd56b58e2f27875000100000000000000000002;
address public bal = 0x9a71012B13CA4d3D0Cdc72A177DF3ef03b0E76A3;
address public token0 = wmatic;
address public token1 = 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174; // usdc
address public token2 = weth;
address public token3 = bal;
// How much BAL tokens to keep?
uint256 public keepReward = 0;
uint256 public constant keepRewardMax = 10000;
// pool deposit fee
uint256 public depositFee = 0;
address _lp = 0x0297e37f1873D2DAb4487Aa67cD56B58E2F27875;
constructor(
address _governance,
address _strategist,
address _controller,
address _timelock
)
public
StrategyBase(
_lp,
_governance,
_strategist,
_controller,
_timelock
)
{
}
function getName() external override pure returns (string memory) {
return "StrategyBalancerWmaticUsdcWethBalLp";
}
function balanceOfPool() public override view returns (uint256) {
return 0;
}
function getHarvestable() external virtual view returns (uint256) {
return IERC20(bal).balanceOf(address(this));
}
// **** Setters ****
function deposit() public override {
}
function _withdrawSome(uint256 _amount)
internal
override
returns (uint256)
{
return _amount;
}
// **** Setters ****
function setKeepReward(uint256 _keepReward) external {
require(msg.sender == timelock, "!timelock");
keepReward = _keepReward;
}
// **** State Mutations ****
function harvest() public override onlyBenevolent {
uint256 _rewardBalance = IERC20(bal).balanceOf(address(this));
if (_rewardBalance > 0) {
// 10% is locked up for future gov
uint256 _keepReward = _rewardBalance.mul(keepReward).div(keepRewardMax);
IERC20(bal).safeTransfer(
IController(controller).treasury(),
_keepReward
);
}
uint256 remainingRewardBalance = IERC20(bal).balanceOf(address(this));
if (remainingRewardBalance == 0) {
return;
}
// allow Uniswap to sell our reward
IERC20(bal).safeApprove(vault, 0);
IERC20(bal).safeApprove(vault, remainingRewardBalance);
IAsset[] memory assets = new IAsset[](4);
assets[0] = IAsset(token0);
assets[1] = IAsset(token1);
assets[2] = IAsset(token2);
assets[3] = IAsset(token3);
IBVault.JoinKind joinKind = IBVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT;
uint256[] memory amountsIn = new uint256[](4);
amountsIn[0] = 0;
amountsIn[1] = 0;
amountsIn[2] = 0;
amountsIn[3] = remainingRewardBalance;
uint256 minAmountOut = 1;
bytes memory userData = abi.encode(joinKind, amountsIn, minAmountOut);
IBVault.JoinPoolRequest memory request;
request.assets = assets;
request.maxAmountsIn = amountsIn;
request.userData = userData;
request.fromInternalBalance = false;
uint256 _before = IERC20(want).balanceOf(address(this));
IBVault(vault).joinPool(
poolId,
address(this),
address(this),
request
);
uint256 _after = IERC20(want).balanceOf(address(this));
uint256 _amount = _after.sub(_before);
_distributePerformanceFeesBasedAmountAndDeposit(_amount);
}
}
| 10% is locked up for future gov | function harvest() public override onlyBenevolent {
uint256 _rewardBalance = IERC20(bal).balanceOf(address(this));
if (_rewardBalance > 0) {
uint256 _keepReward = _rewardBalance.mul(keepReward).div(keepRewardMax);
IERC20(bal).safeTransfer(
IController(controller).treasury(),
_keepReward
);
}
uint256 remainingRewardBalance = IERC20(bal).balanceOf(address(this));
if (remainingRewardBalance == 0) {
return;
}
IERC20(bal).safeApprove(vault, remainingRewardBalance);
IAsset[] memory assets = new IAsset[](4);
assets[0] = IAsset(token0);
assets[1] = IAsset(token1);
assets[2] = IAsset(token2);
assets[3] = IAsset(token3);
IBVault.JoinKind joinKind = IBVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT;
uint256[] memory amountsIn = new uint256[](4);
amountsIn[0] = 0;
amountsIn[1] = 0;
amountsIn[2] = 0;
amountsIn[3] = remainingRewardBalance;
uint256 minAmountOut = 1;
bytes memory userData = abi.encode(joinKind, amountsIn, minAmountOut);
IBVault.JoinPoolRequest memory request;
request.assets = assets;
request.maxAmountsIn = amountsIn;
request.userData = userData;
request.fromInternalBalance = false;
uint256 _before = IERC20(want).balanceOf(address(this));
IBVault(vault).joinPool(
poolId,
address(this),
address(this),
request
);
uint256 _after = IERC20(want).balanceOf(address(this));
uint256 _amount = _after.sub(_before);
_distributePerformanceFeesBasedAmountAndDeposit(_amount);
}
| 5,447,177 |
pragma solidity ^0.6.12;
abstract contract context10 { //inject NONSTANDARD NAMING
function _MSGSENDER9() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA1() 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;
}
}
interface ierc202 { //inject NONSTANDARD NAMING
function TOTALSUPPLY1() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF3(address ACCOUNT10) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER5(address RECIPIENT5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE1(address OWNER0, address SPENDER5) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE1(address SPENDER5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER2(address indexed FROM2, address indexed TO9, uint256 VALUE2); //inject NONSTANDARD NAMING
event APPROVAL10(address indexed OWNER0, address indexed SPENDER5, uint256 VALUE2); //inject NONSTANDARD NAMING
}
library safemath1 { //inject NONSTANDARD NAMING
function ADD4(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 C8 = A1 + B6; //inject NONSTANDARD NAMING
require(C8 >= A1, "SafeMath: addition overflow");
return C8;
}
function SUB5(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB5(A1, B6, "SafeMath: subtraction overflow");
}
function SUB5(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B6 <= A1, ERRORMESSAGE3);
uint256 C8 = A1 - B6; //inject NONSTANDARD NAMING
return C8;
}
function MUL6(uint256 A1, uint256 B6) 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 (A1 == 0) {
return 0;
}
uint256 C8 = A1 * B6; //inject NONSTANDARD NAMING
require(C8 / A1 == B6, "SafeMath: multiplication overflow");
return C8;
}
function DIV4(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV4(A1, B6, "SafeMath: division by zero");
}
function DIV4(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B6 > 0, ERRORMESSAGE3);
uint256 C8 = A1 / B6; //inject NONSTANDARD NAMING
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return C8;
}
function MOD8(uint256 A1, uint256 B6) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD8(A1, B6, "SafeMath: modulo by zero");
}
function MOD8(uint256 A1, uint256 B6, string memory ERRORMESSAGE3) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B6 != 0, ERRORMESSAGE3);
return A1 % B6;
}
}
library address5 { //inject NONSTANDARD NAMING
function ISCONTRACT2(address ACCOUNT10) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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 CODEHASH4; //inject NONSTANDARD NAMING
bytes32 ACCOUNTHASH1 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING
// solhint-disable-next-line no-inline-assembly
assembly { CODEHASH4 := extcodehash(ACCOUNT10) }
return (CODEHASH4 != ACCOUNTHASH1 && CODEHASH4 != 0x0);
}
function SENDVALUE0(address payable RECIPIENT5, uint256 AMOUNT9) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= AMOUNT9, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool SUCCESS3, ) = RECIPIENT5.call{ value: AMOUNT9 }(""); //inject NONSTANDARD NAMING
require(SUCCESS3, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL5(address TARGET4, bytes memory DATA2) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL5(TARGET4, DATA2, "Address: low-level call failed");
}
function FUNCTIONCALL5(address TARGET4, bytes memory DATA2, string memory ERRORMESSAGE3) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE9(TARGET4, DATA2, 0, ERRORMESSAGE3);
}
function FUNCTIONCALLWITHVALUE5(address TARGET4, bytes memory DATA2, uint256 VALUE2) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE5(TARGET4, DATA2, VALUE2, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE5(address TARGET4, bytes memory DATA2, uint256 VALUE2, string memory ERRORMESSAGE3) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= VALUE2, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE9(TARGET4, DATA2, VALUE2, ERRORMESSAGE3);
}
function _FUNCTIONCALLWITHVALUE9(address TARGET4, bytes memory DATA2, uint256 WEIVALUE7, string memory ERRORMESSAGE3) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT2(TARGET4), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool SUCCESS3, bytes memory RETURNDATA9) = TARGET4.call{ value: WEIVALUE7 }(DATA2); //inject NONSTANDARD NAMING
if (SUCCESS3) {
return RETURNDATA9;
} else {
// Look for revert reason and bubble it up if present
if (RETURNDATA9.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(RETURNDATA9)
revert(add(32, RETURNDATA9), returndata_size)
}
} else {
revert(ERRORMESSAGE3);
}
}
}
}
library safeerc206 { //inject NONSTANDARD NAMING
using safemath1 for uint256;
using address5 for address;
function SAFETRANSFER10(ierc202 TOKEN0, address TO9, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.TRANSFER5.selector, TO9, VALUE2));
}
function SAFETRANSFERFROM2(ierc202 TOKEN0, address FROM2, address TO9, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.TRANSFERFROM10.selector, FROM2, TO9, VALUE2));
}
function SAFEAPPROVE2(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) 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((VALUE2 == 0) || (TOKEN0.ALLOWANCE1(address(this), SPENDER5) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, VALUE2));
}
function SAFEINCREASEALLOWANCE0(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
uint256 NEWALLOWANCE4 = TOKEN0.ALLOWANCE1(address(this), SPENDER5).ADD4(VALUE2); //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, NEWALLOWANCE4));
}
function SAFEDECREASEALLOWANCE7(ierc202 TOKEN0, address SPENDER5, uint256 VALUE2) internal { //inject NONSTANDARD NAMING
uint256 NEWALLOWANCE4 = TOKEN0.ALLOWANCE1(address(this), SPENDER5).SUB5(VALUE2, "SafeERC20: decreased allowance below zero"); //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN7(TOKEN0, abi.encodeWithSelector(TOKEN0.APPROVE1.selector, SPENDER5, NEWALLOWANCE4));
}
function _CALLOPTIONALRETURN7(ierc202 TOKEN0, bytes memory DATA2) 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 RETURNDATA9 = address(TOKEN0).FUNCTIONCALL5(DATA2, "SafeERC20: low-level call failed"); //inject NONSTANDARD NAMING
if (RETURNDATA9.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(RETURNDATA9, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ownable2 is context10 { //inject NONSTANDARD NAMING
address private _OWNER5; //inject NONSTANDARD NAMING
event OWNERSHIPTRANSFERRED2(address indexed PREVIOUSOWNER0, address indexed NEWOWNER9); //inject NONSTANDARD NAMING
constructor () internal {
address MSGSENDER1 = _MSGSENDER9(); //inject NONSTANDARD NAMING
_OWNER5 = MSGSENDER1;
emit OWNERSHIPTRANSFERRED2(address(0), MSGSENDER1);
}
function OWNER2() public view returns (address) { //inject NONSTANDARD NAMING
return _OWNER5;
}
modifier ONLYOWNER10() { //inject NONSTANDARD NAMING
require(_OWNER5 == _MSGSENDER9(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP2() public virtual ONLYOWNER10 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED2(_OWNER5, address(0));
_OWNER5 = address(0);
}
function TRANSFEROWNERSHIP5(address NEWOWNER9) public virtual ONLYOWNER10 { //inject NONSTANDARD NAMING
require(NEWOWNER9 != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED2(_OWNER5, NEWOWNER9);
_OWNER5 = NEWOWNER9;
}
}
contract erc206 is context10, ierc202 { //inject NONSTANDARD NAMING
using safemath1 for uint256;
using address5 for address;
mapping (address => uint256) private _BALANCES2; //inject NONSTANDARD NAMING
mapping (address => mapping (address => uint256)) private _ALLOWANCES8; //inject NONSTANDARD NAMING
uint256 private _TOTALSUPPLY10; //inject NONSTANDARD NAMING
string private _NAME6; //inject NONSTANDARD NAMING
string private _SYMBOL5; //inject NONSTANDARD NAMING
uint8 private _DECIMALS1; //inject NONSTANDARD NAMING
constructor (string memory NAME8, string memory SYMBOL9) public { //inject NONSTANDARD NAMING
_NAME6 = NAME8;
_SYMBOL5 = SYMBOL9;
_DECIMALS1 = 18;
}
function NAME2() public view returns (string memory) { //inject NONSTANDARD NAMING
return _NAME6;
}
function SYMBOL4() public view returns (string memory) { //inject NONSTANDARD NAMING
return _SYMBOL5;
}
function DECIMALS0() public view returns (uint8) { //inject NONSTANDARD NAMING
return _DECIMALS1;
}
function TOTALSUPPLY1() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _TOTALSUPPLY10;
}
function BALANCEOF3(address ACCOUNT10) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _BALANCES2[ACCOUNT10];
}
function TRANSFER5(address RECIPIENT5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER10(_MSGSENDER9(), RECIPIENT5, AMOUNT9);
return true;
}
function ALLOWANCE1(address OWNER0, address SPENDER5) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _ALLOWANCES8[OWNER0][SPENDER5];
}
function APPROVE1(address SPENDER5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE0(_MSGSENDER9(), SPENDER5, AMOUNT9);
return true;
}
function TRANSFERFROM10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER10(SENDER1, RECIPIENT5, AMOUNT9);
_APPROVE0(SENDER1, _MSGSENDER9(), _ALLOWANCES8[SENDER1][_MSGSENDER9()].SUB5(AMOUNT9, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE2(address SPENDER5, uint256 ADDEDVALUE8) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE0(_MSGSENDER9(), SPENDER5, _ALLOWANCES8[_MSGSENDER9()][SPENDER5].ADD4(ADDEDVALUE8));
return true;
}
function DECREASEALLOWANCE5(address SPENDER5, uint256 SUBTRACTEDVALUE10) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE0(_MSGSENDER9(), SPENDER5, _ALLOWANCES8[_MSGSENDER9()][SPENDER5].SUB5(SUBTRACTEDVALUE10, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER10(address SENDER1, address RECIPIENT5, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(SENDER1 != address(0), "ERC20: transfer from the zero address");
require(RECIPIENT5 != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER8(SENDER1, RECIPIENT5, AMOUNT9);
_BALANCES2[SENDER1] = _BALANCES2[SENDER1].SUB5(AMOUNT9, "ERC20: transfer amount exceeds balance");
_BALANCES2[RECIPIENT5] = _BALANCES2[RECIPIENT5].ADD4(AMOUNT9);
emit TRANSFER2(SENDER1, RECIPIENT5, AMOUNT9);
}
function _MINT10(address ACCOUNT10, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(ACCOUNT10 != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER8(address(0), ACCOUNT10, AMOUNT9);
_TOTALSUPPLY10 = _TOTALSUPPLY10.ADD4(AMOUNT9);
_BALANCES2[ACCOUNT10] = _BALANCES2[ACCOUNT10].ADD4(AMOUNT9);
emit TRANSFER2(address(0), ACCOUNT10, AMOUNT9);
}
function _BURN5(address ACCOUNT10, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(ACCOUNT10 != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER8(ACCOUNT10, address(0), AMOUNT9);
_BALANCES2[ACCOUNT10] = _BALANCES2[ACCOUNT10].SUB5(AMOUNT9, "ERC20: burn amount exceeds balance");
_TOTALSUPPLY10 = _TOTALSUPPLY10.SUB5(AMOUNT9);
emit TRANSFER2(ACCOUNT10, address(0), AMOUNT9);
}
function _APPROVE0(address OWNER0, address SPENDER5, uint256 AMOUNT9) internal virtual { //inject NONSTANDARD NAMING
require(OWNER0 != address(0), "ERC20: approve from the zero address");
require(SPENDER5 != address(0), "ERC20: approve to the zero address");
_ALLOWANCES8[OWNER0][SPENDER5] = AMOUNT9;
emit APPROVAL10(OWNER0, SPENDER5, AMOUNT9);
}
function _SETUPDECIMALS6(uint8 DECIMALS_1) internal { //inject NONSTANDARD NAMING
_DECIMALS1 = DECIMALS_1;
}
function _BEFORETOKENTRANSFER8(address FROM2, address TO9, uint256 AMOUNT9) internal virtual { } //inject NONSTANDARD NAMING
}
// Moon Token with Governance.
contract moontoken3 is erc206("MOON.finance", "MOON"), ownable2 { //inject NONSTANDARD NAMING
function MINT7(address _TO2, uint256 _AMOUNT3) public ONLYOWNER10 { //inject NONSTANDARD NAMING
_MINT10(_TO2, _AMOUNT3);
}
} | inject NONSTANDARD NAMING | function ALLOWANCE1(address OWNER0, address SPENDER5) public view virtual override returns (uint256) { | 13,119,640 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
interface IERC20 {
function TOTALSUPPLY57() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF949(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER654(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE664(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE585(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM949(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER751(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL265(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER315() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA742() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address payable private _owner;
event OWNERSHIPTRANSFERRED883(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER315();
emit OWNERSHIPTRANSFERRED883(address(0), _owner);
}
function OWNER860() public view returns (address payable) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER684() { //inject NONSTANDARD NAMING
require(ISOWNER606(), "Ownable: caller is not the owner");
_;
}
function ISOWNER606() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER315() == _owner;
}
function RENOUNCEOWNERSHIP25() public ONLYOWNER684 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED883(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP520(address payable newOwner) public ONLYOWNER684 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP409(newOwner);
}
function _TRANSFEROWNERSHIP409(address payable newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED883(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 _totalSupply;
function TOTALSUPPLY57() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF949(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER654(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER957(_MSGSENDER315(), recipient, amount);
return true;
}
function ALLOWANCE664(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE585(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE29(_MSGSENDER315(), spender, amount);
return true;
}
function TRANSFERFROM949(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER957(sender, recipient, amount);
_APPROVE29(sender, _MSGSENDER315(), _allowances[sender][_MSGSENDER315()].SUB32(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE599(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE29(_MSGSENDER315(), spender, _allowances[_MSGSENDER315()][spender].ADD719(addedValue));
return true;
}
function DECREASEALLOWANCE607(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE29(_MSGSENDER315(), spender, _allowances[_MSGSENDER315()][spender].SUB32(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER957(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB32(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD719(amount);
emit TRANSFER751(sender, recipient, amount);
}
function _MINT290(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD719(amount);
_balances[account] = _balances[account].ADD719(amount);
emit TRANSFER751(address(0), account, amount);
}
function _BURN535(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB32(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB32(amount);
emit TRANSFER751(account, address(0), amount);
}
function _APPROVE29(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL265(owner, spender, amount);
}
function _BURNFROM245(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN535(account, amount);
_APPROVE29(account, _MSGSENDER315(), _allowances[account][_MSGSENDER315()].SUB32(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME844() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL911() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS364() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD719(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB32(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB32(a, b, "SafeMath: subtraction overflow");
}
function SUB32(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 MUL297(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV972(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV972(a, b, "SafeMath: division by zero");
}
function DIV972(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD124(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD124(a, b, "SafeMath: modulo by zero");
}
function MOD124(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
contract yeldTUSD is ERC20, ERC20Detailed, Ownable {
using SafeMath for uint256;
address public yTUSDAddress;
uint256 public initialPrice = 10000;
uint256 public fromYeldTTUSDoYeld = initialPrice * (10 ** 18); // Must be divided by 1e18 to get the real value
uint256 public fromTTUSDoYeldTUSDPrice = fromYeldTTUSDoYeld / initialPrice; // Must be divided by 1e18 to get the real value
uint256 public yeldReward = 1;
uint256 public yeldTUSDDecimals = 18; // The price has 18 decimals meaning you'll have to divide by 1e18 to get the real value
uint256 public lastPriceUpdate = now;
uint256 public priceUpdatePeriod = 1 days;
modifier ONLYYTUSD369 { //inject NONSTANDARD NAMING
require(msg.sender == yTUSDAddress);
_;
}
constructor() public payable ERC20Detailed("yeld TUSD", "yeldTUSD", 18) {}
function SETYTUSD712(address _yTUSDAddress) public ONLYOWNER684 { //inject NONSTANDARD NAMING
yTUSDAddress = _yTUSDAddress;
}
function MINT359(address _to, uint256 _amount) public ONLYYTUSD369 { //inject NONSTANDARD NAMING
_MINT290(_to, _amount);
}
function BURN815(address _to, uint256 _amount) public ONLYYTUSD369 { //inject NONSTANDARD NAMING
_BURN535(_to, _amount);
}
function CHANGEPRICERATIO481(uint256 _price) public ONLYOWNER684 { //inject NONSTANDARD NAMING
initialPrice = _price;
}
function CHECKIFPRICENEEDSUPDATING725() public view returns(bool) { //inject NONSTANDARD NAMING
return now >= lastPriceUpdate + priceUpdatePeriod;
}
function UPDATEPRICE820() public { //inject NONSTANDARD NAMING
require(CHECKIFPRICENEEDSUPDATING725(), "The price can't be updated yet");
// Update the price
uint256 daysPassed = (now - lastPriceUpdate) / 1 days;
yeldReward = daysPassed;
lastPriceUpdate = now;
fromYeldTTUSDoYeld = initialPrice.MUL297(10 ** yeldTUSDDecimals).DIV972(yeldReward);
fromTTUSDoYeldTUSDPrice = fromYeldTTUSDoYeld.DIV972(initialPrice);
}
function EXTRACTTOKENSIFSTUCK927(address _token, uint256 _amount) public ONLYOWNER684 { //inject NONSTANDARD NAMING
IERC20(_token).TRANSFER654(msg.sender, _amount);
}
function EXTRACTETHIFSTUCK461() public ONLYOWNER684 { //inject NONSTANDARD NAMING
OWNER860().transfer(address(this).balance);
}
} | inject NONSTANDARD NAMING | function _BURNFROM245(address account, uint256 amount) internal { | 12,740,432 |
pragma solidity 0.5.8;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title RelayRegistry
* @dev Singleton contract that registers a whitelist of relays accessed by the factory and smart wallets. Contract is owned by an external account for now but ownership should be transferred to a governance contract in the future.
*/
contract RelayRegistry is Ownable {
event AddedRelay(address relay);
event RemovedRelay(address relay);
mapping (address => bool) public relays;
constructor(address initialRelay) public {
relays[initialRelay] = true;
}
/**
* @dev Allows relay registry owner to add or remove a relay from the whitelist
* @param relay Address of the selected relay
* @param value True to add them to the whitelist, false to remove them
*/
function triggerRelay(address relay, bool value) onlyOwner public returns (bool) {
relays[relay] = value;
if(value) {
emit AddedRelay(relay);
} else {
emit RemovedRelay(relay);
}
return true;
}
}
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
}
/**
* @title Smart Wallet Contract
* @dev All functions of this contract should be called using delegatecall from the Proxy contract. This allows us to significantly reduce the deployment costs of smart wallets. All functions of this contract are executed in the context of Proxy contract.
*/
contract SmartWallet {
event Upgrade(address indexed newImplementation);
/**
* @dev Shared key value store. Data should be encoded and decoded using abi.encode()/abi.decode() by different functions. No data is actually stored in SmartWallet, instead everything is stored in the Proxy contract's context.
*/
mapping (bytes32 => bytes) public store;
modifier onlyRelay {
RelayRegistry registry = RelayRegistry(0x4360b517f5b3b2D4ddfAEDb4fBFc7eF0F48A4Faa);
require(registry.relays(msg.sender));
_;
}
modifier onlyOwner {
require(msg.sender == abi.decode(store["factory"], (address)) || msg.sender == abi.decode(store["owner"], (address)));
_;
}
/**
* @dev Function called once by Factory contract to initiate owner and nonce. This is necessary because we cannot pass arguments to a CREATE2-created contract without changing its address.
* @param owner Wallet Owner
*/
function initiate(address owner) public returns (bool) {
// this function can only be called by the factory
if(msg.sender != abi.decode(store["factory"], (address))) return false;
// store current owner in key store
store["owner"] = abi.encode(owner);
store["nonce"] = abi.encode(0);
return true;
}
/**
* @dev Same as above, but also applies a feee to a relayer address provided by the factory
* @param owner Wallet Owner
* @param relay Address of the relayer
* @param fee Fee paid to relayer in a token
* @param token Address of ERC20 contract in which fee will be denominated.
*/
function initiate(address owner, address relay, uint fee, address token) public returns (bool) {
require(initiate(owner), "internal initiate failed");
// Access ERC20 token
IERC20 tokenContract = IERC20(token);
// Send fee to relay
tokenContract.transfer(relay, fee);
return true;
}
/**
* @dev Relayed token transfer. Submitted by a relayer on behalf of the wallet owner.
* @param to Recipient address
* @param value Transfer amount
* @param fee Fee paid to the relayer
* @param tokenContract Address of the token contract used for both the transfer and the fees
* @param deadline Block number deadline for this signed message
*/
function pay(address to, uint value, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("pay", msg.sender, to, tokenContract, value, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
IERC20 token = IERC20(tokenContract);
store["nonce"] = abi.encode(currentNonce+1);
token.transfer(to, value);
token.transfer(msg.sender, fee);
return true;
}
/**
* @dev Direct token transfer. Submitted by the wallet owner
* @param to Recipient address
* @param value Transfer amount
* @param tokenContract Address of the token contract used for the transfer
*/
function pay(address to, uint value, address tokenContract) onlyOwner public returns (bool) {
IERC20 token = IERC20(tokenContract);
token.transfer(to, value);
return true;
}
/**
* @dev Same as above but allows batched transfers in multiple tokens
*/
function pay(address[] memory to, uint[] memory value, address[] memory tokenContract) onlyOwner public returns (bool) {
for (uint i; i < to.length; i++) {
IERC20 token = IERC20(tokenContract[i]);
token.transfer(to[i], value[i]);
}
return true;
}
/**
* @dev Internal function that executes a call to any contract
* @param contractAddress Address of the contract to call
* @param data calldata to send to contractAddress
* @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance
*/
function _execCall(address contractAddress, bytes memory data, uint256 msgValue) internal returns (bool result) {
// Warning: This executes an external contract call, may pose re-entrancy risk.
assembly {
result := call(gas, contractAddress, msgValue, add(data, 0x20), mload(data), 0, 0)
}
}
/**
* @dev Internal function that creates any contract
* @param data bytecode of the new contract
*/
function _execCreate(bytes memory data) internal returns (bool result) {
address deployedContract;
assembly {
deployedContract := create(0, add(data, 0x20), mload(data))
}
result = (deployedContract != address(0));
}
/**
* @dev Internal function that creates any contract using create2
* @param data bytecode of the new contract
* @param salt Create2 salt parameter
*/
function _execCreate2(bytes memory data, uint256 salt) internal returns (bool result) {
address deployedContract;
assembly {
deployedContract := create2(0, add(data, 0x20), mload(data), salt)
}
result = (deployedContract != address(0));
}
/**
* @dev Public function that allows the owner to execute a call to any contract
* @param contractAddress Address of the contract to call
* @param data calldata to send to contractAddress
* @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance
*/
function execCall(address contractAddress, bytes memory data, uint256 msgValue) onlyOwner public returns (bool) {
require(_execCall(contractAddress, data, msgValue));
return true;
}
/**
* @dev Public function that allows a relayer to execute a call to any contract on behalf of the owner
* @param contractAddress Address of the contract to call
* @param data calldata to send to contractAddress
* @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance
* @param fee Fee paid to the relayer
* @param tokenContract Address of the token contract used for the fee
* @param deadline Block number deadline for this signed message
*/
function execCall(address contractAddress, bytes memory data, uint256 msgValue, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCall", msg.sender, contractAddress, tokenContract, data, msgValue, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
IERC20 token = IERC20(tokenContract);
store["nonce"] = abi.encode(currentNonce+1);
token.transfer(msg.sender, fee);
require(_execCall(contractAddress, data, msgValue));
return true;
}
/**
* @dev Public function that allows the owner to create any contract
* @param data bytecode of the new contract
*/
function execCreate(bytes memory data) onlyOwner public returns (bool) {
require(_execCreate(data));
return true;
}
/**
* @dev Public function that allows a relayer to create any contract on behalf of the owner
* @param data new contract bytecode
* @param fee Fee paid to the relayer
* @param tokenContract Address of the token contract used for the fee
* @param deadline Block number deadline for this signed message
*/
function execCreate(bytes memory data, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCreate", msg.sender, tokenContract, data, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
require(_execCreate(data));
IERC20 token = IERC20(tokenContract);
store["nonce"] = abi.encode(currentNonce+1);
token.transfer(msg.sender, fee);
return true;
}
/**
* @dev Public function that allows the owner to create any contract using create2
* @param data bytecode of the new contract
* @param salt Create2 salt parameter
*/
function execCreate2(bytes memory data, uint salt) onlyOwner public returns (bool) {
require(_execCreate2(data, salt));
return true;
}
/**
* @dev Public function that allows a relayer to create any contract on behalf of the owner using create2
* @param data new contract bytecode
* @param salt Create2 salt parameter
* @param fee Fee paid to the relayer
* @param tokenContract Address of the token contract used for the fee
* @param deadline Block number deadline for this signed message
*/
function execCreate2(bytes memory data, uint salt, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCreate2", msg.sender, tokenContract, data, salt, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
require(_execCreate2(data, salt));
IERC20 token = IERC20(tokenContract);
store["nonce"] = abi.encode(currentNonce+1);
token.transfer(msg.sender, fee);
return true;
}
/**
* @dev Since all eth transfers to this contract are redirected to the owner. This is the only way for anyone, including the owner, to keep ETH on this contract.
*/
function depositEth() public payable {}
/**
* @dev Allows the owner to withdraw all ETH from the contract.
*/
function withdrawEth() public onlyOwner() {
address payable owner = abi.decode(store["owner"], (address));
owner.transfer(address(this).balance);
}
/**
* @dev Allows a relayer to change the address of the smart wallet implementation contract on behalf of the owner. New contract should have its own upgradability logic or Proxy will be stuck on it.
* @param implementation Address of the new implementation contract to replace this one.
* @param fee Fee paid to the relayer
* @param feeContract Address of the fee token contract
* @param deadline Block number deadline for this signed message
*/
function upgrade(address implementation, uint fee, address feeContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
address owner = abi.decode(store["owner"], (address));
require(owner == recover(keccak256(abi.encodePacked("upgrade", msg.sender, implementation, feeContract, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
store["nonce"] = abi.encode(currentNonce+1);
store["fallback"] = abi.encode(implementation);
IERC20 feeToken = IERC20(feeContract);
feeToken.transfer(msg.sender, fee);
emit Upgrade(implementation);
return true;
}
/**
* @dev Same as above, but activated directly by the owner.
* @param implementation Address of the new implementation contract to replace this one.
*/
function upgrade(address implementation) onlyOwner public returns (bool) {
store["fallback"] = abi.encode(implementation);
emit Upgrade(implementation);
return true;
}
/**
* @dev Internal function used to prefix hashes to allow for compatibility with signers such as Metamask
* @param messageHash Original hash
*/
function recover(bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
bytes memory prefix = "\x19Metacash Signed Message:\n32";
bytes32 prefixedMessageHash = keccak256(abi.encodePacked(prefix, messageHash));
return ecrecover(prefixedMessageHash, v, r, s);
}
}
/**
* @title Proxy
* @dev This contract is usually deployed as part of every user's first gasless transaction. It refers to a hardcoded address of the smart wallet contract and uses its functions via delegatecall.
*/
contract Proxy {
/**
* @dev Shared key value store. All data across different SmartWallet implementations is stored here. It also keeps storage across different upgrades.
*/
mapping (bytes32 => bytes) public store;
/**
* @dev The Proxy constructor adds the hardcoded address of SmartWallet and the address of the factory (from msg.sender) to the store for later transactions
*/
constructor() public {
// set implementation address in storage
store["fallback"] = abi.encode(0xEfc66C37a06507bCcABc0ce8d8bb5Ac4c1A2a8AA); // SmartWallet address
// set factory address in storage
store["factory"] = abi.encode(msg.sender);
}
/**
* @dev The fallback functions forwards everything as a delegatecall to the implementation SmartWallet contract
*/
function() external payable {
address impl = abi.decode(store["fallback"], (address));
assembly {
let ptr := mload(0x40)
// (1) copy incoming call data
calldatacopy(ptr, 0, calldatasize)
// (2) forward call to logic contract
let result := delegatecall(gas, impl, ptr, calldatasize, 0, 0)
let size := returndatasize
// (3) retrieve return data
returndatacopy(ptr, 0, size)
// (4) forward return data back to caller
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
/**
* @title Smart wallet factory
* @dev Singleton contract responsible for deploying new smart wallet instances
*/
contract Factory {
event Deployed(address indexed addr, address indexed owner);
modifier onlyRelay {
RelayRegistry registry = RelayRegistry(0x4360b517f5b3b2D4ddfAEDb4fBFc7eF0F48A4Faa); // Relay Registry address
require(registry.relays(msg.sender));
_;
}
/**
* @dev Internal function used for deploying smart wallets using create2
* @param owner Address of the wallet signer address (external account) associated with the smart wallet
*/
function deployCreate2(address owner) internal returns (address) {
bytes memory code = type(Proxy).creationCode;
address addr;
assembly {
// create2
addr := create2(0, add(code, 0x20), mload(code), owner)
// revert if contract was not created
if iszero(extcodesize(addr)) {revert(0, 0)}
}
return addr;
}
/**
* @dev Allows a relayer to deploy a smart wallet on behalf of a user
* @param fee Fee paid from the user's newly deployed smart wallet to the relay
* @param token Address of token contract for the fee
* @param deadline Block number deadline for this signed message
*/
function deployWallet(uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address) {
require(block.number <= deadline);
address signer = recover(keccak256(abi.encodePacked("deployWallet", msg.sender, token, tx.gasprice, fee, deadline)), v, r, s);
address addr = deployCreate2(signer);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.initiate(signer, msg.sender, fee, token));
emit Deployed(addr, signer);
return addr;
}
/**
* @dev Allows a relayer to deploy a smart wallet and send a token transfer on behalf of a user
* @param fee Fee paid from the user's newly deployed smart wallet to the relay
* @param token Address of token contract for the fee
* @param to Transfer recipient address
* @param value Transfer amount
* @param deadline Block number deadline for this signed message
*/
function deployWalletPay(uint fee, address token, address to, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) {
require(block.number <= deadline);
address signer = recover(keccak256(abi.encodePacked("deployWalletPay", msg.sender, token, to, tx.gasprice, fee, value, deadline)), v, r, s);
addr = deployCreate2(signer);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.initiate(signer, msg.sender, fee, token));
require(wallet.pay(to, value, token));
emit Deployed(addr, signer);
}
/**
* @dev Allows a user to directly deploy their own smart wallet
*/
function deployWallet() public returns (address) {
address addr = deployCreate2(msg.sender);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.initiate(msg.sender));
emit Deployed(addr, msg.sender);
return addr;
}
/**
* @dev Same as above, but also sends a transfer from the newly-deployed smart wallet
* @param token Address of the token contract for the transfer
* @param to Transfer recipient address
* @param value Transfer amount
*/
function deployWalletPay(address token, address to, uint value) public returns (address) {
address addr = deployCreate2(msg.sender);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.pay(to, value, token));
require(wallet.initiate(msg.sender));
emit Deployed(addr, msg.sender);
return addr;
}
/**
* @dev Allows user to deploy their wallet and execute a call operation to a foreign contract.
* @notice The order of wallet.execCall & wallet.initiate is important. It allows the fee to be paid after the execution is finished. This allows collect-call use cases.
* @param contractAddress Address of the contract to call
* @param data calldata to send to contractAddress
*/
function deployWalletExecCall(address contractAddress, bytes memory data) public payable returns (address) {
address addr = deployCreate2(msg.sender);
SmartWallet wallet = SmartWallet(uint160(addr));
if(msg.value > 0) {
wallet.depositEth.value(msg.value)();
}
require(wallet.execCall(contractAddress, data, msg.value));
require(wallet.initiate(msg.sender));
emit Deployed(addr, msg.sender);
return addr;
}
/**
* @dev Allows a relayer to deploy a wallet and execute a call operation to a foreign contract on behalf of a user.
* @param contractAddress Address of the contract to call
* @param data calldata to send to contractAddress
* @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance
* @param fee Fee paid to the relayer
* @param token Address of the token contract for the fee
* @param deadline Block number deadline for this signed message
*/
function deployWalletExecCall(address contractAddress, bytes memory data, uint msgValue, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) {
require(block.number <= deadline);
address signer = recover(keccak256(abi.encodePacked("deployWalletExecCall", msg.sender, token, contractAddress, data, msgValue, tx.gasprice, fee, deadline)), v, r, s);
addr = deployCreate2(signer);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.execCall(contractAddress, data, msgValue));
require(wallet.initiate(signer, msg.sender, fee, token));
emit Deployed(addr, signer);
}
/**
* @dev Allows user to deploy their wallet and deploy a new contract through their wallet
* @param data bytecode of the new contract
*/
function deployWalletExecCreate(bytes memory data) public returns (address) {
address addr = deployCreate2(msg.sender);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.execCreate(data));
require(wallet.initiate(msg.sender));
emit Deployed(addr, msg.sender);
return addr;
}
/**
* @dev Allows a relayer to deploy a wallet and deploy a new contract through the wallet on behalf of a user.
* @param data bytecode of the new contract
* @param fee Fee paid to the relayer
* @param token Address of the token contract for the fee
* @param deadline Block number deadline for this signed message
*/
function deployWalletExecCreate(bytes memory data, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) {
require(block.number <= deadline);
address signer = recover(keccak256(abi.encodePacked("deployWalletExecCreate", msg.sender, token, data, tx.gasprice, fee, deadline)), v, r, s);
addr = deployCreate2(signer);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.execCreate(data));
require(wallet.initiate(signer, msg.sender, fee, token));
emit Deployed(addr, signer);
}
/**
* @dev Allows user to deploy their wallet and deploy a new contract through their wallet using create2
* @param data bytecode of the new contract
* @param salt create2 salt parameter
*/
function deployWalletExecCreate2(bytes memory data, uint salt) public returns (address) {
address addr = deployCreate2(msg.sender);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.execCreate2(data, salt));
require(wallet.initiate(msg.sender));
emit Deployed(addr, msg.sender);
return addr;
}
/**
* @dev Allows a relayer to deploy a wallet and deploy a new contract through the wallet using create2 on behalf of a user.
* @param data bytecode of the new contract
* @param salt create2 salt parameter
* @param fee Fee paid to the relayer
* @param token Address of the token contract for the fee
* @param deadline Block number deadline for this signed message
*/
function deployWalletExecCreate2(bytes memory data, uint salt, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) {
require(block.number <= deadline);
address signer = recover(keccak256(abi.encodePacked("deployWalletExecCreate2", msg.sender, token, data, tx.gasprice, salt, fee, deadline)), v, r, s);
addr = deployCreate2(signer);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.execCreate2(data, salt));
require(wallet.initiate(signer, msg.sender, fee, token));
emit Deployed(addr, signer);
}
/**
* @dev Utility view function that allows clients to fetch a smart wallet address of any signer address
* @param owner Signer address
*/
function getCreate2Address(address owner) public view returns (address) {
bytes32 temp = keccak256(abi.encodePacked(bytes1(0xff), address(this), uint(owner), bytes32(keccak256(type(Proxy).creationCode))));
address ret;
uint mask = 2 ** 160 - 1;
assembly {
ret := and(temp, mask)
}
return ret;
}
/**
* @dev Utility view function that allows clients to fetch own smart wallet address
*/
function getCreate2Address() public view returns (address) {
return getCreate2Address(msg.sender);
}
/**
* @dev Utility view function that allows clients to query whether a signer's smart wallet can be deployed or has already been
* @param owner Signer address
*/
function canDeploy(address owner) public view returns (bool inexistent) {
address wallet = getCreate2Address(owner);
assembly {
inexistent := eq(extcodesize(wallet), 0)
}
}
/**
* @dev Utility view function that allows clients to query whether their signer's smart wallet can be deployed or has already been
*/
function canDeploy() public view returns (bool) {
return canDeploy(msg.sender);
}
/**
* @dev Internal function used to prefix hashes to allow for compatibility with signers such as Metamask
* @param messageHash Original hash
*/
function recover(bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
bytes memory prefix = "\x19Metacash Signed Message:\n32";
bytes32 prefixedMessageHash = keccak256(abi.encodePacked(prefix, messageHash));
return ecrecover(prefixedMessageHash, v, r, s);
}
}
| Public function that allows the owner to create any contract using create2 data bytecode of the new contract salt Create2 salt parameter/ | function execCreate2(bytes memory data, uint salt) onlyOwner public returns (bool) {
require(_execCreate2(data, salt));
return true;
}
| 6,353,877 |
//██████╗ █████╗ ██╗ █████╗ ██████╗ ██╗███╗ ██╗
//██╔══██╗██╔══██╗██║ ██╔══██╗██╔══██╗██║████╗ ██║
//██████╔╝███████║██║ ███████║██║ ██║██║██╔██╗ ██║
//██╔═══╝ ██╔══██║██║ ██╔══██║██║ ██║██║██║╚██╗██║
//██║ ██║ ██║███████╗██║ ██║██████╔╝██║██║ ╚████║
//╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝╚═╝ ╚═══╝
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
import "../utils/IERC20.sol";
import "../utils/SafeERC20.sol";
import "../utils/SafeMath.sol";
import {Errors} from "../utils/Errors.sol";
import "./utils/IDelegateRegistry.sol";
/** @title Snapshot token Delegator */
/// @author Paladin
contract SnapshotDelegator{
using SafeMath for uint;
using SafeERC20 for IERC20;
IDelegateRegistry public constant registry = IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446);
//Variables
/** @notice Address of the underlying token for this loan */
address public underlying;
/** @notice Amount of the underlying token in this loan */
uint public amount;
/** @notice Address of the borrower */
address public borrower;
/** @notice Address of the delegatee for the voting power */
address public delegatee;
/** @notice PalPool that created this loan */
address payable public motherPool;
/** @notice Amount of fees paid for this loan */
uint public feesAmount;
constructor(){
//Set up initial values
motherPool = payable(address(0xdead));
}
modifier motherPoolOnly() {
require(msg.sender == motherPool);
_;
}
/**
* @notice Starts the Loan and Delegate the voting Power to the Delegatee
* @dev Sets the amount values for the Loan, then delegate the voting power to the Delegatee
* @param _delegatee Address to delegate the voting power to
* @param _amount Amount of the underlying token for this loan
* @param _feesAmount Amount of fees (in the underlying token) paid by the borrower
* @return bool : Power Delagation success
*/
function initiate(
address _motherPool,
address _borrower,
address _underlying,
address _delegatee,
uint _amount,
uint _feesAmount
) external returns(bool){
require(motherPool == address(0));
motherPool = payable(_motherPool);
borrower = _borrower;
underlying = _underlying;
//Set up the borrowed amount and the amount of fees paid
amount = _amount;
feesAmount = _feesAmount;
delegatee = _delegatee;
//Delegate governance power : Snapshot version
//This is the Delegate Registry for Mainnet & Kovan
registry.setDelegate("", _delegatee);
return true;
}
/**
* @notice Increases the amount of fees paid to expand the Loan
* @dev Updates the feesAmount value for this Loan
* @param _newFeesAmount new Amount of fees paid by the Borrower
* @return bool : Expand success
*/
function expand(uint _newFeesAmount) external motherPoolOnly returns(bool){
feesAmount = feesAmount.add(_newFeesAmount);
return true;
}
/**
* @notice Closes a Loan, and returns the non-used fees to the Borrower
* @dev Return the non-used fees to the Borrower, the loaned tokens and the used fees to the PalPool, then destroy the contract
* @param _usedAmount Amount of fees to be used as interest for the Loan
*/
function closeLoan(uint _usedAmount) external motherPoolOnly {
IERC20 _underlying = IERC20(underlying);
//Return the remaining amount to the borrower
//Then return the borrowed amount and the used fees to the pool
uint _returnAmount = feesAmount.sub(_usedAmount);
uint _balance = _underlying.balanceOf(address(this));
uint _keepAmount = _balance.sub(_returnAmount);
if(_returnAmount > 0){
_underlying.safeTransfer(borrower, _returnAmount);
}
_underlying.safeTransfer(motherPool, _keepAmount);
registry.clearDelegate("");
//Destruct the contract, so it's not usable anymore
selfdestruct(motherPool);
}
/**
* @notice Kills a Loan, and reward the Killer a part of the fees of the Loan
* @dev Send the reward fees to the Killer, then return the loaned tokens and the fees to the PalPool, and destroy the contract
* @param _killer Address of the Loan Killer
* @param _killerRatio Percentage of the fees to reward to the killer (scale 1e18)
*/
function killLoan(address _killer, uint _killerRatio) external motherPoolOnly {
IERC20 _underlying = IERC20(underlying);
//Send the killer reward to the killer
//Then return the borrowed amount and the fees to the pool
uint _killerAmount = feesAmount.mul(_killerRatio).div(uint(1e18));
uint _balance = _underlying.balanceOf(address(this));
uint _poolAmount = _balance.sub(_killerAmount);
_underlying.safeTransfer(_killer, _killerAmount);
_underlying.safeTransfer(motherPool, _poolAmount);
registry.clearDelegate("");
//Destruct the contract, so it's not usable anymore
selfdestruct(motherPool);
}
/**
* @notice Change the voring power delegatee
* @dev Update the delegatee and delegate him the voting power
* @param _delegatee Address to delegate the voting power to
* @return bool : Power Delagation success
*/
function changeDelegatee(address _delegatee) external motherPoolOnly returns(bool){
delegatee = _delegatee;
//Delegate governance power : Snapshot version
//This is the Delegate Registry for Mainnet & Kovan
registry.setDelegate("", _delegatee);
return true;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.7.6;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "./IERC20.sol";
import "./SafeMath.sol";
import "./Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using 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");
}
}
}
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @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 addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
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 multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
//██████╗ █████╗ ██╗ █████╗ ██████╗ ██╗███╗ ██╗
//██╔══██╗██╔══██╗██║ ██╔══██╗██╔══██╗██║████╗ ██║
//██████╔╝███████║██║ ███████║██║ ██║██║██╔██╗ ██║
//██╔═══╝ ██╔══██║██║ ██╔══██║██║ ██║██║██║╚██╗██║
//██║ ██║ ██║███████╗██║ ██║██████╔╝██║██║ ╚████║
//╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝╚═╝ ╚═══╝
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
library Errors {
// Admin error
string public constant CALLER_NOT_ADMIN = '1'; // 'The caller must be the admin'
string public constant CALLER_NOT_CONTROLLER = '29'; // 'The caller must be the admin or the controller'
string public constant CALLER_NOT_ALLOWED_POOL = '30'; // 'The caller must be a palPool listed in the controller'
string public constant CALLER_NOT_MINTER = '31';
// ERC20 type errors
string public constant FAIL_TRANSFER = '2';
string public constant FAIL_TRANSFER_FROM = '3';
string public constant BALANCE_TOO_LOW = '4';
string public constant ALLOWANCE_TOO_LOW = '5';
string public constant SELF_TRANSFER = '6';
// PalPool errors
string public constant INSUFFICIENT_CASH = '9';
string public constant INSUFFICIENT_BALANCE = '10';
string public constant FAIL_DEPOSIT = '11';
string public constant FAIL_LOAN_INITIATE = '12';
string public constant FAIL_BORROW = '13';
string public constant ZERO_BORROW = '27';
string public constant BORROW_INSUFFICIENT_FEES = '23';
string public constant LOAN_CLOSED = '14';
string public constant NOT_LOAN_OWNER = '15';
string public constant LOAN_OWNER = '16';
string public constant FAIL_LOAN_EXPAND = '17';
string public constant NOT_KILLABLE = '18';
string public constant RESERVE_FUNDS_INSUFFICIENT = '19';
string public constant FAIL_MINT = '20';
string public constant FAIL_BURN = '21';
string public constant FAIL_WITHDRAW = '24';
string public constant FAIL_CLOSE_BORROW = '25';
string public constant FAIL_KILL_BORROW = '26';
string public constant ZERO_ADDRESS = '22';
string public constant INVALID_PARAMETERS = '28';
string public constant FAIL_LOAN_DELEGATEE_CHANGE = '32';
string public constant FAIL_LOAN_TOKEN_BURN = '33';
string public constant FEES_ACCRUED_INSUFFICIENT = '34';
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.8.0;
interface IDelegateRegistry {
function delegation(address delegator, bytes32 id) external view returns(address);
function setDelegate(bytes32 id, address delegate) external;
function clearDelegate(bytes32 id) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/**
* @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);
}
}
}
}
| Starts the Loan and Delegate the voting Power to the Delegatee Sets the amount values for the Loan, then delegate the voting power to the Delegatee _delegatee Address to delegate the voting power to _amount Amount of the underlying token for this loan _feesAmount Amount of fees (in the underlying token) paid by the borrower return bool : Power Delagation success/Set up the borrowed amount and the amount of fees paidDelegate governance power : Snapshot versionThis is the Delegate Registry for Mainnet & Kovan | function initiate(
address _motherPool,
address _borrower,
address _underlying,
address _delegatee,
uint _amount,
uint _feesAmount
) external returns(bool){
require(motherPool == address(0));
motherPool = payable(_motherPool);
borrower = _borrower;
underlying = _underlying;
amount = _amount;
feesAmount = _feesAmount;
delegatee = _delegatee;
registry.setDelegate("", _delegatee);
return true;
}
| 14,680,278 |
// SPDX-License-Identifier: MIT License
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @dev Contract module which provides access control
*
* the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* mapped to
* `onlyOwner`
*/
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);
}
}
contract CryptoChunksMarket is ReentrancyGuard, Pausable, Ownable {
IERC721 chunksContract; // instance of the CryptoChunks contract
struct Offer {
bool isForSale;
uint256 chunkIndex;
address seller;
uint256 minValue; // in ether
address onlySellTo;
}
struct Bid {
bool hasBid;
uint256 chunkIndex;
address bidder;
uint256 value;
}
// A record of chunks that are offered for sale at a specific minimum value, and perhaps to a specific person
mapping(uint256 => Offer) public chunksOfferedForSale;
// A record of the highest chunk bid
mapping(uint256 => Bid) public chunkBids;
// A record of pending ETH withdrawls by address
mapping(address => uint256) public pendingWithdrawals;
event ChunkOffered(
uint256 indexed chunkIndex,
uint256 minValue,
address indexed toAddress
);
event ChunkBidEntered(
uint256 indexed chunkIndex,
uint256 value,
address indexed fromAddress
);
event ChunkBidWithdrawn(
uint256 indexed chunkIndex,
uint256 value,
address indexed fromAddress
);
event ChunkBought(
uint256 indexed chunkIndex,
uint256 value,
address indexed fromAddress,
address indexed toAddress
);
event ChunkNoLongerForSale(uint256 indexed chunkIndex);
/* Initializes contract with an instance of CryptoChunks contract, and sets deployer as owner */
constructor(address initialChunksAddress) {
IERC721(initialChunksAddress).balanceOf(address(this));
chunksContract = IERC721(initialChunksAddress);
}
function pause() public whenNotPaused onlyOwner {
_pause();
}
function unpause() public whenPaused onlyOwner {
_unpause();
}
/* Returns the CryptoChunks contract address currently being used */
function chunksAddress() public view returns (address) {
return address(chunksContract);
}
/* Allows the owner of the contract to set a new CryptoChunks contract address */
function setChunksContract(address newChunksAddress) public onlyOwner {
chunksContract = IERC721(newChunksAddress);
}
/* Allows the owner of a CryptoChunks to stop offering it for sale */
function chunkNoLongerForSale(uint256 chunkIndex) public nonReentrant {
if (chunkIndex >= 10000) revert("token index not valid");
if (chunksContract.ownerOf(chunkIndex) != msg.sender)
revert("you are not the owner of this token");
chunksOfferedForSale[chunkIndex] = Offer(
false,
chunkIndex,
msg.sender,
0,
address(0x0)
);
emit ChunkNoLongerForSale(chunkIndex);
}
/* Allows a CryptoChunk owner to offer it for sale */
function offerChunkForSale(uint256 chunkIndex, uint256 minSalePriceInWei)
public
whenNotPaused
nonReentrant
{
if (chunkIndex >= 10000) revert("token index not valid");
if (chunksContract.ownerOf(chunkIndex) != msg.sender)
revert("you are not the owner of this token");
chunksOfferedForSale[chunkIndex] = Offer(
true,
chunkIndex,
msg.sender,
minSalePriceInWei,
address(0x0)
);
emit ChunkOffered(chunkIndex, minSalePriceInWei, address(0x0));
}
/* Allows a CryptoChunk owner to offer it for sale to a specific address */
function offerChunkForSaleToAddress(
uint256 chunkIndex,
uint256 minSalePriceInWei,
address toAddress
) public whenNotPaused nonReentrant {
if (chunkIndex >= 10000) revert();
if (chunksContract.ownerOf(chunkIndex) != msg.sender)
revert("you are not the owner of this token");
chunksOfferedForSale[chunkIndex] = Offer(
true,
chunkIndex,
msg.sender,
minSalePriceInWei,
toAddress
);
emit ChunkOffered(chunkIndex, minSalePriceInWei, toAddress);
}
/* Allows users to buy a CryptoChunk offered for sale */
function buyChunk(uint256 chunkIndex)
public
payable
whenNotPaused
nonReentrant
{
if (chunkIndex >= 10000) revert("token index not valid");
Offer memory offer = chunksOfferedForSale[chunkIndex];
if (!offer.isForSale) revert("chunk is not for sale"); // chunk not actually for sale
if (offer.onlySellTo != address(0x0) && offer.onlySellTo != msg.sender)
revert();
if (msg.value != offer.minValue) revert("not enough ether"); // Didn't send enough ETH
address seller = offer.seller;
if (seller == msg.sender) revert("seller == msg.sender");
if (seller != chunksContract.ownerOf(chunkIndex))
revert("seller no longer owner of chunk"); // Seller no longer owner of chunk
chunksOfferedForSale[chunkIndex] = Offer(
false,
chunkIndex,
msg.sender,
0,
address(0x0)
);
chunksContract.safeTransferFrom(seller, msg.sender, chunkIndex);
pendingWithdrawals[seller] += msg.value;
emit ChunkBought(chunkIndex, msg.value, seller, msg.sender);
// Check for the case where there is a bid from the new owner and refund it.
// Any other bid can stay in place.
Bid memory bid = chunkBids[chunkIndex];
if (bid.bidder == msg.sender) {
// Kill bid and refund value
pendingWithdrawals[msg.sender] += bid.value;
chunkBids[chunkIndex] = Bid(false, chunkIndex, address(0x0), 0);
}
}
/* Allows users to retrieve ETH from sales */
function withdraw() public nonReentrant {
uint256 amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
payable(msg.sender).transfer(amount);
}
/* Allows users to enter bids for any CryptoChunk */
function enterBidForChunk(uint256 chunkIndex)
public
payable
whenNotPaused
nonReentrant
{
if (chunkIndex >= 10000) revert("token index not valid");
if (chunksContract.ownerOf(chunkIndex) == msg.sender)
revert("you already own this chunk");
if (msg.value == 0) revert("cannot enter bid of zero");
Bid memory existing = chunkBids[chunkIndex];
if (msg.value <= existing.value) revert("your bid is too low");
if (existing.value > 0) {
// Refund the failing bid
pendingWithdrawals[existing.bidder] += existing.value;
}
chunkBids[chunkIndex] = Bid(true, chunkIndex, msg.sender, msg.value);
emit ChunkBidEntered(chunkIndex, msg.value, msg.sender);
}
/* Allows CryptoChunk owners to accept bids for their Chunks */
function acceptBidForChunk(uint256 chunkIndex, uint256 minPrice)
public
whenNotPaused
nonReentrant
{
if (chunkIndex >= 10000) revert("token index not valid");
if (chunksContract.ownerOf(chunkIndex) != msg.sender)
revert("you do not own this token");
address seller = msg.sender;
Bid memory bid = chunkBids[chunkIndex];
if (bid.value == 0) revert("cannot enter bid of zero");
if (bid.value < minPrice) revert("your bid is too low");
address bidder = bid.bidder;
if (seller == bidder) revert("you already own this token");
chunksOfferedForSale[chunkIndex] = Offer(
false,
chunkIndex,
bidder,
0,
address(0x0)
);
uint256 amount = bid.value;
chunkBids[chunkIndex] = Bid(false, chunkIndex, address(0x0), 0);
chunksContract.safeTransferFrom(msg.sender, bidder, chunkIndex);
pendingWithdrawals[seller] += amount;
emit ChunkBought(chunkIndex, bid.value, seller, bidder);
}
/* Allows bidders to withdraw their bids */
function withdrawBidForChunk(uint256 chunkIndex) public nonReentrant {
if (chunkIndex >= 10000) revert("token index not valid");
Bid memory bid = chunkBids[chunkIndex];
if (bid.bidder != msg.sender)
revert("the bidder is not message sender");
emit ChunkBidWithdrawn(chunkIndex, bid.value, msg.sender);
uint256 amount = bid.value;
chunkBids[chunkIndex] = Bid(false, chunkIndex, address(0x0), 0);
// Refund the bid money
payable(msg.sender).transfer(amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
pragma solidity >=0.8.0 <0.9.0;
// SPDX-License-Identifier: UNLICENSE
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "base64-sol/base64.sol";
import "./ToColor.sol";
import "./strings.sol";
contract SvgPunks {
function punkImage(uint16 index) public view returns (bytes memory) {}
function punkAttributes(uint16 index)
external
view
returns (string memory text)
{}
function punkImageSvg(uint16 index)
external
view
returns (string memory svg)
{}
}
contract CryptoChunks is ERC721, Ownable, ReentrancyGuard {
using Counters for Counters.Counter;
using Strings for uint16;
using Strings for uint256;
using ToColor for bytes3;
using strings for *;
uint256 private constant limit = 9999;
Counters.Counter private _tokenIds;
string _symbol = unicode"OϾ";
SvgPunks svgP;
bool private auctionStarted;
mapping(uint16 => bool) public isNormied;
mapping(uint256 => bytes3) public color;
string internal constant SVG_HEADER_NORMIE =
'<svg xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges" version="1.2" viewBox="0 0 24 24"';
// get Phunked (on-chain)
string internal constant SVG_HEADER =
'<svg xmlns="http://www.w3.org/2000/svg" shape-rendering="crispEdges" version="1.2" viewBox="0 0 24 24" transform="scale (-1, 1)" transform-origin="center"';
// larva labs has a foot fetish
string internal constant SVG_FOOTER = "</svg>";
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
constructor(address chainPunks)
ERC721("CryptoChunks, Phunks On-Chained!", _symbol)
{
svgP = SvgPunks(chainPunks);
transferOwnership(0xb010ca9Be09C382A9f31b79493bb232bCC319f01);
}
/**
* @notice Mint pricing scheme borrowed from Phunks.
*/
function getCostForMinting(uint256 _numToMint)
private
view
returns (uint256)
{
require(
_tokenIds.current() + _numToMint <= limit,
"There aren't that many left."
);
if (_numToMint == 1) {
return 0.02 ether;
} else if (_numToMint == 3) {
return 0.05 ether;
} else if (_numToMint == 5) {
return 0.07 ether;
} else if (_numToMint == 10) {
return 0.10 ether;
} else {
revert("Unsupported mint amount");
}
}
/**
* @notice Supporting tyranny isn't cheap. Flip to "punk" for 10 ETH
*/
function setNormied(uint16 index, bool isNormie) public payable {
require(msg.value >= 10 ether, "don't be cheap");
require(ownerOf(index) == msg.sender, "Not Owner");
isNormied[index] = isNormie;
}
/**
* @notice Change your BG color for 1 ETH.
*/
function randomizeBackground(uint16 index) public payable {
require(msg.value >= 1 ether, "don't be cheap");
require(ownerOf(index) == msg.sender, "Not Owner");
bytes32 predictableRandom = keccak256(
abi.encodePacked(
blockhash(block.number - 1),
msg.sender,
address(this),
index
)
);
color[index] =
bytes2(predictableRandom[0]) |
(bytes2(predictableRandom[1]) >> 8) |
(bytes3(predictableRandom[2]) >> 16);
}
/**
* @notice Sets a string value "normied" for use in JSON.
*/
function checkIsNormied(uint16 index) public view returns (string memory) {
if (isNormied[index] == true) {
string memory normie = "true";
return normie;
} else {
string memory normie = "false";
return normie;
}
}
/**
* @notice Improved version of CryptoPunks:Data, reduces gas significantly..
*/
function getPunkImage(uint16 index)
private
view
returns (string memory svg)
{
bytes memory pixels = svgP.punkImage(index);
if (isNormied[index] == true) {
svg = string(
abi.encodePacked(
SVG_HEADER_NORMIE,
' style="background-color:#',
color[index].toColor(),
'">'
)
);
} else {
svg = string(
abi.encodePacked(
SVG_HEADER,
' style="background-color:#',
color[index].toColor(),
'">'
)
);
}
bytes memory buffer = new bytes(8);
for (uint256 y = 0; y < 24; y++) {
for (uint256 x = 0; x < 24; x++) {
uint256 p = (y * 24 + x) * 4;
if (uint8(pixels[p + 3]) > 0) {
for (uint256 i = 0; i < 4; i++) {
uint8 value = uint8(pixels[p + i]);
buffer[i * 2 + 1] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
buffer[i * 2] = _HEX_SYMBOLS[value & 0xf];
}
svg = string(
abi.encodePacked(
svg,
'<rect x="',
x.toString(),
'" y="',
y.toString(),
'" width="1" height="1" fill="#',
string(buffer),
'"/>'
)
);
}
}
}
svg = string(abi.encodePacked(svg, SVG_FOOTER));
}
/**
* @notice Assemble these phunkers.
*/
// prettier-ignore
function constructTokenURI(uint16 id) private view returns (string memory) {
string memory _punkSVG = Base64.encode(bytes(getPunkImage(id)));
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
'OC',
' Phunk #',
id.toString(),
'", "attributes": "',
svgP.punkAttributes(id),
'", "color": "',
color[id].toColor(),
'", "normied": "',
checkIsNormied(id),
'", "image": "',
"data:image/svg+xml;base64,",
_punkSVG,
'"}'
)
)
)
)
);
}
/**
* @notice Type conversion, uint256 to uint16
*/
function convert(uint256 _a) private pure returns (uint16) {
return uint16(_a);
}
/**
* @notice Receives json from constructTokenURI
*/
// prettier-ignore
function tokenURI(uint256 _id)
public
view
override
returns (string memory)
{
require(_id <= limit, "non-existant");
require(_exists(_id), "not exist");
uint16 id = convert(_id);
return constructTokenURI(id);
}
/**
* @notice Mints 0id to owner, mints first 100 to owner.
*/
function initCollection() public payable onlyOwner {
require(_tokenIds.current() == 0, "only to init collection");
uint256 id0 = _tokenIds.current();
_mint(msg.sender, id0);
for (uint256 i = 0; i < 100; i++) {
_tokenIds.increment();
uint256 id = _tokenIds.current();
_mint(msg.sender, id);
bytes32 predictableRandom = keccak256(
abi.encodePacked(
blockhash(block.number - 1),
msg.sender,
address(this),
id
)
);
color[id] =
bytes2(predictableRandom[0]) |
(bytes2(predictableRandom[1]) >> 8) |
(bytes3(predictableRandom[2]) >> 16);
}
isNormied[0] = true;
}
/**
* @notice Mints item, assigns pseudo-random color value.
*/
function mintItem(uint256 _numToMint) public payable nonReentrant {
require(_tokenIds.current() < limit, "mint limit met");
require(auctionStarted == true, "auction not started");
require(
_tokenIds.current() + _numToMint <= limit,
"There aren't that many left."
);
uint256 costForMinting = getCostForMinting(_numToMint);
require(
msg.value >= costForMinting,
"Too little sent, please send more eth."
);
for (uint256 i = 0; i < _numToMint; i++) {
_tokenIds.increment();
uint256 id = _tokenIds.current();
_mint(msg.sender, id);
bytes32 predictableRandom = keccak256(
abi.encodePacked(
blockhash(block.number - 1),
msg.sender,
address(this),
id
)
);
color[id] =
bytes2(predictableRandom[0]) |
(bytes2(predictableRandom[1]) >> 8) |
(bytes3(predictableRandom[2]) >> 16);
}
}
function withdraw() public onlyOwner {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer failed.");
}
function startAuction() public onlyOwner {
auctionStarted = true;
}
function pauseAuction() public onlyOwner {
auctionStarted = false;
}
/**
* @notice Fallback for accepting eth
*/
receive() external payable {}
}
// 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;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE_ENCODE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
// read 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// write 4 characters
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
function decode(string memory _data) internal pure returns (bytes memory) {
bytes memory data = bytes(_data);
if (data.length == 0) return new bytes(0);
require(data.length % 4 == 0, "invalid base64 decoder input");
// load the table into memory
bytes memory table = TABLE_DECODE;
// every 4 characters represent 3 bytes
uint256 decodedLen = (data.length / 4) * 3;
// add some extra buffer at the end required for the writing
bytes memory result = new bytes(decodedLen + 32);
assembly {
// padding with '='
let lastBytes := mload(add(data, mload(data)))
if eq(and(lastBytes, 0xFF), 0x3d) {
decodedLen := sub(decodedLen, 1)
if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
decodedLen := sub(decodedLen, 1)
}
}
// set the actual output length
mstore(result, decodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 4 characters at a time
for {} lt(dataPtr, endPtr) {}
{
// read 4 characters
dataPtr := add(dataPtr, 4)
let input := mload(dataPtr)
// write 3 bytes
let output := add(
add(
shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
add(
shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
and(mload(add(tablePtr, and( input , 0xFF))), 0xFF)
)
)
mstore(resultPtr, shl(232, output))
resultPtr := add(resultPtr, 3)
}
}
return result;
}
}
library ToColor {
bytes16 internal constant ALPHABET = "0123456789abcdef";
function toColor(bytes3 value) internal pure returns (string memory) {
bytes memory buffer = new bytes(6);
for (uint256 i = 0; i < 3; i++) {
buffer[i * 2 + 1] = ALPHABET[uint8(value[i]) & 0xf];
buffer[i * 2] = ALPHABET[uint8(value[i] >> 4) & 0xf];
}
return string(buffer);
}
}
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
pragma solidity >=0.8.0 <0.9.0;
library strings {
struct slice {
uint256 _len;
uint256 _ptr;
}
function memcpy(
uint256 dest,
uint256 src,
uint256 len
) private pure {
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint256 mask = 256**(32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint256 ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint256 retptr;
assembly {
retptr := add(ret, 32)
}
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint256 l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint256 ptr = self._ptr - 31;
uint256 end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly {
b := and(mload(ptr), 0xFF)
}
if (b < 0x80) {
ptr += 1;
} else if (b < 0xE0) {
ptr += 2;
} else if (b < 0xF0) {
ptr += 3;
} else if (b < 0xF8) {
ptr += 4;
} else if (b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune)
internal
pure
returns (slice memory)
{
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint256 l;
uint256 b;
// Load the first byte of the rune into the LSBs of b
assembly {
b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF)
}
if (b < 0x80) {
l = 1;
} else if (b < 0xE0) {
l = 2;
} else if (b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self)
internal
pure
returns (slice memory ret)
{
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint256 ret) {
if (self._len == 0) {
return 0;
}
uint256 word;
uint256 length;
uint256 divisor = 2**248;
// Load the rune into the MSBs of b
assembly {
word := mload(mload(add(self, 32)))
}
uint256 b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if (b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if (b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint256 i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle)
internal
pure
returns (bool)
{
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(
keccak256(selfptr, length),
keccak256(needleptr, length)
)
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle)
internal
pure
returns (slice memory)
{
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(
keccak256(selfptr, length),
keccak256(needleptr, length)
)
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle)
internal
pure
returns (bool)
{
if (self._len < needle._len) {
return false;
}
uint256 selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(
keccak256(selfptr, length),
keccak256(needleptr, length)
)
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle)
internal
pure
returns (slice memory)
{
if (self._len < needle._len) {
return self;
}
uint256 selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(
keccak256(selfptr, length),
keccak256(needleptr, length)
)
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(
uint256 selflen,
uint256 selfptr,
uint256 needlelen,
uint256 needleptr
) private pure returns (uint256) {
uint256 ptr = selfptr;
uint256 idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2**(8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly {
needledata := and(mload(needleptr), mask)
}
uint256 end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly {
ptrdata := and(mload(ptr), mask)
}
while (ptrdata != needledata) {
if (ptr >= end) return selfptr + selflen;
ptr++;
assembly {
ptrdata := and(mload(ptr), mask)
}
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly {
hash := keccak256(needleptr, needlelen)
}
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly {
testHash := keccak256(ptr, needlelen)
}
if (hash == testHash) return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(
uint256 selflen,
uint256 selfptr,
uint256 needlelen,
uint256 needleptr
) private pure returns (uint256) {
uint256 ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2**(8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly {
needledata := and(mload(needleptr), mask)
}
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly {
ptrdata := and(mload(ptr), mask)
}
while (ptrdata != needledata) {
if (ptr <= selfptr) return selfptr;
ptr--;
assembly {
ptrdata := and(mload(ptr), mask)
}
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly {
hash := keccak256(needleptr, needlelen)
}
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly {
testHash := keccak256(ptr, needlelen)
}
if (hash == testHash) return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle)
internal
pure
returns (slice memory)
{
uint256 ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle)
internal
pure
returns (slice memory)
{
uint256 ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(
slice memory self,
slice memory needle,
slice memory token
) internal pure returns (slice memory) {
uint256 ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle)
internal
pure
returns (slice memory token)
{
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(
slice memory self,
slice memory needle,
slice memory token
) internal pure returns (slice memory) {
uint256 ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle)
internal
pure
returns (slice memory token)
{
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle)
internal
pure
returns (uint256 cnt)
{
uint256 ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) +
needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr =
findPtr(
self._len - (ptr - self._ptr),
ptr,
needle._len,
needle._ptr
) +
needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle)
internal
pure
returns (bool)
{
return
rfindPtr(self._len, self._ptr, needle._len, needle._ptr) !=
self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other)
internal
pure
returns (string memory)
{
string memory ret = new string(self._len + other._len);
uint256 retptr;
assembly {
retptr := add(ret, 32)
}
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts)
internal
pure
returns (string memory)
{
if (parts.length == 0) return "";
uint256 length = self._len * (parts.length - 1);
for (uint256 i = 0; i < parts.length; i++) length += parts[i]._len;
string memory ret = new string(length);
uint256 retptr;
assembly {
retptr := add(ret, 32)
}
for (uint256 i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
} | Counts the number of nonoverlapping occurrences of `needle` in `self`. self The slice to search. needle The text to search for in `self`. return The number of occurrences of `needle` found in `self`./ | function count(slice memory self, slice memory needle)
internal
pure
returns (uint256 cnt)
{
uint256 ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) +
needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr =
findPtr(
self._len - (ptr - self._ptr),
ptr,
needle._len,
needle._ptr
) +
needle._len;
}
}
| 443,030 |
./full_match/5/0xf9eF10daDc9b525c35Ae7dC45bfc8700a5e0F68b/sources/contracts/Records.sol | Store treatment summary details patient_id patient patient id _treatment treatment _date_treatment date of treatment _doctor_id id of doctor treated _hospital_id id of hospital _discharge date of discharge _follow_up date for follow up / | function treatment_summary(
uint256 patient_id,
string memory _treatment,
string memory _date_treatment,
uint256 _doctor_id,
uint256 _hospital_id,
string memory _discharge,
string memory _follow_up
) public isOwner {
tr.treatment = _treatment;
tr.date_treatment = _date_treatment;
tr.doctor_id = _doctor_id;
tr.hospital_id = _hospital_id;
tr.discharge = _discharge;
tr.follow_up = _follow_up;
treatment[patient_id] = tr;
}
| 7,076,882 |
/**
*Submitted for verification at Etherscan.io on 2019-12-02
*/
pragma solidity ^0.5.4;
/**
* ERC20 contract interface.
*/
contract ERC20 {
function totalSupply() public view returns (uint);
function decimals() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
}
/**
* @title Module
* @dev Interface for a module.
* A module MUST implement the addModule() method to ensure that a wallet with at least one module
* can never end up in a "frozen" state.
* @author Julien Niset - <[email protected]>
*/
interface Module {
function init(BaseWallet _wallet) external;
function addModule(BaseWallet _wallet, Module _module) external;
function recoverToken(address _token) external;
}
/**
* @title BaseWallet
* @dev Simple modular wallet that authorises modules to call its invoke() method.
* Based on https://gist.github.com/Arachnid/a619d31f6d32757a4328a428286da186 by
* @author Julien Niset - <[email protected]>
*/
contract BaseWallet {
address public implementation;
address public owner;
mapping (address => bool) public authorised;
mapping (bytes4 => address) public enabled;
uint public modules;
function init(address _owner, address[] calldata _modules) external;
function authoriseModule(address _module, bool _value) external;
function enableStaticCall(address _module, bytes4 _method) external;
function setOwner(address _newOwner) external;
function invoke(address _target, uint _value, bytes calldata _data) external returns (bytes memory _result);
function() external payable;
}
/**
* @title ModuleRegistry
* @dev Registry of authorised modules.
* Modules must be registered before they can be authorised on a wallet.
* @author Julien Niset - <[email protected]>
*/
contract ModuleRegistry {
function registerModule(address _module, bytes32 _name) external;
function deregisterModule(address _module) external;
function registerUpgrader(address _upgrader, bytes32 _name) external;
function deregisterUpgrader(address _upgrader) external;
function recoverToken(address _token) external;
function moduleInfo(address _module) external view returns (bytes32);
function upgraderInfo(address _upgrader) external view returns (bytes32);
function isRegisteredModule(address _module) external view returns (bool);
function isRegisteredModule(address[] calldata _modules) external view returns (bool);
function isRegisteredUpgrader(address _upgrader) external view returns (bool);
}
contract TokenPriceProvider {
mapping(address => uint256) public cachedPrices;
function getEtherValue(uint256 _amount, address _token) external view returns (uint256);
}
/**
* @title GuardianStorage
* @dev Contract storing the state of wallets related to guardians and lock.
* The contract only defines basic setters and getters with no logic. Only modules authorised
* for a wallet can modify its state.
* @author Julien Niset - <[email protected]>
* @author Olivier Van Den Biggelaar - <[email protected]>
*/
contract GuardianStorage {
function addGuardian(BaseWallet _wallet, address _guardian) external;
function revokeGuardian(BaseWallet _wallet, address _guardian) external;
function guardianCount(BaseWallet _wallet) external view returns (uint256);
function getGuardians(BaseWallet _wallet) external view returns (address[] memory);
function isGuardian(BaseWallet _wallet, address _guardian) external view returns (bool);
function setLock(BaseWallet _wallet, uint256 _releaseAfter) external;
function isLocked(BaseWallet _wallet) external view returns (bool);
function getLock(BaseWallet _wallet) external view returns (uint256);
function getLocker(BaseWallet _wallet) external view returns (address);
}
/**
* @title TransferStorage
* @dev Contract storing the state of wallets related to transfers (limit and whitelist).
* The contract only defines basic setters and getters with no logic. Only modules authorised
* for a wallet can modify its state.
* @author Julien Niset - <[email protected]>
*/
contract TransferStorage {
function setWhitelist(BaseWallet _wallet, address _target, uint256 _value) external;
function getWhitelist(BaseWallet _wallet, address _target) external view returns (uint256);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw 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;
}
/**
* @dev Returns ceil(a / b).
*/
function ceil(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
if(a % b == 0) {
return c;
}
else {
return c + 1;
}
}
}
/**
* @title BaseModule
* @dev Basic module that contains some methods common to all modules.
* @author Julien Niset - <[email protected]>
*/
contract BaseModule is Module {
// Empty calldata
bytes constant internal EMPTY_BYTES = "";
// The adddress of the module registry.
ModuleRegistry internal registry;
// The address of the Guardian storage
GuardianStorage internal guardianStorage;
/**
* @dev Throws if the wallet is locked.
*/
modifier onlyWhenUnlocked(BaseWallet _wallet) {
// solium-disable-next-line security/no-block-members
require(!guardianStorage.isLocked(_wallet), "BM: wallet must be unlocked");
_;
}
event ModuleCreated(bytes32 name);
event ModuleInitialised(address wallet);
constructor(ModuleRegistry _registry, GuardianStorage _guardianStorage, bytes32 _name) public {
registry = _registry;
guardianStorage = _guardianStorage;
emit ModuleCreated(_name);
}
/**
* @dev Throws if the sender is not the target wallet of the call.
*/
modifier onlyWallet(BaseWallet _wallet) {
require(msg.sender == address(_wallet), "BM: caller must be wallet");
_;
}
/**
* @dev Throws if the sender is not the owner of the target wallet or the module itself.
*/
modifier onlyWalletOwner(BaseWallet _wallet) {
require(msg.sender == address(this) || isOwner(_wallet, msg.sender), "BM: must be an owner for the wallet");
_;
}
/**
* @dev Throws if the sender is not the owner of the target wallet.
*/
modifier strictOnlyWalletOwner(BaseWallet _wallet) {
require(isOwner(_wallet, msg.sender), "BM: msg.sender must be an owner for the wallet");
_;
}
/**
* @dev Inits the module for a wallet by logging an event.
* The method can only be called by the wallet itself.
* @param _wallet The wallet.
*/
function init(BaseWallet _wallet) public onlyWallet(_wallet) {
emit ModuleInitialised(address(_wallet));
}
/**
* @dev Adds a module to a wallet. First checks that the module is registered.
* @param _wallet The target wallet.
* @param _module The modules to authorise.
*/
function addModule(BaseWallet _wallet, Module _module) external strictOnlyWalletOwner(_wallet) {
require(registry.isRegisteredModule(address(_module)), "BM: module is not registered");
_wallet.authoriseModule(address(_module), true);
}
/**
* @dev Utility method enbaling anyone to recover ERC20 token sent to the
* module by mistake and transfer them to the Module Registry.
* @param _token The token to recover.
*/
function recoverToken(address _token) external {
uint total = ERC20(_token).balanceOf(address(this));
ERC20(_token).transfer(address(registry), total);
}
/**
* @dev Helper method to check if an address is the owner of a target wallet.
* @param _wallet The target wallet.
* @param _addr The address.
*/
function isOwner(BaseWallet _wallet, address _addr) internal view returns (bool) {
return _wallet.owner() == _addr;
}
/**
* @dev Helper method to invoke a wallet.
* @param _wallet The target wallet.
* @param _to The target address for the transaction.
* @param _value The value of the transaction.
* @param _data The data of the transaction.
*/
function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) {
bool success;
// solium-disable-next-line security/no-call-value
(success, _res) = _wallet.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _to, _value, _data));
if(success && _res.length > 0) { //_res is empty if _wallet is an "old" BaseWallet that can't return output values
(_res) = abi.decode(_res, (bytes));
} else if (_res.length > 0) {
// solium-disable-next-line security/no-inline-assembly
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
} else if(!success) {
revert("BM: wallet invoke reverted");
}
}
}
/**
* @title RelayerModule
* @dev Base module containing logic to execute transactions signed by eth-less accounts and sent by a relayer.
* @author Julien Niset - <[email protected]>
*/
contract RelayerModule is BaseModule {
uint256 constant internal BLOCKBOUND = 10000;
mapping (address => RelayerConfig) public relayer;
struct RelayerConfig {
uint256 nonce;
mapping (bytes32 => bool) executedTx;
}
event TransactionExecuted(address indexed wallet, bool indexed success, bytes32 signedHash);
/**
* @dev Throws if the call did not go through the execute() method.
*/
modifier onlyExecute {
require(msg.sender == address(this), "RM: must be called via execute()");
_;
}
/* ***************** Abstract method ************************* */
/**
* @dev Gets the number of valid signatures that must be provided to execute a
* specific relayed transaction.
* @param _wallet The target wallet.
* @param _data The data of the relayed transaction.
* @return The number of required signatures.
*/
function getRequiredSignatures(BaseWallet _wallet, bytes memory _data) internal view returns (uint256);
/**
* @dev Validates the signatures provided with a relayed transaction.
* The method MUST throw if one or more signatures are not valid.
* @param _wallet The target wallet.
* @param _data The data of the relayed transaction.
* @param _signHash The signed hash representing the relayed transaction.
* @param _signatures The signatures as a concatenated byte array.
*/
function validateSignatures(BaseWallet _wallet, bytes memory _data, bytes32 _signHash, bytes memory _signatures) internal view returns (bool);
/* ************************************************************ */
/**
* @dev Executes a relayed transaction.
* @param _wallet The target wallet.
* @param _data The data for the relayed transaction
* @param _nonce The nonce used to prevent replay attacks.
* @param _signatures The signatures as a concatenated byte array.
* @param _gasPrice The gas price to use for the gas refund.
* @param _gasLimit The gas limit to use for the gas refund.
*/
function execute(
BaseWallet _wallet,
bytes calldata _data,
uint256 _nonce,
bytes calldata _signatures,
uint256 _gasPrice,
uint256 _gasLimit
)
external
returns (bool success)
{
uint startGas = gasleft();
bytes32 signHash = getSignHash(address(this), address(_wallet), 0, _data, _nonce, _gasPrice, _gasLimit);
require(checkAndUpdateUniqueness(_wallet, _nonce, signHash), "RM: Duplicate request");
require(verifyData(address(_wallet), _data), "RM: the wallet authorized is different then the target of the relayed data");
uint256 requiredSignatures = getRequiredSignatures(_wallet, _data);
if((requiredSignatures * 65) == _signatures.length) {
if(verifyRefund(_wallet, _gasLimit, _gasPrice, requiredSignatures)) {
if(requiredSignatures == 0 || validateSignatures(_wallet, _data, signHash, _signatures)) {
// solium-disable-next-line security/no-call-value
(success,) = address(this).call(_data);
refund(_wallet, startGas - gasleft(), _gasPrice, _gasLimit, requiredSignatures, msg.sender);
}
}
}
emit TransactionExecuted(address(_wallet), success, signHash);
}
/**
* @dev Gets the current nonce for a wallet.
* @param _wallet The target wallet.
*/
function getNonce(BaseWallet _wallet) external view returns (uint256 nonce) {
return relayer[address(_wallet)].nonce;
}
/**
* @dev Generates the signed hash of a relayed transaction according to ERC 1077.
* @param _from The starting address for the relayed transaction (should be the module)
* @param _to The destination address for the relayed transaction (should be the wallet)
* @param _value The value for the relayed transaction
* @param _data The data for the relayed transaction
* @param _nonce The nonce used to prevent replay attacks.
* @param _gasPrice The gas price to use for the gas refund.
* @param _gasLimit The gas limit to use for the gas refund.
*/
function getSignHash(
address _from,
address _to,
uint256 _value,
bytes memory _data,
uint256 _nonce,
uint256 _gasPrice,
uint256 _gasLimit
)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(byte(0x19), byte(0), _from, _to, _value, _data, _nonce, _gasPrice, _gasLimit))
));
}
/**
* @dev Checks if the relayed transaction is unique.
* @param _wallet The target wallet.
* @param _nonce The nonce
* @param _signHash The signed hash of the transaction
*/
function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) {
if(relayer[address(_wallet)].executedTx[_signHash] == true) {
return false;
}
relayer[address(_wallet)].executedTx[_signHash] = true;
return true;
}
/**
* @dev Checks that a nonce has the correct format and is valid.
* It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes.
* @param _wallet The target wallet.
* @param _nonce The nonce
*/
function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) {
if(_nonce <= relayer[address(_wallet)].nonce) {
return false;
}
uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128;
if(nonceBlock > block.number + BLOCKBOUND) {
return false;
}
relayer[address(_wallet)].nonce = _nonce;
return true;
}
/**
* @dev Recovers the signer at a given position from a list of concatenated signatures.
* @param _signedHash The signed hash
* @param _signatures The concatenated signatures.
* @param _index The index of the signature to recover.
*/
function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) {
uint8 v;
bytes32 r;
bytes32 s;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(_signatures, add(0x20,mul(0x41,_index))))
s := mload(add(_signatures, add(0x40,mul(0x41,_index))))
v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff)
}
require(v == 27 || v == 28);
return ecrecover(_signedHash, v, r, s);
}
/**
* @dev Refunds the gas used to the Relayer.
* For security reasons the default behavior is to not refund calls with 0 or 1 signatures.
* @param _wallet The target wallet.
* @param _gasUsed The gas used.
* @param _gasPrice The gas price for the refund.
* @param _gasLimit The gas limit for the refund.
* @param _signatures The number of signatures used in the call.
* @param _relayer The address of the Relayer.
*/
function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal {
uint256 amount = 29292 + _gasUsed; // 21000 (transaction) + 7620 (execution of refund) + 672 to log the event + _gasUsed
// only refund if gas price not null, more than 1 signatures, gas less than gasLimit
if(_gasPrice > 0 && _signatures > 1 && amount <= _gasLimit) {
if(_gasPrice > tx.gasprice) {
amount = amount * tx.gasprice;
}
else {
amount = amount * _gasPrice;
}
invokeWallet(address(_wallet), _relayer, amount, EMPTY_BYTES);
}
}
/**
* @dev Returns false if the refund is expected to fail.
* @param _wallet The target wallet.
* @param _gasUsed The expected gas used.
* @param _gasPrice The expected gas price for the refund.
*/
function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) {
if(_gasPrice > 0
&& _signatures > 1
&& (address(_wallet).balance < _gasUsed * _gasPrice || _wallet.authorised(address(this)) == false)) {
return false;
}
return true;
}
/**
* @dev Checks that the wallet address provided as the first parameter of the relayed data is the same
* as the wallet passed as the input of the execute() method.
@return false if the addresses are different.
*/
function verifyData(address _wallet, bytes memory _data) private pure returns (bool) {
require(_data.length >= 36, "RM: Invalid dataWallet");
address dataWallet;
// solium-disable-next-line security/no-inline-assembly
assembly {
//_data = {length:32}{sig:4}{_wallet:32}{...}
dataWallet := mload(add(_data, 0x24))
}
return dataWallet == _wallet;
}
/**
* @dev Parses the data to extract the method signature.
*/
function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) {
require(_data.length >= 4, "RM: Invalid functionPrefix");
// solium-disable-next-line security/no-inline-assembly
assembly {
prefix := mload(add(_data, 0x20))
}
}
}
/**
* @title OnlyOwnerModule
* @dev Module that extends BaseModule and RelayerModule for modules where the execute() method
* must be called with one signature frm the owner.
* @author Julien Niset - <[email protected]>
*/
contract OnlyOwnerModule is BaseModule, RelayerModule {
// bytes4 private constant IS_ONLY_OWNER_MODULE = bytes4(keccak256("isOnlyOwnerModule()"));
/**
* @dev Returns a constant that indicates that the module is an OnlyOwnerModule.
* @return The constant bytes4(keccak256("isOnlyOwnerModule()"))
*/
function isOnlyOwnerModule() external pure returns (bytes4) {
// return IS_ONLY_OWNER_MODULE;
return this.isOnlyOwnerModule.selector;
}
/**
* @dev Adds a module to a wallet. First checks that the module is registered.
* Unlike its overrided parent, this method can be called via the RelayerModule's execute()
* @param _wallet The target wallet.
* @param _module The modules to authorise.
*/
function addModule(BaseWallet _wallet, Module _module) external onlyWalletOwner(_wallet) {
require(registry.isRegisteredModule(address(_module)), "BM: module is not registered");
_wallet.authoriseModule(address(_module), true);
}
// *************** Implementation of RelayerModule methods ********************* //
// Overrides to use the incremental nonce and save some gas
function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 /* _signHash */) internal returns (bool) {
return checkAndUpdateNonce(_wallet, _nonce);
}
function validateSignatures(
BaseWallet _wallet,
bytes memory /* _data */,
bytes32 _signHash,
bytes memory _signatures
)
internal
view
returns (bool)
{
address signer = recoverSigner(_signHash, _signatures, 0);
return isOwner(_wallet, signer); // "OOM: signer must be owner"
}
function getRequiredSignatures(BaseWallet /* _wallet */, bytes memory /* _data */) internal view returns (uint256) {
return 1;
}
}
/**
* @title LimitManager
* @dev Module to manage a daily spending limit
* @author Julien Niset - <[email protected]>
*/
contract LimitManager is BaseModule {
// large limit when the limit can be considered disabled
uint128 constant private LIMIT_DISABLED = uint128(-1); // 3.40282366920938463463374607431768211455e+38
using SafeMath for uint256;
struct LimitManagerConfig {
// The daily limit
Limit limit;
// The current usage
DailySpent dailySpent;
}
struct Limit {
// the current limit
uint128 current;
// the pending limit if any
uint128 pending;
// when the pending limit becomes the current limit
uint64 changeAfter;
}
struct DailySpent {
// The amount already spent during the current period
uint128 alreadySpent;
// The end of the current period
uint64 periodEnd;
}
// wallet specific storage
mapping (address => LimitManagerConfig) internal limits;
// The default limit
uint256 public defaultLimit;
// *************** Events *************************** //
event LimitChanged(address indexed wallet, uint indexed newLimit, uint64 indexed startAfter);
// *************** Constructor ********************** //
constructor(uint256 _defaultLimit) public {
defaultLimit = _defaultLimit;
}
// *************** External/Public Functions ********************* //
/**
* @dev Inits the module for a wallet by setting the limit to the default value.
* @param _wallet The target wallet.
*/
function init(BaseWallet _wallet) public onlyWallet(_wallet) {
Limit storage limit = limits[address(_wallet)].limit;
if(limit.current == 0 && limit.changeAfter == 0) {
limit.current = uint128(defaultLimit);
}
}
// *************** Internal Functions ********************* //
/**
* @dev Changes the daily limit.
* The limit is expressed in ETH and the change is pending for the security period.
* @param _wallet The target wallet.
* @param _newLimit The new limit.
* @param _securityPeriod The security period.
*/
function changeLimit(BaseWallet _wallet, uint256 _newLimit, uint256 _securityPeriod) internal {
Limit storage limit = limits[address(_wallet)].limit;
// solium-disable-next-line security/no-block-members
uint128 current = (limit.changeAfter > 0 && limit.changeAfter < now) ? limit.pending : limit.current;
limit.current = current;
limit.pending = uint128(_newLimit);
// solium-disable-next-line security/no-block-members
limit.changeAfter = uint64(now.add(_securityPeriod));
// solium-disable-next-line security/no-block-members
emit LimitChanged(address(_wallet), _newLimit, uint64(now.add(_securityPeriod)));
}
/**
* @dev Disable the daily limit.
* The change is pending for the security period.
* @param _wallet The target wallet.
* @param _securityPeriod The security period.
*/
function disableLimit(BaseWallet _wallet, uint256 _securityPeriod) internal {
changeLimit(_wallet, LIMIT_DISABLED, _securityPeriod);
}
/**
* @dev Gets the current daily limit for a wallet.
* @param _wallet The target wallet.
* @return the current limit expressed in ETH.
*/
function getCurrentLimit(BaseWallet _wallet) public view returns (uint256 _currentLimit) {
Limit storage limit = limits[address(_wallet)].limit;
_currentLimit = uint256(currentLimit(limit.current, limit.pending, limit.changeAfter));
}
/**
* @dev Returns whether the daily limit is disabled for a wallet.
* @param _wallet The target wallet.
* @return true if the daily limit is disabled, false otherwise.
*/
function isLimitDisabled(BaseWallet _wallet) public view returns (bool _limitDisabled) {
uint256 currentLimit = getCurrentLimit(_wallet);
_limitDisabled = currentLimit == LIMIT_DISABLED;
}
/**
* @dev Gets a pending limit for a wallet if any.
* @param _wallet The target wallet.
* @return the pending limit (in ETH) and the time at chich it will become effective.
*/
function getPendingLimit(BaseWallet _wallet) external view returns (uint256 _pendingLimit, uint64 _changeAfter) {
Limit storage limit = limits[address(_wallet)].limit;
// solium-disable-next-line security/no-block-members
return ((now < limit.changeAfter)? (uint256(limit.pending), limit.changeAfter) : (0,0));
}
/**
* @dev Gets the amount of tokens that has not yet been spent during the current period.
* @param _wallet The target wallet.
* @return the amount of tokens (in ETH) that has not been spent yet and the end of the period.
*/
function getDailyUnspent(BaseWallet _wallet) external view returns (uint256 _unspent, uint64 _periodEnd) {
uint256 limit = getCurrentLimit(_wallet);
DailySpent storage expense = limits[address(_wallet)].dailySpent;
// solium-disable-next-line security/no-block-members
if(now > expense.periodEnd) {
_unspent = limit;
// solium-disable-next-line security/no-block-members
_periodEnd = uint64(now + 24 hours);
}
else {
_periodEnd = expense.periodEnd;
if(expense.alreadySpent < limit) {
_unspent = limit - expense.alreadySpent;
}
}
}
/**
* @dev Helper method to check if a transfer is within the limit.
* If yes the daily unspent for the current period is updated.
* @param _wallet The target wallet.
* @param _amount The amount for the transfer
*/
function checkAndUpdateDailySpent(BaseWallet _wallet, uint _amount) internal returns (bool) {
if(address(this).balance == 0) return true; //inject PRESENT ETHER
Limit storage limit = limits[address(_wallet)].limit;
uint128 current = currentLimit(limit.current, limit.pending, limit.changeAfter);
if(isWithinDailyLimit(_wallet, current, _amount)) {
updateDailySpent(_wallet, current, _amount);
return true;
}
return false;
}
/**
* @dev Helper method to update the daily spent for the current period.
* @param _wallet The target wallet.
* @param _limit The current limit for the wallet.
* @param _amount The amount to add to the daily spent.
*/
function updateDailySpent(BaseWallet _wallet, uint128 _limit, uint _amount) internal {
if(_limit != LIMIT_DISABLED) {
DailySpent storage expense = limits[address(_wallet)].dailySpent;
// solium-disable-next-line security/no-block-members
if (expense.periodEnd < now) {
// solium-disable-next-line security/no-block-members
expense.periodEnd = uint64(now + 24 hours);
expense.alreadySpent = uint128(_amount);
}
else {
expense.alreadySpent += uint128(_amount);
}
}
}
/**
* @dev Checks if a transfer amount is withing the daily limit for a wallet.
* @param _wallet The target wallet.
* @param _limit The current limit for the wallet.
* @param _amount The transfer amount.
* @return true if the transfer amount is withing the daily limit.
*/
function isWithinDailyLimit(BaseWallet _wallet, uint _limit, uint _amount) internal view returns (bool) {
if(_limit == LIMIT_DISABLED) {
return true;
}
DailySpent storage expense = limits[address(_wallet)].dailySpent;
// solium-disable-next-line security/no-block-members
if (expense.periodEnd < now) {
return (_amount <= _limit);
} else {
return (expense.alreadySpent + _amount <= _limit && expense.alreadySpent + _amount >= expense.alreadySpent);
}
}
/**
* @dev Helper method to get the current limit from a Limit struct.
* @param _current The value of the current parameter
* @param _pending The value of the pending parameter
* @param _changeAfter The value of the changeAfter parameter
*/
function currentLimit(uint128 _current, uint128 _pending, uint64 _changeAfter) internal view returns (uint128) {
// solium-disable-next-line security/no-block-members
if(_changeAfter > 0 && _changeAfter < now) {
return _pending;
}
return _current;
}
}
/**
* @title BaseTransfer
* @dev Module containing internal methods to execute or approve transfers
* @author Olivier VDB - <[email protected]>
*/
contract BaseTransfer is BaseModule {
// Mock token address for ETH
address constant internal ETH_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// *************** Events *************************** //
event Transfer(address indexed wallet, address indexed token, uint256 indexed amount, address to, bytes data);
event Approved(address indexed wallet, address indexed token, uint256 amount, address spender);
event CalledContract(address indexed wallet, address indexed to, uint256 amount, bytes data);
// *************** Internal Functions ********************* //
/**
* @dev Helper method to transfer ETH or ERC20 for a wallet.
* @param _wallet The target wallet.
* @param _token The ERC20 address.
* @param _to The recipient.
* @param _value The amount of ETH to transfer
* @param _data The data to *log* with the transfer.
*/
function doTransfer(BaseWallet _wallet, address _token, address _to, uint256 _value, bytes memory _data) internal {
if(_token == ETH_TOKEN) {
invokeWallet(address(_wallet), _to, _value, EMPTY_BYTES);
}
else {
bytes memory methodData = abi.encodeWithSignature("transfer(address,uint256)", _to, _value);
invokeWallet(address(_wallet), _token, 0, methodData);
}
emit Transfer(address(_wallet), _token, _value, _to, _data);
}
/**
* @dev Helper method to approve spending the ERC20 of a wallet.
* @param _wallet The target wallet.
* @param _token The ERC20 address.
* @param _spender The spender address.
* @param _value The amount of token to transfer.
*/
function doApproveToken(BaseWallet _wallet, address _token, address _spender, uint256 _value) internal {
bytes memory methodData = abi.encodeWithSignature("approve(address,uint256)", _spender, _value);
invokeWallet(address(_wallet), _token, 0, methodData);
emit Approved(address(_wallet), _token, _value, _spender);
}
/**
* @dev Helper method to call an external contract.
* @param _wallet The target wallet.
* @param _contract The contract address.
* @param _value The ETH value to transfer.
* @param _data The method data.
*/
function doCallContract(BaseWallet _wallet, address _contract, uint256 _value, bytes memory _data) internal {
invokeWallet(address(_wallet), _contract, _value, _data);
emit CalledContract(address(_wallet), _contract, _value, _data);
}
}
/**
* @title TransferManager
* @dev Module to transfer and approve tokens (ETH or ERC20) or data (contract call) based on a security context (daily limit, whitelist, etc).
* This module is the V2 of TokenTransfer.
* @author Julien Niset - <[email protected]>
*/
contract TransferManager is BaseModule, RelayerModule, OnlyOwnerModule, BaseTransfer, LimitManager {
bytes32 constant NAME = "TransferManager";
bytes4 private constant ERC721_ISVALIDSIGNATURE_BYTES = bytes4(keccak256("isValidSignature(bytes,bytes)"));
bytes4 private constant ERC721_ISVALIDSIGNATURE_BYTES32 = bytes4(keccak256("isValidSignature(bytes32,bytes)"));
enum ActionType { Transfer }
using SafeMath for uint256;
struct TokenManagerConfig {
// Mapping between pending action hash and their timestamp
mapping (bytes32 => uint256) pendingActions;
}
// wallet specific storage
mapping (address => TokenManagerConfig) internal configs;
// The security period
uint256 public securityPeriod;
// The execution window
uint256 public securityWindow;
// The Token storage
TransferStorage public transferStorage;
// The Token price provider
TokenPriceProvider public priceProvider;
// The previous limit manager needed to migrate the limits
LimitManager public oldLimitManager;
// *************** Events *************************** //
event AddedToWhitelist(address indexed wallet, address indexed target, uint64 whitelistAfter);
event RemovedFromWhitelist(address indexed wallet, address indexed target);
event PendingTransferCreated(address indexed wallet, bytes32 indexed id, uint256 indexed executeAfter,
address token, address to, uint256 amount, bytes data);
event PendingTransferExecuted(address indexed wallet, bytes32 indexed id);
event PendingTransferCanceled(address indexed wallet, bytes32 indexed id);
// *************** Constructor ********************** //
constructor(
ModuleRegistry _registry,
TransferStorage _transferStorage,
GuardianStorage _guardianStorage,
address _priceProvider,
uint256 _securityPeriod,
uint256 _securityWindow,
uint256 _defaultLimit,
LimitManager _oldLimitManager
)
BaseModule(_registry, _guardianStorage, NAME)
LimitManager(_defaultLimit)
public
{
transferStorage = _transferStorage;
priceProvider = TokenPriceProvider(_priceProvider);
securityPeriod = _securityPeriod;
securityWindow = _securityWindow;
oldLimitManager = _oldLimitManager;
}
/**
* @dev Inits the module for a wallet by setting up the isValidSignature (EIP 1271)
* static call redirection from the wallet to the module and copying all the parameters
* of the daily limit from the previous implementation of the LimitManager module.
* @param _wallet The target wallet.
*/
function init(BaseWallet _wallet) public onlyWallet(_wallet) {
// setup static calls
_wallet.enableStaticCall(address(this), ERC721_ISVALIDSIGNATURE_BYTES);
_wallet.enableStaticCall(address(this), ERC721_ISVALIDSIGNATURE_BYTES32);
// setup default limit for new deployment
if(address(oldLimitManager) == address(0)) {
super.init(_wallet);
return;
}
// get limit from previous LimitManager
uint256 current = oldLimitManager.getCurrentLimit(_wallet);
(uint256 pending, uint64 changeAfter) = oldLimitManager.getPendingLimit(_wallet);
// setup default limit for new wallets
if(current == 0 && changeAfter == 0) {
super.init(_wallet);
return;
}
// migrate existing limit for existing wallets
if(current == pending) {
limits[address(_wallet)].limit.current = uint128(current);
}
else {
limits[address(_wallet)].limit = Limit(uint128(current), uint128(pending), changeAfter);
}
// migrate daily pending if we are within a rolling period
(uint256 unspent, uint64 periodEnd) = oldLimitManager.getDailyUnspent(_wallet);
// solium-disable-next-line security/no-block-members
if(periodEnd > now) {
limits[address(_wallet)].dailySpent = DailySpent(uint128(current.sub(unspent)), periodEnd);
}
}
// *************** External/Public Functions ********************* //
/**
* @dev lets the owner transfer tokens (ETH or ERC20) from a wallet.
* @param _wallet The target wallet.
* @param _token The address of the token to transfer.
* @param _to The destination address
* @param _amount The amoutn of token to transfer
* @param _data The data for the transaction
*/
function transferToken(
BaseWallet _wallet,
address _token,
address _to,
uint256 _amount,
bytes calldata _data
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
if(isWhitelisted(_wallet, _to)) {
// transfer to whitelist
doTransfer(_wallet, _token, _to, _amount, _data);
}
else {
uint256 etherAmount = (_token == ETH_TOKEN) ? _amount : priceProvider.getEtherValue(_amount, _token);
if (checkAndUpdateDailySpent(_wallet, etherAmount)) {
// transfer under the limit
doTransfer(_wallet, _token, _to, _amount, _data);
}
else {
// transfer above the limit
(bytes32 id, uint256 executeAfter) = addPendingAction(ActionType.Transfer, _wallet, _token, _to, _amount, _data);
emit PendingTransferCreated(address(_wallet), id, executeAfter, _token, _to, _amount, _data);
}
}
}
/**
* @dev lets the owner approve an allowance of ERC20 tokens for a spender (dApp).
* @param _wallet The target wallet.
* @param _token The address of the token to transfer.
* @param _spender The address of the spender
* @param _amount The amount of tokens to approve
*/
function approveToken(
BaseWallet _wallet,
address _token,
address _spender,
uint256 _amount
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
if(isWhitelisted(_wallet, _spender)) {
// approve to whitelist
doApproveToken(_wallet, _token, _spender, _amount);
}
else {
// get current alowance
uint256 currentAllowance = ERC20(_token).allowance(address(_wallet), _spender);
if(_amount <= currentAllowance) {
// approve if we reduce the allowance
doApproveToken(_wallet, _token, _spender, _amount);
}
else {
// check if delta is under the limit
uint delta = _amount - currentAllowance;
uint256 deltaInEth = priceProvider.getEtherValue(delta, _token);
require(checkAndUpdateDailySpent(_wallet, deltaInEth), "TM: Approve above daily limit");
// approve if under the limit
doApproveToken(_wallet, _token, _spender, _amount);
}
}
}
/**
* @dev lets the owner call a contract.
* @param _wallet The target wallet.
* @param _contract The address of the contract.
* @param _value The amount of ETH to transfer as part of call
* @param _data The encoded method data
*/
function callContract(
BaseWallet _wallet,
address _contract,
uint256 _value,
bytes calldata _data
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
// Make sure we don't call a module, the wallet itself, or a supported ERC20
authoriseContractCall(_wallet, _contract);
if(isWhitelisted(_wallet, _contract)) {
// call to whitelist
doCallContract(_wallet, _contract, _value, _data);
}
else {
require(checkAndUpdateDailySpent(_wallet, _value), "TM: Call contract above daily limit");
// call under the limit
doCallContract(_wallet, _contract, _value, _data);
}
}
/**
* @dev lets the owner do an ERC20 approve followed by a call to a contract.
* We assume that the contract will pull the tokens and does not require ETH.
* @param _wallet The target wallet.
* @param _token The token to approve.
* @param _contract The address of the contract.
* @param _amount The amount of ERC20 tokens to approve.
* @param _data The encoded method data
*/
function approveTokenAndCallContract(
BaseWallet _wallet,
address _token,
address _contract,
uint256 _amount,
bytes calldata _data
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
// Make sure we don't call a module, the wallet itself, or a supported ERC20
authoriseContractCall(_wallet, _contract);
if(isWhitelisted(_wallet, _contract)) {
doApproveToken(_wallet, _token, _contract, _amount);
doCallContract(_wallet, _contract, 0, _data);
}
else {
// get current alowance
uint256 currentAllowance = ERC20(_token).allowance(address(_wallet), _contract);
if(_amount <= currentAllowance) {
// no need to approve more
doCallContract(_wallet, _contract, 0, _data);
}
else {
// check if delta is under the limit
uint delta = _amount - currentAllowance;
uint256 deltaInEth = priceProvider.getEtherValue(delta, _token);
require(checkAndUpdateDailySpent(_wallet, deltaInEth), "TM: Approve above daily limit");
// approve if under the limit
doApproveToken(_wallet, _token, _contract, _amount);
doCallContract(_wallet, _contract, 0, _data);
}
}
}
/**
* @dev Adds an address to the whitelist of a wallet.
* @param _wallet The target wallet.
* @param _target The address to add.
*/
function addToWhitelist(
BaseWallet _wallet,
address _target
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
require(!isWhitelisted(_wallet, _target), "TT: target already whitelisted");
// solium-disable-next-line security/no-block-members
uint256 whitelistAfter = now.add(securityPeriod);
transferStorage.setWhitelist(_wallet, _target, whitelistAfter);
emit AddedToWhitelist(address(_wallet), _target, uint64(whitelistAfter));
}
/**
* @dev Removes an address from the whitelist of a wallet.
* @param _wallet The target wallet.
* @param _target The address to remove.
*/
function removeFromWhitelist(
BaseWallet _wallet,
address _target
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
require(isWhitelisted(_wallet, _target), "TT: target not whitelisted");
transferStorage.setWhitelist(_wallet, _target, 0);
emit RemovedFromWhitelist(address(_wallet), _target);
}
/**
* @dev Executes a pending transfer for a wallet.
* The method can be called by anyone to enable orchestration.
* @param _wallet The target wallet.
* @param _token The token of the pending transfer.
* @param _to The destination address of the pending transfer.
* @param _amount The amount of token to transfer of the pending transfer.
* @param _data The data associated to the pending transfer.
* @param _block The block at which the pending transfer was created.
*/
function executePendingTransfer(
BaseWallet _wallet,
address _token,
address _to,
uint _amount,
bytes calldata _data,
uint _block
)
external
onlyWhenUnlocked(_wallet)
{
bytes32 id = keccak256(abi.encodePacked(ActionType.Transfer, _token, _to, _amount, _data, _block));
uint executeAfter = configs[address(_wallet)].pendingActions[id];
require(executeAfter > 0, "TT: unknown pending transfer");
uint executeBefore = executeAfter.add(securityWindow);
// solium-disable-next-line security/no-block-members
require(executeAfter <= now && now <= executeBefore, "TT: transfer outside of the execution window");
delete configs[address(_wallet)].pendingActions[id];
doTransfer(_wallet, _token, _to, _amount, _data);
emit PendingTransferExecuted(address(_wallet), id);
}
function cancelPendingTransfer(
BaseWallet _wallet,
bytes32 _id
)
external
onlyWalletOwner(_wallet)
onlyWhenUnlocked(_wallet)
{
require(configs[address(_wallet)].pendingActions[_id] > 0, "TT: unknown pending action");
delete configs[address(_wallet)].pendingActions[_id];
emit PendingTransferCanceled(address(_wallet), _id);
}
/**
* @dev Lets the owner of a wallet change its daily limit.
* The limit is expressed in ETH. Changes to the limit take 24 hours.
* @param _wallet The target wallet.
* @param _newLimit The new limit.
*/
function changeLimit(BaseWallet _wallet, uint256 _newLimit) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) {
changeLimit(_wallet, _newLimit, securityPeriod);
}
/**
* @dev Convenience method to disable the limit
* The limit is disabled by setting it to an arbitrary large value.
* @param _wallet The target wallet.
*/
function disableLimit(BaseWallet _wallet) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) {
disableLimit(_wallet, securityPeriod);
}
/**
* @dev Checks if an address is whitelisted for a wallet.
* @param _wallet The target wallet.
* @param _target The address.
* @return true if the address is whitelisted.
*/
function isWhitelisted(BaseWallet _wallet, address _target) public view returns (bool _isWhitelisted) {
uint whitelistAfter = transferStorage.getWhitelist(_wallet, _target);
// solium-disable-next-line security/no-block-members
return whitelistAfter > 0 && whitelistAfter < now;
}
/**
* @dev Gets the info of a pending transfer for a wallet.
* @param _wallet The target wallet.
* @param _id The pending transfer ID.
* @return the epoch time at which the pending transfer can be executed.
*/
function getPendingTransfer(BaseWallet _wallet, bytes32 _id) external view returns (uint64 _executeAfter) {
_executeAfter = uint64(configs[address(_wallet)].pendingActions[_id]);
}
/**
* @dev Implementation of EIP 1271.
* Should return whether the signature provided is valid for the provided data.
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
*/
function isValidSignature(bytes calldata _data, bytes calldata _signature) external view returns (bytes4) {
bytes32 msgHash = keccak256(abi.encodePacked(_data));
isValidSignature(msgHash, _signature);
return ERC721_ISVALIDSIGNATURE_BYTES;
}
/**
* @dev Implementation of EIP 1271.
* Should return whether the signature provided is valid for the provided data.
* @param _msgHash Hash of a message signed on the behalf of address(this)
* @param _signature Signature byte array associated with _msgHash
*/
function isValidSignature(bytes32 _msgHash, bytes memory _signature) public view returns (bytes4) {
require(_signature.length == 65, "TM: invalid signature length");
address signer = recoverSigner(_msgHash, _signature, 0);
require(isOwner(BaseWallet(msg.sender), signer), "TM: Invalid signer");
return ERC721_ISVALIDSIGNATURE_BYTES32;
}
// *************** Internal Functions ********************* //
/**
* @dev Creates a new pending action for a wallet.
* @param _action The target action.
* @param _wallet The target wallet.
* @param _token The target token for the action.
* @param _to The recipient of the action.
* @param _amount The amount of token associated to the action.
* @param _data The data associated to the action.
* @return the identifier for the new pending action and the time when the action can be executed
*/
function addPendingAction(
ActionType _action,
BaseWallet _wallet,
address _token,
address _to,
uint _amount,
bytes memory _data
)
internal
returns (bytes32 id, uint256 executeAfter)
{
id = keccak256(abi.encodePacked(_action, _token, _to, _amount, _data, block.number));
require(address(this).balance == 0, "TM: duplicate pending action"); //inject PRESENT ETHER
// solium-disable-next-line security/no-block-members
executeAfter = now.add(securityPeriod);
configs[address(_wallet)].pendingActions[id] = executeAfter;
}
/**
* @dev Make sure a contract call is not trying to call a module, the wallet itself, or a supported ERC20.
* @param _wallet The target wallet.
* @param _contract The address of the contract.
*/
function authoriseContractCall(BaseWallet _wallet, address _contract) internal view {
require(
_contract != address(_wallet) && // not the wallet itself
!_wallet.authorised(_contract) && // not an authorised module
(priceProvider.cachedPrices(_contract) == 0 || isLimitDisabled(_wallet)), // not an ERC20 listed in the provider (or limit disabled)
"TM: Forbidden contract");
}
// *************** Implementation of RelayerModule methods ********************* //
// Overrides refund to add the refund in the daily limit.
function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal {
// 21000 (transaction) + 7620 (execution of refund) + 7324 (execution of updateDailySpent) + 672 to log the event + _gasUsed
uint256 amount = 36616 + _gasUsed;
if(_gasPrice > 0 && _signatures > 0 && amount <= _gasLimit) {
if(_gasPrice > tx.gasprice) {
amount = amount * tx.gasprice;
}
else {
amount = amount * _gasPrice;
}
checkAndUpdateDailySpent(_wallet, amount);
invokeWallet(address(_wallet), _relayer, amount, EMPTY_BYTES);
}
}
// Overrides verifyRefund to add the refund in the daily limit.
function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) {
if(_gasPrice > 0 && _signatures > 0 && (
address(_wallet).balance < _gasUsed * _gasPrice ||
isWithinDailyLimit(_wallet, getCurrentLimit(_wallet), _gasUsed * _gasPrice) == false ||
_wallet.authorised(address(this)) == false
))
{
return false;
}
return true;
}
} | Overrides refund to add the refund in the daily limit. 21000 (transaction) + 7620 (execution of refund) + 7324 (execution of updateDailySpent) + 672 to log the event + _gasUsed | function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal {
uint256 amount = 36616 + _gasUsed;
if(_gasPrice > 0 && _signatures > 0 && amount <= _gasLimit) {
if(_gasPrice > tx.gasprice) {
amount = amount * tx.gasprice;
}
else {
amount = amount * _gasPrice;
}
checkAndUpdateDailySpent(_wallet, amount);
invokeWallet(address(_wallet), _relayer, amount, EMPTY_BYTES);
}
}
| 2,499,627 |
/* Copyright (C) 2021 Soteria.fund
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.17;
import "../../abstract/Iupgradable.sol";
import "../../libraries/SafeMath.sol";
import "../capital/MCR.sol";
import "../governance/MemberRoles.sol";
import "../capital/PoolData.sol";
contract TokenFunctions is Iupgradable {
using SafeMath for uint;
MCR internal m1;
MemberRoles internal mr;
SOTEToken public tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
PoolData internal pd;
IPooledStaking pooledStaking;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev Rewards stakers on purchase of cover on smart contract.
* @param _contractAddress smart contract address.
* @param _coverPriceSOTE cover price in SOTE.
*/
function pushStakerRewards(address _contractAddress, uint _coverPriceSOTE) external onlyInternal {
uint rewardValue = _coverPriceSOTE.mul(td.stakerCommissionPer()).div(100);
pooledStaking.accumulateReward(_contractAddress, rewardValue);
}
/**
* @dev Deprecated in favor of burnStakedTokens
*/
function burnStakerLockedToken(uint, bytes4, uint) external {
// noop
}
/**
* @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed.
* @param coverId cover id
* @param coverCurrency cover currency
* @param sumAssured amount of $curr to burn
*/
function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal {
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = m1.calculateTokenPrice(coverCurrency);
uint burnSOTEAmount = sumAssured.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnSOTEAmount);
}
/**
* @dev Gets the total staked SOTE tokens against
* Smart contract by all stakers
* @param _stakedContractAddress smart contract address.
* @return amount total staked SOTE tokens.
*/
function deprecated_getTotalStakedTokensOnSmartContract(
address _stakedContractAddress
)
external
view
returns(uint)
{
uint stakedAmount = 0;
address stakerAddress;
uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress);
for (uint i = 0; i < staketLen; i++) {
stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i);
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, i);
uint currentlyStaked;
(, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress,
_stakedContractAddress, stakerIndex);
stakedAmount = stakedAmount.add(currentlyStaked);
}
return stakedAmount;
}
/**
* @dev Returns amount of SOTE Tokens locked as Cover Note for given coverId.
* @param _of address of the coverHolder.
* @param _coverId coverId of the cover.
*/
function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) {
return _getUserLockedCNTokens(_of, _coverId);
}
/**
* @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 amount) {
for (uint i = 0; i < qd.getUserCoverLength(_of); i++) {
amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i]));
}
}
/**
* @dev Returns amount of SOTE Tokens locked as Cover Note against given coverId.
* @param _coverId coverId of the cover.
*/
function getLockedCNAgainstCover(uint _coverId) external view returns(uint) {
return _getLockedCNAgainstCover(_coverId);
}
/**
* @dev Returns total amount of staked SOTE Tokens on all smart contracts.
* @param _stakerAddress address of the Staker.
*/
function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) {
uint stakedAmount = 0;
address scAddress;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
uint currentlyStaked;
(, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i);
stakedAmount = stakedAmount.add(currentlyStaked);
}
amount = stakedAmount;
}
/**
* @dev Returns total unlockable amount of staked SOTE Tokens on all smart contract .
* @param _stakerAddress address of the Staker.
*/
function deprecated_getStakerAllUnlockableStakedTokens(
address _stakerAddress
)
external
view
returns (uint amount)
{
uint unlockableAmount = 0;
address scAddress;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = unlockableAmount.add(
_deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress,
scIndex));
}
amount = unlockableAmount;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tk = SOTEToken(ms.tokenAddress());
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
m1 = MCR(ms.getLatestAddress("MC"));
gv = Governance(ms.getLatestAddress("GV"));
mr = MemberRoles(ms.getLatestAddress("MR"));
pd = PoolData(ms.getLatestAddress("PD"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
/**
* @dev Gets the Token price in a given currency
* @param curr Currency name.
* @return price Token Price.
*/
function getTokenPrice(bytes4 curr) public view returns(uint price) {
price = m1.calculateTokenPrice(curr);
}
/**
* @dev Set the flag to check if cover note is deposited against the cover id
* @param coverId Cover Id.
*/
function depositCN(uint coverId) public onlyInternal returns (bool success) {
require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available");
td.setDepositCN(coverId, true);
success = true;
}
/**
* @param _of address of Member
* @param _coverId Cover Id
* @param _lockTime Pending Time + Cover Period 7*1 days
*/
function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal {
uint timeStamp = now.add(_lockTime);
uint coverValidUntil = qd.getValidityOfCover(_coverId);
if (timeStamp >= coverValidUntil) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId));
tc.extendLockOf(_of, reason, timeStamp);
}
}
/**
* @dev to burn the deposited cover tokens
* @param coverId is id of cover whose tokens have to be burned
* @return the status of the successful burning
*/
function burnDepositCN(uint coverId) public onlyInternal returns (bool success) {
address _of = qd.getCoverMemberAddress(coverId);
uint amount;
(amount, ) = td.depositedCN(coverId);
amount = (amount.mul(50)).div(100);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
tc.burnLockedTokens(_of, reason, amount);
success = true;
}
/**
* @dev Unlocks covernote locked against a given cover
* @param coverId id of cover
*/
function unlockCN(uint coverId) public onlyInternal {
(, bool isDeposited) = td.depositedCN(coverId);
require(!isDeposited,"Cover note is deposited and can not be released");
uint lockedCN = _getLockedCNAgainstCover(coverId);
if (lockedCN != 0) {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/**
* @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) public {
require(ms.checkIsAuthToGoverned(msg.sender));
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to lock cover note tokens
* @param coverNoteAmount is number of tokens to be locked
* @param coverPeriod is cover period in concern
* @param coverId is the cover id of cover in concern
* @param _of address whose tokens are to be locked
*/
function lockCN(
uint coverNoteAmount,
uint coverPeriod,
uint coverId,
address _of
)
public
onlyInternal
{
uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp());
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
td.setDepositCNAmount(coverId, coverNoteAmount);
tc.lockOf(_of, reason, coverNoteAmount, validity);
}
/**
* @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);
}
/**
* @dev Internal function to gets amount of locked SOTE tokens,
* staked against smartcontract by index
* @param _stakerAddress address of user
* @param _stakedContractAddress staked contract address
* @param _stakedContractIndex index of staking
*/
function deprecated_getStakerLockedTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns
(uint amount)
{
amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress,
_stakedContractAddress, _stakedContractIndex);
}
/**
* @dev Function to gets unlockable amount of locked SOTE
* tokens, staked against smartcontract by index
* @param stakerAddress address of staker
* @param stakedContractAddress staked contract address
* @param stakerIndex index of staking
*/
function deprecated_getStakerUnlockableTokensOnSmartContract (
address stakerAddress,
address stakedContractAddress,
uint stakerIndex
)
public
view
returns (uint)
{
return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress,
td.getStakerStakedContractIndex(stakerAddress, stakerIndex));
}
/**
* @dev releases unlockable staked tokens to staker
*/
function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause {
uint unlockableAmount;
address scAddress;
bytes32 reason;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract(
_stakerAddress, scAddress,
scIndex);
td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0);
td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount);
reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex));
tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount);
}
}
/**
* @dev to get tokens of staker locked before burning that are allowed to burn
* @param stakerAdd is the address of the staker
* @param stakedAdd is the address of staked contract in concern
* @param stakerIndex is the staker index in concern
* @return amount of unlockable tokens
* @return amount of tokens that can burn
*/
function _deprecated_unlockableBeforeBurningAndCanBurn(
address stakerAdd,
address stakedAdd,
uint stakerIndex
)
public
view
returns
(uint amount, uint canBurn) {
uint dateAdd;
uint initialStake;
uint totalBurnt;
uint ub;
(, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex);
canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays());
// Can't use SafeMaths for int.
int v = int(initialStake - (canBurn) - (totalBurnt) - (
td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub));
uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract(
stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex));
if (v < 0) {
v = 0;
}
amount = uint(v);
if (canBurn > currentLockedTokens.sub(amount).sub(ub)) {
canBurn = currentLockedTokens.sub(amount).sub(ub);
}
}
/**
* @dev to get tokens of staker that are unlockable
* @param _stakerAddress is the address of the staker
* @param _stakedContractAddress is the address of staked contract in concern
* @param _stakedContractIndex is the staked contract index in concern
* @return amount of unlockable tokens
*/
function _deprecated_getStakerUnlockableTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns
(uint amount)
{
uint initialStake;
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, _stakedContractIndex);
uint burnt;
(, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex);
uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex);
uint currentStakedTokens;
(, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress,
_stakedContractAddress, stakerIndex);
amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt);
}
/**
* @dev Internal function to get the amount of locked SOTE tokens,
* staked against smartcontract by index
* @param _stakerAddress address of user
* @param _stakedContractAddress staked contract address
* @param _stakedContractIndex index of staking
*/
function _deprecated_getStakerLockedTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
internal
view
returns
(uint amount)
{
bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress,
_stakedContractAddress, _stakedContractIndex));
amount = tc.tokensLocked(_stakerAddress, reason);
}
/**
* @dev Returns amount of SOTE Tokens locked as Cover Note for given coverId.
* @param _coverId coverId of the cover.
*/
function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) {
address coverHolder = qd.getCoverMemberAddress(_coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId));
return tc.tokensLockedAtTime(coverHolder, reason, now);
}
/**
* @dev Returns amount of SOTE Tokens locked as Cover Note for given coverId.
* @param _of address of the coverHolder.
* @param _coverId coverId of the cover.
*/
function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId));
return tc.tokensLockedAtTime(_of, reason, now);
}
/**
* @dev Internal function to gets remaining amount of staked SOTE tokens,
* against smartcontract by index
* @param _stakeAmount address of user
* @param _stakeDays staked contract address
* @param _validDays index of staking
*/
function _deprecated_calculateStakedTokens(
uint _stakeAmount,
uint _stakeDays,
uint _validDays
)
internal
pure
returns (uint amount)
{
if (_validDays > _stakeDays) {
uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays);
amount = (rf.mul(_stakeAmount)).div(100000);
} else {
amount = 0;
}
}
/**
* @dev Gets the total staked SOTE tokens against Smart contract
* by all stakers
* @param _stakedContractAddress smart contract address.
* @return amount total staked SOTE tokens.
*/
function _deprecated_burnStakerTokenLockedAgainstSmartContract(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _amount
)
internal
{
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, _stakedContractIndex);
td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount);
bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress,
_stakedContractAddress, _stakedContractIndex));
tc.burnLockedTokens(_stakerAddress, reason, _amount);
}
} | Returns amount of SOTE Tokens locked as Cover Note for given coverId. _of address of the coverHolder. _coverId coverId of the cover./ | function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) {
return _getUserLockedCNTokens(_of, _coverId);
}
| 7,238,575 |
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import { SignatureChecker } from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract DataToChain {
struct UserInfo {
uint256 userId;
uint256 parentId;
uint256 lockeBalance;
uint256 assetsBalance;
uint256 changeBalance;
}
address public owner = msg.sender;
mapping(address => UserInfo) public userInfos;
mapping(uint256 => address) public userIdMapAddress;
// Stores a new value in the contract
function store(uint256 userId,uint256 parentId,uint256 lockeBalance,uint256 assetsBalance,uint256 changeBalance,bytes memory signature) public {
require(userId != 0,"DataToChain: userId cannt be zero");
require(userIdMapAddress[userId] == address(0),"DataToChain:userId Have imported");
require(userInfos[msg.sender].userId == 0,"DataToChain: msg.sender Have imported");
require(lockeBalance+assetsBalance+changeBalance>0,"DataToChain: The upload amount must be greater than 0");
bytes32 message = ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(msg.sender, userId, parentId, lockeBalance, assetsBalance, changeBalance, this)));
require(SignatureChecker.isValidSignatureNow(owner, message, signature),"DataToChain: Signature verification failure");
userIdMapAddress[userId] = msg.sender;
userInfos[userIdMapAddress[userId]].userId = userId;
userInfos[userIdMapAddress[userId]].parentId = parentId;
userInfos[userIdMapAddress[userId]].lockeBalance = lockeBalance;
userInfos[userIdMapAddress[userId]].assetsBalance = assetsBalance;
userInfos[userIdMapAddress[userId]].changeBalance = changeBalance;
}
// Reads the last stored value
function getParentAddress(address userAddress) public view returns (address) {
return userIdMapAddress[userInfos[userAddress].parentId];
}
// Reads the last stored value
function getUpChainAmount(address userAddress) public view returns (uint256) {
return userInfos[userAddress].lockeBalance+userInfos[userAddress].assetsBalance+userInfos[userAddress].changeBalance;
}
// Reads the last stored value
function isUp(address userAddress,uint256 userId) public view returns (bool,bool) {
bool addressBool = userInfos[userAddress].userId > 0;
bool userIdBool = userIdMapAddress[userId] != address(0);
return (addressBool,userIdBool);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract signatures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureChecker {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// 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/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);
}
} | Stores a new value in the contract | function store(uint256 userId,uint256 parentId,uint256 lockeBalance,uint256 assetsBalance,uint256 changeBalance,bytes memory signature) public {
require(userId != 0,"DataToChain: userId cannt be zero");
require(userIdMapAddress[userId] == address(0),"DataToChain:userId Have imported");
require(userInfos[msg.sender].userId == 0,"DataToChain: msg.sender Have imported");
require(lockeBalance+assetsBalance+changeBalance>0,"DataToChain: The upload amount must be greater than 0");
bytes32 message = ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(msg.sender, userId, parentId, lockeBalance, assetsBalance, changeBalance, this)));
require(SignatureChecker.isValidSignatureNow(owner, message, signature),"DataToChain: Signature verification failure");
userIdMapAddress[userId] = msg.sender;
userInfos[userIdMapAddress[userId]].userId = userId;
userInfos[userIdMapAddress[userId]].parentId = parentId;
userInfos[userIdMapAddress[userId]].lockeBalance = lockeBalance;
userInfos[userIdMapAddress[userId]].assetsBalance = assetsBalance;
userInfos[userIdMapAddress[userId]].changeBalance = changeBalance;
}
| 1,276,807 |
./full_match/5/0xeDbDfF00161080D8929A3aEBF88c72A96477d25a/sources/contracts/pools/stable/StableMath.sol | Computes how many tokens can be taken out of a pool if `tokenAmountIn` are sent, given the current balances. The amplification parameter equals: A n^(n-1) outGivenIn token x for y - polynomial equation to solve ay = amount out to calculate by = balance token out y = by - ay (finalBalanceOut) D = invariant D D^(n+1) A = amplification coefficient y^2 + ( S - ---------- - D) y - ------------- = 0 n = number of tokens (A n^n) A n^2n P S = sum of final balances but y P = product of final balances but y Amount out, so we round down overall. | function _calcOutGivenIn(
uint256 amplificationParameter,
uint256[] memory balances,
uint256 tokenIndexIn,
uint256 tokenIndexOut,
uint256 tokenAmountIn
) internal pure returns (uint256) {
uint256 invariant = _calculateInvariant(amplificationParameter, balances);
balances[tokenIndexIn] = balances[tokenIndexIn].add(tokenAmountIn);
uint256 finalBalanceOut = _getTokenBalanceGivenInvariantAndAllOtherBalances(
amplificationParameter,
balances,
invariant,
tokenIndexOut
);
balances[tokenIndexIn] = balances[tokenIndexIn].sub(tokenAmountIn);
return balances[tokenIndexOut].sub(finalBalanceOut).sub(1);
}
| 11,617,981 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
contract SampleNFT is Initializable, ERC721Upgradeable, PausableUpgradeable, AccessControlUpgradeable, UUPSUpgradeable {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
address private marketplaceAdd;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() initializer public {
__ERC721_init("SampleNFT", "SNFT");
__Pausable_init();
__AccessControl_init();
__UUPSUpgradeable_init();
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(PAUSER_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
_grantRole(UPGRADER_ROLE, msg.sender);
}
function _baseURI() internal pure override returns (string memory) {
return "https://mynfturl";
}
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
function safeMint(address to, uint256 tokenId) public onlyRole(MINTER_ROLE) {
_safeMint(to, tokenId);
_setApprovalForAll(to, marketplaceAdd, true);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _authorizeUpgrade(address newImplementation)
internal
onlyRole(UPGRADER_ROLE)
override
{}
// The following functions are overrides required by Solidity.
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, AccessControlUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function setMarketplaceAdd(address mp) public onlyRole(DEFAULT_ADMIN_ROLE) {
require(mp != address(0));
marketplaceAdd = mp;
}
} | The following functions are overrides required by Solidity. | function _authorizeUpgrade(address newImplementation)
internal
onlyRole(UPGRADER_ROLE)
override
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, AccessControlUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
| 15,811,379 |
pragma solidity ^0.4.4;
contract Token {
function totalSupply() public constant returns(uint256 supply) {} /// @return total amount of tokens
/// @param _owner The address from which the balance will be retrieved
function balanceOf(address _owner) public constant returns (uint256 balance) {} /// @return The balance
function transfer(address _to, uint256 _value) public returns (bool success) {} //The amount of token to be transferred to address @return Whether the transfer was successful or not
function transferFrom(address _from, address _to,uint256 _value) public returns (bool success) {} //@param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful
function approve(address _spender, uint256 _value) public returns (bool success) {} /// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {} /// @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
event Transfer(address indexed _from, address indexed _to,uint256 _value);
event Approval(address indexed _owner,address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to,uint256 _value) public returns (bool success) {
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
if(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]){
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to,_value); return true;
} else {return false;}
}
}
function transferFrom(address _from, address _to,uint256 _value) public returns (bool success) {
// same as function transfer
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value; Transfer(_from,_to, _value); return true; } else { return
false; } } }
function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner];
} function approve(address _spender, uint256 _value) public returns
(bool success)
{ allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value); return true;
} function allowance(address _owner, address _spender) public
constant returns (uint256 remaining)
{ return
allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address =>
uint256)) allowed; uint256 public totalSupply; } //name this
contract ERC20Token is StandardToken { function () public {
}
function ERC20Token() public {
balances[msg.sender] = 100000;
totalSupply = 100000; //
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData))
{ revert(); } return true; } } | / return total amount of tokens | function totalSupply() public constant returns(uint256 supply) {} | 13,057,337 |
./full_match/42/0xb4540cf1684D8f566f15daa17441B8a33211A9AB/sources/dex/Main.sol | Weth= WETH(_WETH); Weth.approve(address(this),Weth.balanceOf(address(this))); | function setWETH(address _WETH) public{
tokenWETH= _WETH;
}
| 9,581,558 |
// SPDX-License-Identifier: MIT
/**
ScacContract
*/
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _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/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/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/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 {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_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);
}
}
pragma solidity >=0.7.0 <0.9.0;
contract SaveUkraineNFTs is ERC721Enumerable, Ownable {
using Strings for uint256;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.07 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmount = 20;
bool public paused = true;
bool public revealed = false;
string public notRevealedUri;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
// This will pay 10% of the initial sale to the community wallet.
// =============================================================================
(bool hs, ) = payable(0x84f54c35E676ae1D6e4EF656b3BF4F8Aaa1a289b).call{value: address(this).balance * 10 / 100}("");
require(hs);
// =============================================================================
// This will payout the owner 90% of the contract balance.
// 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);
// =============================================================================
}
} | Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./ | interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
ScacContract
pragma solidity ^0.8.0;
}
| 13,961,890 |
//Address: 0xceffdb3f1aed635e94a0b565239d4353ae44c744
//Contract name: BancorBuyer
//Balance: 0 Ether
//Verification Date: 6/10/2017
//Transacion Count: 5
// CODE STARTS HERE
pragma solidity ^0.4.11;
/*
Bancor Buyer
========================
Buys Bancor tokens from the crowdsale on your behalf.
Author: /u/Cintix
*/
// ERC20 Interface: https://github.com/ethereum/EIPs/issues/20
contract ERC20 {
function transfer(address _to, uint _value) returns (bool success);
}
contract BancorBuyer {
// Store the amount of ETH deposited or BNT owned by each account.
mapping (address => uint) public balances;
// Track whether the contract has bought the tokens yet.
bool public bought_tokens;
// Record the time the contract bought the tokens.
uint public time_bought;
// The Bancor Token Sale address.
address sale = 0xBbc79794599b19274850492394004087cBf89710;
// Bancor Smart Token Contract address.
address token = 0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C;
// The developer address.
address developer = 0x4e6A1c57CdBfd97e8efe831f8f4418b1F2A09e6e;
// Withdraws all ETH deposited by the sender.
// Called to cancel a user's participation in the sale.
function withdraw(){
// Store the user's balance prior to withdrawal in a temporary variable.
uint amount = balances[msg.sender];
// Update the user's balance prior to sending ETH to prevent recursive call.
balances[msg.sender] = 0;
// Return the user's funds. Throws on failure to prevent loss of funds.
msg.sender.transfer(amount);
}
// Buys tokens in the crowdsale, callable by anyone.
function buy(){
// Transfer all funds to the Bancor crowdsale contract to buy tokens.
// Throws if the crowdsale hasn't started yet or has
// already completed, preventing loss of funds.
sale.transfer(this.balance);
// Record that the contract has bought the tokens.
bought_tokens = true;
// Record the time the contract bought the tokens.
time_bought = now;
}
function () payable {
// Only allow deposits if the contract hasn't already purchased the tokens.
if (!bought_tokens) {
// Update records of deposited ETH to include the received amount.
balances[msg.sender] += msg.value;
}
// Withdraw the sender's tokens if the contract has already purchased them.
else {
// Store the user's BNT balance in a temporary variable (1 ETHWei -> 100 BNTWei).
uint amount = balances[msg.sender] * 100;
// Update the user's balance prior to sending BNT to prevent recursive call.
balances[msg.sender] = 0;
// No fee for withdrawing during the crowdsale.
uint fee = 0;
// 1% fee for withdrawing after the crowdsale has ended.
if (now > time_bought + 1 hours) {
fee = amount / 100;
}
// Transfer the tokens to the sender and the developer.
ERC20(token).transfer(msg.sender, amount - fee);
ERC20(token).transfer(developer, fee);
// Refund any ETH sent after the contract has already purchased tokens.
msg.sender.transfer(msg.value);
}
}
}
| Only allow deposits if the contract hasn't already purchased the tokens. Update records of deposited ETH to include the received amount. Withdraw the sender's tokens if the contract has already purchased them. Store the user's BNT balance in a temporary variable (1 ETHWei -> 100 BNTWei). Update the user's balance prior to sending BNT to prevent recursive call. No fee for withdrawing during the crowdsale. 1% fee for withdrawing after the crowdsale has ended. | function () payable {
if (!bought_tokens) {
balances[msg.sender] += msg.value;
}
else {
uint amount = balances[msg.sender] * 100;
balances[msg.sender] = 0;
uint fee = 0;
if (now > time_bought + 1 hours) {
fee = amount / 100;
}
ERC20(token).transfer(developer, fee);
}
}
| 13,113,660 |
./partial_match/3/0xB8dfa8a6B569390a13777bE08D10f52E16302926/sources/Crowdsale.sol | Event for token purchase logging purchaser who paid for the tokens beneficiary who got the tokens value weis paid for purchase amount amount of tokens purchased/ _rate Number of token units a buyer gets per wei _wallet Address where collected funds will be forwarded to _token Address of the token being sold/ | function Crowdsale(uint256 _rate, address _wallet, ERC20 _token, uint _releaseTime) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
releaseTime = _releaseTime;
}
| 5,311,268 |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./CurveStable.sol";
import "./ConvexBase.sol";
/// @notice Implements the strategy using Convex. The steps are similar to CurveStable strategy, the main differences are:
/// 1) The Curve LP tokens are deposited into Convex Booster contract
/// 2) Use the Convex Rewards contract to claim rewards and get both CRV and CVX in return
/// Because of this, the strategy only overrides some of the functions from parent contracts for the different parts.
/// Booster: 0xF403C135812408BFbE8713b5A23a04b3D48AAE31
/// Rewards: 0x4a2631d090e8b40bBDe245e687BF09e5e534A239
/// Pool Id: 13 (This id is used by Convex to look up pool information in the booster)
contract ConvexStable is CurveStable, ConvexBase {
using SafeERC20 for IERC20;
uint256 private constant POOL_ID = 13;
constructor(
address _vault,
address _proposer,
address _developer,
address _keeper,
address _pool,
address _booster
) CurveStable(_vault, _proposer, _developer, _keeper, _pool) ConvexBase(POOL_ID, _booster) {}
function name() external view override returns (string memory) {
return string(abi.encodePacked("ConvexStable_", IERC20Metadata(address(want)).symbol()));
}
function protectedTokens() internal view virtual override returns (address[] memory) {
return _buildProtectedTokens(_getCurveTokenAddress());
}
function _approveDex() internal virtual override {
super._approveDex();
_approveDexExtra(dex);
}
function _balanceOfPool() internal view virtual override returns (uint256) {
// get staked cvxusdn3crv
uint256 convexBalance = _getLpTokenBalance();
// staked convex converts 1 to 1 to usdn3crv so no need to calc
// convert usdn3crv to want
if (convexBalance > 0) {
return _quoteWantInMetapoolLp(convexBalance);
} else {
return 0;
}
}
function _balanceOfRewards() internal view virtual override returns (uint256) {
return _convexRewardsValue(_getCurveTokenAddress(), _getQuoteForTokenToWant);
}
function _depositLPTokens() internal virtual override {
_depositToConvex();
}
function _claimRewards() internal virtual override {
_claimConvexRewards(_getCurveTokenAddress(), _swapToWant);
}
function _getLpTokenBalance() internal view virtual override returns (uint256) {
return _getConvexBalance();
}
function _removeLpToken(uint256 _amount) internal virtual override {
_withdrawFromConvex(_amount);
}
// no need to do anything
function onHarvest() internal virtual override {}
}
// 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
pragma solidity =0.8.9;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../interfaces/curve/ICurveDeposit.sol";
import "../interfaces/curve/ICurveGauge.sol";
import "../interfaces/curve/ICurveMinter.sol";
import "../interfaces/sushiswap/IUniswapV2Router.sol";
import "./CurveBase.sol";
/// @notice Implements the strategy using the usdn/3Crv(DAI/USDC/USDT) pool.
/// There is a zap depositor available, however, we came across an error when we tried to use it, and can't figure out a fix, that's why it's not used.
/// So the strategy will deploy the input token (USDC) to the 3Crv pool first, and then deploy the 3Crv LP token to the meta pool.
/// Finally, the strategy will deposit the meta pool LP tokens into the gauge.
/// Input token: USDC
/// Base pool: 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7 (3Crv pool)
/// Meta pool: 0x0f9cb53Ebe405d49A0bbdBD291A65Ff571bC83e1
/// Gauge: 0xF98450B5602fa59CC66e1379DFfB6FDDc724CfC4
contract CurveStable is CurveBase {
using SafeERC20 for IERC20;
using Address for address;
// the address of the meta pool
address internal constant USDN_METAPOOL = address(0x0f9cb53Ebe405d49A0bbdBD291A65Ff571bC83e1);
// the address of the gauge
address internal constant CURVE_GAUGE = address(0xF98450B5602fa59CC66e1379DFfB6FDDc724CfC4);
// the address of the 3Crv pool LP token
IERC20 internal constant THREE_CRV = IERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490);
// the address of the usdn/3Crv meta pool LP token
IERC20 internal constant USDN_3CRV = IERC20(0x4f3E8F405CF5aFC05D68142F3783bDfE13811522);
ICurveDeposit internal usdnMetaPool;
IERC20 internal triPoolLpToken;
// the index of the want token in the 3Crv pool
int128 internal immutable wantThreepoolIndex;
uint256 internal constant N_POOL_COINS = 3;
constructor(
address _vault,
address _proposer,
address _developer,
address _keeper,
address _pool
) CurveBase(_vault, _proposer, _developer, _keeper, _pool) {
// threePool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
// usdnMetaPool = 0x0f9cb53Ebe405d49A0bbdBD291A65Ff571bC83e1;
// curveGauge = address(0xF98450B5602fa59CC66e1379DFfB6FDDc724CfC4);
// curveMinter = address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0);
usdnMetaPool = ICurveDeposit(_getMetaPool());
triPoolLpToken = _getTriPoolLpToken();
wantThreepoolIndex = _getWantIndexInCurvePool(_pool);
_approveCurveExtra();
}
function name() external view virtual override returns (string memory) {
return string(abi.encodePacked("CurveStable_", IERC20Metadata(address(want)).symbol()));
}
function _getMetaPool() internal view virtual returns (address) {
return USDN_METAPOOL;
}
function _getTriPoolLpToken() internal view virtual returns (IERC20) {
return THREE_CRV;
}
function _getMetaPoolLpToken() internal view virtual returns (IERC20) {
return USDN_3CRV;
}
function _getWantTokenIndex() internal view override returns (uint256) {
return uint128(wantThreepoolIndex);
}
function _getCoinsCount() internal pure override returns (uint256) {
return N_POOL_COINS;
}
function _getWantIndexInCurvePool(address _pool) internal view returns (int128) {
address _candidate;
for (uint256 i = 0; i < N_POOL_COINS; i++) {
_candidate = ICurveDeposit(_pool).coins(uint256(i));
if (address(want) == _candidate) {
return int128(uint128(i));
}
}
revert("Want token doesnt match any tokens in the curve pool");
}
function _balanceOfPool() internal view virtual override returns (uint256) {
uint256 lpTokenAmount = curveGauge.balanceOf(address(this));
// we will get the eth amount, which is the same as weth
if (lpTokenAmount > 0) {
uint256 outputAmount = _quoteWantInMetapoolLp(lpTokenAmount);
return outputAmount;
}
return 0;
}
/// @dev The input is the LP token of the meta pool. To get the value of the original liquidity in the base pool,
/// we need to use `calc_withdraw_one_coin` from meta pool and base pool to see how much `want` we will get if we withdraw, without actually doing the withdraw.
function _quoteWantInMetapoolLp(uint256 _metaPoolLpTokens) public view returns (uint256) {
uint256 _3crvInUsdn3crv = usdnMetaPool.calc_withdraw_one_coin(_metaPoolLpTokens, 1);
uint256 _wantIn3crv = curvePool.calc_withdraw_one_coin(_3crvInUsdn3crv, wantThreepoolIndex);
return _wantIn3crv;
}
function _approveCurveExtra() internal virtual {
want.safeApprove(address(curvePool), type(uint256).max);
_getTriPoolLpToken().safeApprove(address(usdnMetaPool), type(uint256).max);
}
function _addLiquidityToCurvePool() internal virtual override {
uint256 _wantBalance = _balanceOfWant();
if (_wantBalance > 0) {
uint256[3] memory _tokens = _buildDepositArray(_wantBalance);
curvePool.add_liquidity(_tokens, 0);
}
// stake 3crv and recevice usdnMetaPool LP tokens - _getMetaPoolLpToken()
uint256 _3crv = _getTriPoolLpToken().balanceOf(address(this));
if (_3crv > 0) {
// uint256 _usdn3crvLPs2 = usdnMetaPool.add_liquidity([uint256(0), _3crv], uint256(0));
usdnMetaPool.add_liquidity([uint256(0), _3crv], uint256(0));
}
}
function _depositLPTokens() internal virtual override {
uint256 _usdn3crvLPs = _getMetaPoolLpToken().balanceOf(address(this));
if (_usdn3crvLPs > 0) {
// add usdn3crvLp tokens to curvegauge, this allow to call mint to receive CRV tokens
curveGauge.deposit(_usdn3crvLPs);
curveGauge.balanceOf(address(this));
}
}
function _buildDepositArray(uint256 _amount) public view returns (uint256[3] memory) {
uint256[3] memory _tokenBins;
_tokenBins[uint128(wantThreepoolIndex)] = _amount;
return _tokenBins;
}
/// @dev The `_amount` is in want token, so we need to convert that to LP tokens first.
/// We use the `calc_token_amount` to calculate how many LP tokens we will get with the `_amount` of want tokens without actually doing the deposit.
/// Then we add a bit more (2%) for padding.
function _withdrawSome(uint256 _amount) internal override returns (uint256) {
uint256 requiredTriPoollLpTokens = curvePool.calc_token_amount(_buildDepositArray(_amount), true);
uint256 requiredMetaPoollLpTokens = (usdnMetaPool.calc_token_amount([0, requiredTriPoollLpTokens], true) * 10200) /
10000; // adding 2% for fees
uint256 liquidated = _removeLiquidity(requiredMetaPoollLpTokens);
return liquidated;
}
function _getCurvePoolGaugeAddress() internal view virtual override returns (address) {
return CURVE_GAUGE;
}
/// @dev Remove the liquidity by the LP token amount
/// @param _amount The amount of LP token (not want token)
function _removeLiquidity(uint256 _amount) internal override returns (uint256) {
uint256 _before = _balanceOfWant();
uint256 lpBalance = _getLpTokenBalance();
// need to make sure we don't withdraw more than what we have
uint256 withdrawAmount = Math.min(lpBalance, _amount);
// withdraw this amount of lp tokens first
_removeLpToken(withdrawAmount);
// then remove the liqudity from the pool, will get want back
uint256 usdn3crv = _getMetaPoolLpToken().balanceOf(address(this));
usdnMetaPool.remove_liquidity_one_coin(usdn3crv, 1, uint256(0));
uint256 _3crv = _getTriPoolLpToken().balanceOf(address(this));
ICurveDepositTrio(address(curvePool)).remove_liquidity_one_coin(_3crv, wantThreepoolIndex, 0);
return _balanceOfWant() - _before;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/convex/IConvexDeposit.sol";
import "../interfaces/convex/IConvexRewards.sol";
/// @notice This contract provides common functions that will be used by all Convex strategies.
contract ConvexBase {
using SafeERC20 for IERC20;
address private constant CONVEX_TOKEN_ADDRESS = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
// The pool id. This is unique for each Curve pool.
uint256 public poolId;
// The address of the Convex booster contract
address public convexBooster;
// The address of the Rewards contract for the pool. Different for each pool
address public cvxRewards;
// The address of the LP token that the booster contract will accept for a pool
address public lpToken;
// Store dex approval status to avoid excessive approvals
mapping(address => bool) internal cvxDexApprovals;
/// @param _pooId the id of the pool
/// @param _booster the address of the booster contract
constructor(uint256 _pooId, address _booster) {
require(_booster != address(0), "invalid booster address");
poolId = _pooId;
convexBooster = _booster;
(lpToken, , , cvxRewards, , ) = IConvexDeposit(convexBooster).poolInfo(poolId);
_approveConvexExtra();
}
// Need to allow booster to access the lp tokens for deposit
function _approveConvexExtra() internal virtual {
IERC20(lpToken).safeApprove(convexBooster, type(uint256).max);
}
// Need to allow dex to access the Convex tokens for swaps
function _approveDexExtra(address _dex) internal {
if (!cvxDexApprovals[_dex]) {
cvxDexApprovals[_dex] = true;
IERC20(_getConvexTokenAddress()).safeApprove(_dex, type(uint256).max);
}
}
// Keep CRV, CVX and the pool lp tokens in the strategy. Everything else can be sent to somewhere else.
function _buildProtectedTokens(address _curveToken) internal view returns (address[] memory) {
address[] memory protected = new address[](3);
protected[0] = _curveToken;
protected[1] = _getConvexTokenAddress();
protected[2] = lpToken;
return protected;
}
/// @dev Add Curve LP tokens to Convex booster
function _depositToConvex() internal {
uint256 balance = IERC20(lpToken).balanceOf(address(this));
if (balance > 0) {
IConvexDeposit(convexBooster).depositAll(poolId, true);
}
}
/// @dev Return the amount of Curve LP tokens.
/// The Curve LP tokens are eventually deposited into the Rewards contract, and we can query it to get the balance.
function _getConvexBalance() internal view returns (uint256) {
return IConvexRewards(cvxRewards).balanceOf(address(this));
}
/// @dev When withdraw, withdraw the LP tokens from the Rewards contract and claim rewards. Unwrap these to Curve LP tokens.
/// @param _amount The amount of rewards (1:1 to LP tokens) to withdraw.
function _withdrawFromConvex(uint256 _amount) internal {
IConvexRewards(cvxRewards).withdrawAndUnwrap(_amount, true);
}
function _getConvexTokenAddress() internal view virtual returns (address) {
return CONVEX_TOKEN_ADDRESS;
}
/// @dev Get the rewards (CRV and CVX) from Convex, and swap them for the `want` tokens.
function _claimConvexRewards(address _curveTokenAddress, function(address, uint256) returns (uint256) _swapFunc)
internal
virtual
{
IConvexRewards(cvxRewards).getReward(address(this), true);
uint256 crvBalance = IERC20(_curveTokenAddress).balanceOf(address(this));
uint256 convexBalance = IERC20(_getConvexTokenAddress()).balanceOf(address(this));
_swapFunc(_curveTokenAddress, crvBalance);
_swapFunc(_getConvexTokenAddress(), convexBalance);
}
/// @dev calculate the value of the convex rewards in want token.
/// It will calculate how many CVX tokens can be claimed based on the _crv amount and then swap them to want
function _convexRewardsValue(address _curveTokenAddress, function(address, uint256) view returns (uint256) _quoteFunc)
internal
view
returns (uint256)
{
uint256 _crv = IConvexRewards(cvxRewards).earned(address(this));
if (_crv > 0) {
// calculations pulled directly from CVX's contract for minting CVX per CRV claimed
uint256 totalCliffs = 1000;
uint256 maxSupply = 1e8 * 1e18; // 100m
uint256 reductionPerCliff = 1e5 * 1e18; // 100k
uint256 supply = IERC20(_getConvexTokenAddress()).totalSupply();
uint256 _cvx;
uint256 cliff = supply / reductionPerCliff;
// mint if below total cliffs
if (cliff < totalCliffs) {
// for reduction% take inverse of current cliff
uint256 reduction = totalCliffs - cliff;
// reduce
_cvx = (_crv * reduction) / totalCliffs;
// supply cap check
uint256 amtTillMax = maxSupply - supply;
if (_cvx > amtTillMax) {
_cvx = amtTillMax;
}
}
uint256 rewardsValue;
rewardsValue += _quoteFunc(_curveTokenAddress, _crv);
if (_cvx > 0) {
rewardsValue += _quoteFunc(_getConvexTokenAddress(), _cvx);
}
return rewardsValue;
}
return 0;
}
}
// 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 (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/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
interface ICurveDeposit {
// 3 coin
function add_liquidity(uint256[1] memory amounts, uint256 min_mint_amount) external;
function add_liquidity(uint256[2] memory amounts, uint256 min_mint_amount) external payable returns (uint256);
function add_liquidity(uint256[3] memory amounts, uint256 min_mint_amount) external;
function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external;
function add_liquidity(
uint256[3] memory amounts,
uint256 min_mint_amount,
bool _use_underlying
) external;
function coins(uint256 arg0) external view returns (address);
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
function calc_token_amount(uint256[4] memory amounts, bool is_deposit) external view returns (uint256);
function calc_token_amount(uint256[3] memory amounts, bool is_deposit) external view returns (uint256);
function calc_token_amount(uint256[2] memory amounts, bool is_deposit) external view returns (uint256);
/// @notice Withdraw and unwrap a single coin from the pool
/// @param _token_amount Amount of LP tokens to burn in the withdrawal
/// @param i Index value of the coin to withdraw, 0-Dai, 1-USDC, 2-USDT
/// @param _min_amount Minimum amount of underlying coin to receive
//
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 _min_amount
) external returns (uint256);
}
interface ICurveDepositTrio {
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 _min_amount
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
interface ICurveGauge {
function deposit(uint256 _value) external;
function integrate_fraction(address arg0) external view returns (uint256);
function balanceOf(address arg0) external view returns (uint256);
function claimable_tokens(address arg0) external returns (uint256);
function withdraw(uint256 _value) external;
/// @dev The address of the LP token that may be deposited into the gauge.
function lp_token() external view returns (address);
function user_checkpoint(address _user) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
// so
interface ICurveMinter {
function mint(address gauge_addr) external;
function minted(address arg0, address arg1) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
interface IUniswapV2Router {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
}
// interface GeneratedInterface {
// function WETH() external view returns (address);
// function addLiquidity(
// address tokenA,
// address tokenB,
// uint256 amountADesired,
// uint256 amountBDesired,
// uint256 amountAMin,
// uint256 amountBMin,
// address to,
// uint256 deadline
// )
// external
// returns (
// uint256 amountA,
// uint256 amountB,
// uint256 liquidity
// );
// function addLiquidityETH(
// address token,
// uint256 amountTokenDesired,
// uint256 amountTokenMin,
// uint256 amountETHMin,
// address to,
// uint256 deadline
// )
// external
// returns (
// uint256 amountToken,
// uint256 amountETH,
// uint256 liquidity
// );
// function factory() external view returns (address);
// function getAmountIn(
// uint256 amountOut,
// uint256 reserveIn,
// uint256 reserveOut
// ) external pure returns (uint256 amountIn);
// function getAmountOut(
// uint256 amountIn,
// uint256 reserveIn,
// uint256 reserveOut
// ) external pure returns (uint256 amountOut);
// function getAmountsIn(uint256 amountOut, address[] path) external view returns (uint256[] amounts);
// function getAmountsOut(uint256 amountIn, address[] path) external view returns (uint256[] amounts);
// function quote(
// uint256 amountA,
// uint256 reserveA,
// uint256 reserveB
// ) external pure returns (uint256 amountB);
// function removeLiquidity(
// address tokenA,
// address tokenB,
// uint256 liquidity,
// uint256 amountAMin,
// uint256 amountBMin,
// address to,
// uint256 deadline
// ) external returns (uint256 amountA, uint256 amountB);
// function removeLiquidityETH(
// address token,
// uint256 liquidity,
// uint256 amountTokenMin,
// uint256 amountETHMin,
// address to,
// uint256 deadline
// ) external returns (uint256 amountToken, uint256 amountETH);
// function removeLiquidityETHSupportingFeeOnTransferTokens(
// address token,
// uint256 liquidity,
// uint256 amountTokenMin,
// uint256 amountETHMin,
// address to,
// uint256 deadline
// ) external returns (uint256 amountETH);
// function removeLiquidityETHWithPermit(
// address token,
// uint256 liquidity,
// uint256 amountTokenMin,
// uint256 amountETHMin,
// address to,
// uint256 deadline,
// bool approveMax,
// uint8 v,
// bytes32 r,
// bytes32 s
// ) external returns (uint256 amountToken, uint256 amountETH);
// function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
// address token,
// uint256 liquidity,
// uint256 amountTokenMin,
// uint256 amountETHMin,
// address to,
// uint256 deadline,
// bool approveMax,
// uint8 v,
// bytes32 r,
// bytes32 s
// ) external returns (uint256 amountETH);
// function removeLiquidityWithPermit(
// address tokenA,
// address tokenB,
// uint256 liquidity,
// uint256 amountAMin,
// uint256 amountBMin,
// address to,
// uint256 deadline,
// bool approveMax,
// uint8 v,
// bytes32 r,
// bytes32 s
// ) external returns (uint256 amountA, uint256 amountB);
// function swapETHForExactTokens(
// uint256 amountOut,
// address[] path,
// address to,
// uint256 deadline
// ) external returns (uint256[] amounts);
// function swapExactETHForTokens(
// uint256 amountOutMin,
// address[] path,
// address to,
// uint256 deadline
// ) external returns (uint256[] amounts);
// function swapExactETHForTokensSupportingFeeOnTransferTokens(
// uint256 amountOutMin,
// address[] path,
// address to,
// uint256 deadline
// ) external;
// function swapExactTokensForETH(
// uint256 amountIn,
// uint256 amountOutMin,
// address[] path,
// address to,
// uint256 deadline
// ) external returns (uint256[] amounts);
// function swapExactTokensForETHSupportingFeeOnTransferTokens(
// uint256 amountIn,
// uint256 amountOutMin,
// address[] path,
// address to,
// uint256 deadline
// ) external;
// function swapExactTokensForTokens(
// uint256 amountIn,
// uint256 amountOutMin,
// address[] path,
// address to,
// uint256 deadline
// ) external returns (uint256[] amounts);
// function swapExactTokensForTokensSupportingFeeOnTransferTokens(
// uint256 amountIn,
// uint256 amountOutMin,
// address[] path,
// address to,
// uint256 deadline
// ) external;
// function swapTokensForExactETH(
// uint256 amountOut,
// uint256 amountInMax,
// address[] path,
// address to,
// uint256 deadline
// ) external returns (uint256[] amounts);
// function swapTokensForExactTokens(
// uint256 amountOut,
// uint256 amountInMax,
// address[] path,
// address to,
// uint256 deadline
// ) external returns (uint256[] amounts);
// }
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./BaseStrategy.sol";
import "../interfaces/curve/ICurveGauge.sol";
import "../interfaces/curve/ICurveMinter.sol";
import "../interfaces/curve/ICurveRegistry.sol";
import "../interfaces/curve/ICurveDeposit.sol";
import "../interfaces/curve/ICurveAddressProvider.sol";
import "../interfaces/sushiswap/IUniswapV2Router.sol";
/// @dev The base implementation for all Curve strategies. All strategies will add liquidity to a Curve pool (could be a plain or meta pool), and then deposit the LP tokens to the corresponding gauge to earn Curve tokens.
/// When it comes to harvest time, the Curve tokens will be minted and sold, and the profit will be reported and moved back to the vault.
/// The next time when harvest is called again, the profits from previous harvests will be invested again (if they haven't been withdrawn from the vault).
/// The Convex strategies are pretty much the same as the Curve ones, the only different is that the LP tokens are deposited into Convex instead, and it will take rewards from both Curve and Convex.
abstract contract CurveBase is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
// The address of the curve address provider. This address will never change is is the recommended way to get the address of their registry.
// See https://curve.readthedocs.io/registry-address-provider.html#
address private constant CURVE_ADDRESS_PROVIDER_ADDRESS = 0x0000000022D53366457F9d5E68Ec105046FC4383;
// Minter contract address will never change either. See https://curve.readthedocs.io/dao-gauges.html#minter
address private constant CURVE_MINTER_ADDRESS = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
address private constant CRV_TOKEN_ADDRESS = 0xD533a949740bb3306d119CC777fa900bA034cd52;
address private constant SUSHISWAP_ADDRESS = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
address private constant UNISWAP_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address private constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
// Curve token minter
ICurveMinter public curveMinter;
// Curve address provider, where we can query for the address of the registry
ICurveAddressProvider public curveAddressProvider;
// Curve pool. Can be either a plain pool, or meta pool, or Curve zap depositor (automatically add liquidity to base pool and then meta pool).
ICurveDeposit public curvePool;
// The Curve gauge corresponding to the Curve pool
ICurveGauge public curveGauge;
// Dex address for token swaps.
address public dex;
// Store dex approval status to avoid excessive approvals
mapping(address => bool) internal dexApprovals;
/// @param _vault The address of the vault. The underlying token should match the `want` token of the strategy.
/// @param _proposer The address of the strategy proposer
/// @param _developer The address of the strategy developer
/// @param _keeper The address of the keeper of the strategy.
/// @param _pool The address of the Curve pool
constructor(
address _vault,
address _proposer,
address _developer,
address _keeper,
address _pool
) BaseStrategy(_vault, _proposer, _developer, _keeper) {
require(_pool != address(0), "invalid pool address");
minReportDelay = 43_200; // 12hr
maxReportDelay = 259_200; // 72hr
profitFactor = 1000;
debtThreshold = 1e24;
dex = SUSHISWAP_ADDRESS;
_initCurvePool(_pool);
_approveOnInit();
}
/// @notice Approves pools/dexes to be spenders of the tokens of this strategy
function approveAll() external onlyAuthorized {
_approveBasic();
_approveDex();
}
/// @notice Changes the dex to use when swap tokens
/// @param _isUniswap If true, uses Uniswap, otherwise uses Sushiswap
function switchDex(bool _isUniswap) external onlyAuthorized {
if (_isUniswap) {
dex = UNISWAP_ADDRESS;
} else {
dex = SUSHISWAP_ADDRESS;
}
_approveDex();
}
/// @notice Returns the total value of assets in want tokens
/// @dev it should include the current balance of want tokens, the assets that are deployed and value of rewards so far
function estimatedTotalAssets() public view virtual override returns (uint256) {
return _balanceOfWant() + _balanceOfPool() + _balanceOfRewards();
}
/// @dev Before migration, we will claim all rewards and remove all liquidity.
function prepareMigration(address) internal override {
// mint all the CRV tokens
_claimRewards();
_removeLiquidity(_getLpTokenBalance());
}
// solhint-disable-next-line no-unused-vars
/// @dev This will perform the actual invest steps.
/// For both Curve & Convex, it will add liquidity to Curve pool(s) first, and then deposit the LP tokens to either Curve gauges or Convex booster.
function adjustPosition(uint256) internal virtual override {
if (emergencyExit) {
return;
}
_addLiquidityToCurvePool();
_depositLPTokens();
}
/// @dev This will claim the rewards from either Curve or Convex, swap them to want tokens and calculate the profit/loss.
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
uint256 wantBefore = _balanceOfWant();
_claimRewards();
uint256 wantNow = _balanceOfWant();
_profit = wantNow - wantBefore;
uint256 _total = estimatedTotalAssets();
uint256 _debt = IVault(vault).strategy(address(this)).totalDebt;
if (_total < _debt) {
_loss = _debt - _total;
_profit = 0;
}
if (_debtOutstanding > 0) {
_withdrawSome(_debtOutstanding);
_debtPayment = Math.min(_debtOutstanding, _balanceOfWant() - _profit);
}
}
/// @dev Liquidates the positions from either Curve or Convex.
function liquidatePosition(uint256 _amountNeeded)
internal
virtual
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
// cash out all the rewards first
_claimRewards();
uint256 _balance = _balanceOfWant();
if (_balance < _amountNeeded) {
_liquidatedAmount = _withdrawSome(_amountNeeded - _balance);
_liquidatedAmount = _liquidatedAmount + _balance;
_loss = _amountNeeded - _liquidatedAmount; // this should be 0. o/w there must be an error
} else {
_liquidatedAmount = _amountNeeded;
}
}
function protectedTokens() internal view virtual override returns (address[] memory) {
address[] memory protected = new address[](2);
protected[0] = _getCurveTokenAddress();
protected[1] = curveGauge.lp_token();
return protected;
}
/// @dev Can be used to perform some actions by the strategy, before the rewards are claimed (like call the checkpoint to update user rewards).
function onHarvest() internal virtual override {
// make sure the claimable rewards record is up to date
curveGauge.user_checkpoint(address(this));
}
/// @dev Initialises the state variables. Put them in a function to allow for testing. Testing contracts can override these.
function _initCurvePool(address _pool) internal virtual {
curveAddressProvider = ICurveAddressProvider(CURVE_ADDRESS_PROVIDER_ADDRESS);
curveMinter = ICurveMinter(CURVE_MINTER_ADDRESS);
curvePool = ICurveDeposit(_pool);
curveGauge = ICurveGauge(_getCurvePoolGaugeAddress());
}
function _approveOnInit() internal virtual {
_approveBasic();
_approveDex();
}
/// @dev Returns the balance of the `want` token.
function _balanceOfWant() internal view returns (uint256) {
return want.balanceOf(address(this));
}
/// @dev Returns total liquidity provided to Curve pools.
/// Can be overridden if the strategy has a different way to get the value of the pool.
function _balanceOfPool() internal view virtual returns (uint256) {
uint256 lpTokenAmount = _getLpTokenBalance();
if (lpTokenAmount > 0) {
uint256 outputAmount = curvePool.calc_withdraw_one_coin(lpTokenAmount, _int128(_getWantTokenIndex()));
return outputAmount;
}
return 0;
}
/// @dev Returns the estimated value of the unclaimed rewards.
function _balanceOfRewards() internal view virtual returns (uint256) {
uint256 totalClaimableCRV = curveGauge.integrate_fraction(address(this));
uint256 mintedCRV = curveMinter.minted(address(this), address(curveGauge));
uint256 remainingCRV = totalClaimableCRV - mintedCRV;
if (remainingCRV > 0) {
return _getQuoteForTokenToWant(_getCurveTokenAddress(), remainingCRV);
}
return 0;
}
/// @dev Swaps the `_from` token to the want token using either Uniswap or Sushiswap
function _swapToWant(address _from, uint256 _fromAmount) internal virtual returns (uint256) {
if (_fromAmount > 0) {
address[] memory path;
if (address(want) == _getWETHTokenAddress()) {
path = new address[](2);
path[0] = _from;
path[1] = address(want);
} else {
path = new address[](3);
path[0] = _from;
path[1] = address(_getWETHTokenAddress());
path[2] = address(want);
}
/* solhint-disable not-rely-on-time */
uint256[] memory amountOut = IUniswapV2Router(dex).swapExactTokensForTokens(
_fromAmount,
uint256(0),
path,
address(this),
block.timestamp
);
/* solhint-enable */
return amountOut[path.length - 1];
}
return 0;
}
/// @dev Deposits the LP tokens to Curve gauge.
function _depositLPTokens() internal virtual {
address poolLPToken = curveGauge.lp_token();
uint256 balance = IERC20(poolLPToken).balanceOf(address(this));
if (balance > 0) {
curveGauge.deposit(balance);
}
}
/// @dev Withdraws the given amount of want tokens from the Curve pools.
/// @param _amount The amount of *want* tokens (not LP token).
function _withdrawSome(uint256 _amount) internal virtual returns (uint256) {
uint256 requiredLPTokenAmount;
// check how many LP tokens we will need for the given want _amount
// not great, but can't find a better way to define the params dynamically based on the coins count
if (_getCoinsCount() == 2) {
uint256[2] memory params;
params[_getWantTokenIndex()] = _amount;
requiredLPTokenAmount = (curvePool.calc_token_amount(params, true) * 10200) / 10000; // adding 2% padding
} else if (_getCoinsCount() == 3) {
uint256[3] memory params;
params[_getWantTokenIndex()] = _amount;
requiredLPTokenAmount = (curvePool.calc_token_amount(params, true) * 10200) / 10000; // adding 2% padding
} else if (_getCoinsCount() == 4) {
uint256[4] memory params;
params[_getWantTokenIndex()] = _amount;
requiredLPTokenAmount = (curvePool.calc_token_amount(params, true) * 10200) / 10000; // adding 2% padding
} else {
revert("Invalid number of LP tokens");
}
// decide how many LP tokens we can actually withdraw
return _removeLiquidity(requiredLPTokenAmount);
}
/// @dev Removes the liquidity by the LP token amount
/// @param _amount The amount of LP token (not want token)
function _removeLiquidity(uint256 _amount) internal virtual returns (uint256) {
uint256 balance = _getLpTokenBalance();
uint256 withdrawAmount = Math.min(_amount, balance);
// withdraw this amount of token from the gauge first
_removeLpToken(withdrawAmount);
// then remove the liqudity from the pool, will get eth back
uint256 amount = curvePool.remove_liquidity_one_coin(withdrawAmount, _int128(_getWantTokenIndex()), 0);
return amount;
}
/// @dev Returns the total amount of Curve LP tokens the strategy has
function _getLpTokenBalance() internal view virtual returns (uint256) {
return curveGauge.balanceOf(address(this));
}
/// @dev Withdraws the given amount of LP tokens from Curve gauge
/// @param _amount The amount of LP tokens to withdraw
function _removeLpToken(uint256 _amount) internal virtual {
curveGauge.withdraw(_amount);
}
/// @dev Claims the curve rewards tokens and swap them to want tokens
function _claimRewards() internal virtual {
curveMinter.mint(address(curveGauge));
uint256 crvBalance = IERC20(_getCurveTokenAddress()).balanceOf(address(this));
_swapToWant(_getCurveTokenAddress(), crvBalance);
}
/// @dev Returns the address of the pool LP token. Use a function to allow override in sub contracts to allow for unit testing.
function _getPoolLPTokenAddress(address _pool) internal virtual returns (address) {
require(_pool != address(0), "invalid pool address");
address registry = curveAddressProvider.get_registry();
return ICurveRegistry(registry).get_lp_token(address(_pool));
}
/// @dev Returns the address of the curve gauge. It will use the Curve registry to look up the gauge for a Curve pool.
/// Use a function to allow override in sub contracts to allow for unit testing.
function _getCurvePoolGaugeAddress() internal view virtual returns (address) {
address registry = curveAddressProvider.get_registry();
(address[10] memory gauges, ) = ICurveRegistry(registry).get_gauges(address(curvePool));
// This only usese the first gauge of the pool. Should be enough for most cases, however, if this is not the case, then this method should be overriden
return gauges[0];
}
/// @dev Returns the address of the Curve token. Use a function to allow override in sub contracts to allow for unit testing.
function _getCurveTokenAddress() internal view virtual returns (address) {
return CRV_TOKEN_ADDRESS;
}
/// @dev Returns the address of the WETH token. Use a function to allow override in sub contracts to allow for unit testing.
function _getWETHTokenAddress() internal view virtual returns (address) {
return WETH_ADDRESS;
}
/// @dev Gets an estimate value in want token for the given amount of given token using the dex.
function _getQuoteForTokenToWant(address _from, uint256 _fromAmount) internal view virtual returns (uint256) {
if (_fromAmount > 0) {
address[] memory path;
if (address(want) == _getWETHTokenAddress()) {
path = new address[](2);
path[0] = _from;
path[1] = address(want);
} else {
path = new address[](3);
path[0] = _from;
path[1] = address(_getWETHTokenAddress());
path[2] = address(want);
}
uint256[] memory amountOut = IUniswapV2Router(dex).getAmountsOut(_fromAmount, path);
return amountOut[path.length - 1];
}
return 0;
}
/// @dev Approves Curve pools/gauges/rewards contracts to access the tokens in the strategy
function _approveBasic() internal virtual {
IERC20(curveGauge.lp_token()).safeApprove(address(curveGauge), type(uint256).max);
}
/// @dev Approves dex to access tokens in the strategy for swaps
function _approveDex() internal virtual {
if (!dexApprovals[dex]) {
dexApprovals[dex] = true;
IERC20(_getCurveTokenAddress()).safeApprove(dex, type(uint256).max);
}
}
// does not deal with over/under flow
function _int128(uint256 _val) internal pure returns (int128) {
return int128(uint128(_val));
}
/// @dev This needs to be overridden by the concrete strategyto implement how liquidity will be added to Curve pools
function _addLiquidityToCurvePool() internal virtual;
/// @dev Returns the index of the want token for a Curve pool
function _getWantTokenIndex() internal view virtual returns (uint256);
/// @dev Returns the total number of coins the Curve pool supports
function _getCoinsCount() internal view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "../interfaces/IVault.sol";
import "../interfaces/IStrategy.sol";
/**
*
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy is IStrategy, ERC165 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.0.1";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
address public vault;
address public strategyProposer;
address public strategyDeveloper;
address public rewards;
address public harvester;
IERC20 public want;
// So indexers can keep track of this
event UpdatedStrategyProposer(address strategyProposer);
event UpdatedStrategyDeveloper(address strategyDeveloper);
event UpdatedHarvester(address newHarvester);
event UpdatedVault(address vault);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(
msg.sender == strategyProposer || msg.sender == strategyDeveloper || msg.sender == governance(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategyProposer || msg.sender == strategyDeveloper, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == harvester ||
msg.sender == strategyProposer ||
msg.sender == strategyDeveloper ||
msg.sender == governance(),
"!authorized"
);
_;
}
constructor(
address _vault,
address _strategyProposer,
address _strategyDeveloper,
address _harvester
) {
_initialize(_vault, _strategyProposer, _strategyDeveloper, _harvester);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
function _initialize(
address _vault,
address _strategyProposer,
address _strategyDeveloper,
address _harvester
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = _vault;
want = IERC20(IVault(vault).token());
checkWantToken();
want.safeApprove(_vault, type(uint256).max); // Give Vault unlimited access (might save gas)
strategyProposer = _strategyProposer;
strategyDeveloper = _strategyDeveloper;
harvester = _harvester;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
}
/**
* @notice
* Used to change `_strategyProposer`.
*
* This may only be called by governance or the existing strategist.
* @param _strategyProposer The new address to assign as `strategist`.
*/
function setStrategyProposer(address _strategyProposer) external onlyAuthorized {
require(_strategyProposer != address(0), "! address 0");
strategyProposer = _strategyProposer;
emit UpdatedStrategyProposer(_strategyProposer);
}
function setStrategyDeveloper(address _strategyDeveloper) external onlyAuthorized {
require(_strategyDeveloper != address(0), "! address 0");
strategyDeveloper = _strategyDeveloper;
emit UpdatedStrategyDeveloper(_strategyDeveloper);
}
/**
* @notice
* Used to change `harvester`.
*
* `harvester` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `harvester` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _harvester The new address to assign as `keeper`.
*/
function setHarvester(address _harvester) external onlyAuthorized {
require(_harvester != address(0), "! address 0");
harvester = _harvester;
emit UpdatedHarvester(_harvester);
}
function setVault(address _vault) external onlyAuthorized {
require(_vault != address(0), "! address 0");
vault = _vault;
emit UpdatedVault(_vault);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return IVault(vault).governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return IVault(vault).strategyDebtRatio(address(this)) > 0 || estimatedTotalAssets() > 0;
}
/*
* @notice
* Support ERC165 spec to allow other contracts to query if a strategy has implemented IStrategy interface
*/
function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) {
return _interfaceId == type(IStrategy).interfaceId || super.supportsInterface(_interfaceId);
}
/// @notice check the want token to make sure it is the token that the strategy is expecting
// solhint-disable-next-line no-empty-blocks
function checkWantToken() internal view virtual {
// by default this will do nothing. But child strategies can override this and validate the want token
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other situation at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
// solhint-disable-next-line no-unused-vars
function tendTrigger(uint256) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintenance, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(IVault(vault).debtOutstanding(address(this)));
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public view virtual returns (bool) {
StrategyInfo memory params = IVault(vault).strategy(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (timestamp().sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (timestamp().sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = IVault(vault).debtOutstanding(address(this));
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = IVault(vault).creditAvailable(address(this));
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice All the strategy to do something when harvest is called.
*/
// solhint-disable-next-line no-empty-blocks
function onHarvest() internal virtual {}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = IVault(vault).debtOutstanding(address(this));
uint256 debtPayment = 0;
onHarvest();
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = IVault(vault).report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance(), "!authorised");
require(BaseStrategy(_newStrategy).vault() == vault, "invalid vault");
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
IVault(vault).revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) {
require(_token != _protectedTokens[i], "!protected");
}
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
function timestamp() internal view virtual returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
interface ICurveRegistry {
function get_lp_token(address _pool) external view returns (address);
function get_gauges(address _pool) external view returns (address[10] memory, address[10] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
interface ICurveAddressProvider {
function get_registry() external view returns (address);
}
// 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 (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
pragma solidity =0.8.9;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
struct StrategyInfo {
uint256 activation;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
interface IVault is IERC20, IERC20Permit {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint256);
function activation() external view returns (uint256);
function rewards() external view returns (address);
function managementFee() external view returns (uint256);
function gatekeeper() external view returns (address);
function governance() external view returns (address);
function creator() external view returns (address);
function strategyDataStore() external view returns (address);
function healthCheck() external view returns (address);
function emergencyShutdown() external view returns (bool);
function lockedProfitDegradation() external view returns (uint256);
function depositLimit() external view returns (uint256);
function lastReport() external view returns (uint256);
function lockedProfit() external view returns (uint256);
function totalDebt() external view returns (uint256);
function token() external view returns (address);
function totalAsset() external view returns (uint256);
function availableDepositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
function pricePerShare() external view returns (uint256);
function debtOutstanding(address _strategy) external view returns (uint256);
function creditAvailable(address _strategy) external view returns (uint256);
function expectedReturn(address _strategy) external view returns (uint256);
function strategy(address _strategy) external view returns (StrategyInfo memory);
function strategyDebtRatio(address _strategy) external view returns (uint256);
function setRewards(address _rewards) external;
function setManagementFee(uint256 _managementFee) external;
function setGatekeeper(address _gatekeeper) external;
function setStrategyDataStore(address _strategyDataStoreContract) external;
function setHealthCheck(address _healthCheck) external;
function setVaultEmergencyShutdown(bool _active) external;
function setLockedProfileDegradation(uint256 _degradation) external;
function setDepositLimit(uint256 _limit) external;
function sweep(address _token, uint256 _amount) external;
function addStrategy(address _strategy) external returns (bool);
function migrateStrategy(address _oldVersion, address _newVersion) external returns (bool);
function revokeStrategy() external;
/// @notice deposit the given amount into the vault, and return the number of shares
function deposit(uint256 _amount, address _recipient) external returns (uint256);
/// @notice burn the given amount of shares from the vault, and return the number of underlying tokens recovered
function withdraw(
uint256 _shares,
address _recipient,
uint256 _maxLoss
) external returns (uint256);
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IStrategy {
// *** Events *** //
event Harvested(uint256 _profit, uint256 _loss, uint256 _debtPayment, uint256 _debtOutstanding);
event StrategistUpdated(address _newStrategist);
event KeeperUpdated(address _newKeeper);
event MinReportDelayUpdated(uint256 _delay);
event MaxReportDelayUpdated(uint256 _delay);
event ProfitFactorUpdated(uint256 _profitFactor);
event DebtThresholdUpdated(uint256 _debtThreshold);
event EmergencyExitEnabled();
// *** The following functions are used by the Vault *** //
/// @notice returns the address of the token that the strategy wants
function want() external view returns (IERC20);
/// @notice the address of the Vault that the strategy belongs to
function vault() external view returns (address);
/// @notice if the strategy is active
function isActive() external view returns (bool);
/// @notice migrate the strategy to the new one
function migrate(address _newStrategy) external;
/// @notice withdraw the amount from the strategy
function withdraw(uint256 _amount) external returns (uint256);
/// @notice the amount of total assets managed by this strategy that should not account towards the TVL of the strategy
function delegatedAssets() external view returns (uint256);
/// @notice the total assets that the strategy is managing
function estimatedTotalAssets() external view returns (uint256);
// *** public read functions that can be called by anyone *** //
function name() external view returns (string memory);
function harvester() external view returns (address);
function strategyProposer() external view returns (address);
function strategyDeveloper() external view returns (address);
function tendTrigger(uint256 _callCost) external view returns (bool);
function harvestTrigger(uint256 _callCost) external view returns (bool);
// *** write functions that can be called by the governance, the strategist or the keeper *** //
function tend() external;
function harvest() external;
// *** write functions that can be called by the governance or the strategist ***//
function setHarvester(address _havester) external;
function setVault(address _vault) external;
/// @notice `minReportDelay` is the minimum number of blocks that should pass for `harvest()` to be called.
function setMinReportDelay(uint256 _delay) external;
function setMaxReportDelay(uint256 _delay) external;
/// @notice `profitFactor` is used to determine if it's worthwhile to harvest, given gas costs.
function setProfitFactor(uint256 _profitFactor) external;
/// @notice Sets how far the Strategy can go into loss without a harvest and report being required.
function setDebtThreshold(uint256 _debtThreshold) external;
// *** write functions that can be called by the governance, or the strategist, or the guardian, or the management *** //
function setEmergencyExit() external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
address private immutable _CACHED_THIS;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_CACHED_THIS = address(this);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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
pragma solidity =0.8.9;
interface IConvexDeposit {
struct PoolInfo {
address lptoken;
address token;
address gauge;
address crvRewards;
address stash;
bool shutdown;
}
function poolInfo(uint256)
external
view
returns (
address,
address,
address,
address,
address,
bool
);
// deposit lp tokens and stake
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
// deposit all lp tokens and stake
function depositAll(uint256 _pid, bool _stake) external returns (bool);
function poolLength() external view returns (uint256);
// withdraw lp tokens
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
// withdraw all lp tokens
function withdrawAll(uint256 _pid) external returns (bool);
// claim crv + extra rewards
function earmarkRewards(uint256 _pid) external returns (bool);
// claim rewards on stash (msg.sender == stash)
function claimRewards(uint256 _pid, address _gauge) external returns (bool);
// delegate address votes on dao (needs to be voteDelegate)
function vote(
uint256 _voteId,
address _votingAddress,
bool _support
) external returns (bool);
function voteGaugeWeight(address[] calldata _gauge, uint256[] calldata _weight) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.9;
interface IConvexRewards {
// strategy's staked balance in the synthetix staking contract
function balanceOf(address account) external view returns (uint256);
// read how much claimable CRV a strategy has
function earned(address account) external view returns (uint256);
// stake a convex tokenized deposit
function stake(uint256 _amount) external returns (bool);
// withdraw to a convex tokenized deposit, probably never need to use this
function withdraw(uint256 _amount, bool _claim) external returns (bool);
// withdraw directly to curve LP token, this is what we primarily use
function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool);
// claim rewards, with an option to claim extra rewards or not
function getReward(address _account, bool _claimExtras) external returns (bool);
} | Initialises the state variables. Put them in a function to allow for testing. Testing contracts can override these. | function _initCurvePool(address _pool) internal virtual {
curveAddressProvider = ICurveAddressProvider(CURVE_ADDRESS_PROVIDER_ADDRESS);
curveMinter = ICurveMinter(CURVE_MINTER_ADDRESS);
curvePool = ICurveDeposit(_pool);
curveGauge = ICurveGauge(_getCurvePoolGaugeAddress());
}
| 519,079 |
./full_match/80001/0xD238dD70E5376DA21274717eaa6053075c8b62b4/sources/contracts/TraderBalanceVault/TraderBalanceVault.sol | @inheritdoc ITraderBalanceVault/ | function withdrawFrom(
address _from,
address _to,
address _asset,
uint256 _amount,
bool fromLocked
) external override onlyRole(VAULT_ACCESS_ROLE) {
if (fromLocked) {
_require(balances[_from][_asset].lockedBalance >= _amount, Errors.INSUFFICIENT_FREE_ASSETS.selector);
balances[_from][_asset].lockedBalance -= _amount;
_require(balances[_from][_asset].availableBalance >= _amount, Errors.INSUFFICIENT_FREE_ASSETS.selector);
balances[_from][_asset].availableBalance -= _amount;
}
if (_asset == NATIVE_CURRENCY) {
TokenTransfersLibrary.doTransferOutETH(_to, _amount);
TokenTransfersLibrary.doTransferOut(_asset, _to, _amount);
}
}
| 9,522,276 |
./full_match/1/0xb867dF3efF1B234CA08B7D0d85Fb51Fd25C2c2d0/sources/contracts/v2/strategies/RamosStrategy.sol | Shutdown the strategy. First unstake all BPT and liquidate into temple & stables, and then repay to the TRV. shutdownData abi encoded data of struct `PopulateShutdownParams`/ | function _doShutdown(bytes calldata shutdownData) internal virtual override {
(ShutdownParams memory params) = abi.decode(shutdownData, (ShutdownParams));
ramos.removeLiquidity(params.requestData, params.bptAmount);
uint256 stableBalance = quoteToken.balanceOf(address(this));
if (stableBalance > 0) {
treasuryReservesVault.repay(quoteToken, stableBalance, address(this));
}
uint256 templeBalance = templeToken.balanceOf(address(this));
if (templeBalance > 0) {
treasuryReservesVault.repay(templeToken, templeBalance, address(this));
}
}
| 3,120,050 |
./partial_match/1/0xeEFe0487f16082cABef73974aD689D3F55544240/sources/PitchHero.sol | The ETH balance of the account is not enough to perform the operation./ There's no code at `target` (it is not a contract)./ A call to an address target failed. The target may have reverted./ Replacement for Solidity's `transfer`: sends `amount` wei to `recipient`, forwarding all available gas and reverting on errors. 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. IMPORTANT: because control is transferred to `recipient`, care must be taken to not create reentrancy vulnerabilities. Consider using {ReentrancyGuard} or the/ | function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
if (!success) {
revert FailedInnerCall();
}
}
| 2,649,760 |
// File: contracts\lib\TransferHelper.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.6;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: contracts\interface\INestMining.sol
/// @dev This interface defines the mining methods for nest
interface INestMining {
/// @dev Post event
/// @param tokenAddress The address of TOKEN contract
/// @param miner Address of miner
/// @param index Index of the price sheet
/// @param ethNum The numbers of ethers to post sheets
event Post(address tokenAddress, address miner, uint index, uint ethNum, uint price);
/* ========== Structures ========== */
/// @dev Nest mining configuration structure
struct Config {
// Eth number of each post. 30
// We can stop post and taking orders by set postEthUnit to 0 (closing and withdraw are not affected)
uint32 postEthUnit;
// Post fee(0.0001eth,DIMI_ETHER). 1000
uint16 postFeeUnit;
// Proportion of miners digging(10000 based). 8000
uint16 minerNestReward;
// The proportion of token dug by miners is only valid for the token created in version 3.0
// (10000 based). 9500
uint16 minerNTokenReward;
// When the circulation of ntoken exceeds this threshold, post() is prohibited(Unit: 10000 ether). 500
uint32 doublePostThreshold;
// The limit of ntoken mined blocks. 100
uint16 ntokenMinedBlockLimit;
// -- Public configuration
// The number of times the sheet assets have doubled. 4
uint8 maxBiteNestedLevel;
// Price effective block interval. 20
uint16 priceEffectSpan;
// The amount of nest to pledge for each post(Unit: 1000). 100
uint16 pledgeNest;
}
/// @dev PriceSheetView structure
struct PriceSheetView {
// Index of the price sheeet
uint32 index;
// Address of miner
address miner;
// The block number of this price sheet packaged
uint32 height;
// The remain number of this price sheet
uint32 remainNum;
// The eth number which miner will got
uint32 ethNumBal;
// The eth number which equivalent to token's value which miner will got
uint32 tokenNumBal;
// The pledged number of nest in this sheet. (Unit: 1000nest)
uint24 nestNum1k;
// The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet
uint8 level;
// Post fee shares, if there are many sheets in one block, this value is used to divide up mining value
uint8 shares;
// The token price. (1eth equivalent to (price) token)
uint152 price;
}
/* ========== Configuration ========== */
/// @dev Modify configuration
/// @param config Configuration object
function setConfig(Config calldata config) external;
/// @dev Get configuration
/// @return Configuration object
function getConfig() external view returns (Config memory);
/// @dev Set the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled
/// @param tokenAddress Destination token address
/// @param ntokenAddress The ntoken address
function setNTokenAddress(address tokenAddress, address ntokenAddress) external;
/// @dev Get the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled
/// @param tokenAddress Destination token address
/// @return The ntoken address
function getNTokenAddress(address tokenAddress) external view returns (address);
/* ========== Mining ========== */
/// @notice Post a price sheet for TOKEN
/// @dev It is for TOKEN (except USDT and NTOKENs) whose NTOKEN has a total supply below a threshold (e.g. 5,000,000 * 1e18)
/// @param tokenAddress The address of TOKEN contract
/// @param ethNum The numbers of ethers to post sheets
/// @param tokenAmountPerEth The price of TOKEN
function post(address tokenAddress, uint ethNum, uint tokenAmountPerEth) external payable;
/// @notice Post two price sheets for a token and its ntoken simultaneously
/// @dev Support dual-posts for TOKEN/NTOKEN, (ETH, TOKEN) + (ETH, NTOKEN)
/// @param tokenAddress The address of TOKEN contract
/// @param ethNum The numbers of ethers to post sheets
/// @param tokenAmountPerEth The price of TOKEN
/// @param ntokenAmountPerEth The price of NTOKEN
function post2(address tokenAddress, uint ethNum, uint tokenAmountPerEth, uint ntokenAmountPerEth) external payable;
/// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet
/// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal)
/// @param tokenAddress The address of token(ntoken)
/// @param index The position of the sheet in priceSheetList[token]
/// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth
/// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth
function takeToken(address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth) external payable;
/// @notice Call the function to buy ETH from a posted price sheet
/// @dev bite ETH by TOKEN(NTOKEN), (-ethNumBal, +tokenNumBal)
/// @param tokenAddress The address of token(ntoken)
/// @param index The position of the sheet in priceSheetList[token]
/// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum
/// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth
function takeEth(address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth) external payable;
/// @notice Close a price sheet of (ETH, USDx) | (ETH, NEST) | (ETH, TOKEN) | (ETH, NTOKEN)
/// @dev Here we allow an empty price sheet (still in VERIFICATION-PERIOD) to be closed
/// @param tokenAddress The address of TOKEN contract
/// @param index The index of the price sheet w.r.t. `token`
function close(address tokenAddress, uint index) external;
/// @notice Close a batch of price sheets passed VERIFICATION-PHASE
/// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed
/// @param tokenAddress The address of TOKEN contract
/// @param indices A list of indices of sheets w.r.t. `token`
function closeList(address tokenAddress, uint[] memory indices) external;
/// @notice Close two batch of price sheets passed VERIFICATION-PHASE
/// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed
/// @param tokenAddress The address of TOKEN1 contract
/// @param tokenIndices A list of indices of sheets w.r.t. `token`
/// @param ntokenIndices A list of indices of sheets w.r.t. `ntoken`
function closeList2(address tokenAddress, uint[] memory tokenIndices, uint[] memory ntokenIndices) external;
/// @dev The function updates the statistics of price sheets
/// It calculates from priceInfo to the newest that is effective.
function stat(address tokenAddress) external;
/// @dev Settlement Commission
/// @param tokenAddress The token address
function settle(address tokenAddress) external;
/// @dev List sheets by page
/// @param tokenAddress Destination token address
/// @param offset Skip previous (offset) records
/// @param count Return (count) records
/// @param order Order. 0 reverse order, non-0 positive order
/// @return List of price sheets
function list(address tokenAddress, uint offset, uint count, uint order) external view returns (PriceSheetView[] memory);
/// @dev Estimated mining amount
/// @param tokenAddress Destination token address
/// @return Estimated mining amount
function estimate(address tokenAddress) external view returns (uint);
/// @dev Query the quantity of the target quotation
/// @param tokenAddress Token address. The token can't mine. Please make sure you don't use the token address when calling
/// @param index The index of the sheet
/// @return minedBlocks Mined block period from previous block
/// @return totalShares Total shares of sheets in the block
function getMinedBlocks(address tokenAddress, uint index) external view returns (uint minedBlocks, uint totalShares);
/* ========== Accounts ========== */
/// @dev Withdraw assets
/// @param tokenAddress Destination token address
/// @param value The value to withdraw
function withdraw(address tokenAddress, uint value) external;
/// @dev View the number of assets specified by the user
/// @param tokenAddress Destination token address
/// @param addr Destination address
/// @return Number of assets
function balanceOf(address tokenAddress, address addr) external view returns (uint);
/// @dev Gets the address corresponding to the given index number
/// @param index The index number of the specified address
/// @return The address corresponding to the given index number
function indexAddress(uint index) external view returns (address);
/// @dev Gets the registration index number of the specified address
/// @param addr Destination address
/// @return 0 means nonexistent, non-0 means index number
function getAccountIndex(address addr) external view returns (uint);
/// @dev Get the length of registered account array
/// @return The length of registered account array
function getAccountCount() external view returns (uint);
}
// File: contracts\interface\INestQuery.sol
/// @dev This interface defines the methods for price query
interface INestQuery {
/// @dev Get the latest trigger price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function triggeredPrice(address tokenAddress) external view returns (uint blockNumber, uint price);
/// @dev Get the full information of latest trigger price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo(address tokenAddress) external view returns (
uint blockNumber,
uint price,
uint avgPrice,
uint sigmaSQ
);
/// @dev Find the price at block number
/// @param tokenAddress Destination token address
/// @param height Destination block number
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function findPrice(
address tokenAddress,
uint height
) external view returns (uint blockNumber, uint price);
/// @dev Get the latest effective price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function latestPrice(address tokenAddress) external view returns (uint blockNumber, uint price);
/// @dev Get the last (num) effective price
/// @param tokenAddress Destination token address
/// @param count The number of prices that want to return
/// @return An array which length is num * 2, each two element expresses one price like blockNumber|price
function lastPriceList(address tokenAddress, uint count) external view returns (uint[] memory);
/// @dev Returns the results of latestPrice() and triggeredPriceInfo()
/// @param tokenAddress Destination token address
/// @return latestPriceBlockNumber The block number of latest price
/// @return latestPriceValue The token latest price. (1eth equivalent to (price) token)
/// @return triggeredPriceBlockNumber The block number of triggered price
/// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// @return triggeredAvgPrice Average price
/// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function latestPriceAndTriggeredPriceInfo(address tokenAddress) external view
returns (
uint latestPriceBlockNumber,
uint latestPriceValue,
uint triggeredPriceBlockNumber,
uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
);
/// @dev Returns lastPriceList and triggered price info
/// @param tokenAddress Destination token address
/// @param count The number of prices that want to return
/// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price
/// @return triggeredPriceBlockNumber The block number of triggered price
/// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// @return triggeredAvgPrice Average price
/// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function lastPriceListAndTriggeredPriceInfo(address tokenAddress, uint count) external view
returns (
uint[] memory prices,
uint triggeredPriceBlockNumber,
uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
);
/// @dev Get the latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function triggeredPrice2(address tokenAddress) external view returns (
uint blockNumber,
uint price,
uint ntokenBlockNumber,
uint ntokenPrice
);
/// @dev Get the full information of latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
/// @return ntokenAvgPrice Average price of ntoken
/// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo2(address tokenAddress) external view returns (
uint blockNumber,
uint price,
uint avgPrice,
uint sigmaSQ,
uint ntokenBlockNumber,
uint ntokenPrice,
uint ntokenAvgPrice,
uint ntokenSigmaSQ
);
/// @dev Get the latest effective price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function latestPrice2(address tokenAddress) external view returns (
uint blockNumber,
uint price,
uint ntokenBlockNumber,
uint ntokenPrice
);
}
// File: contracts\interface\INTokenController.sol
///@dev This interface defines the methods for ntoken management
interface INTokenController {
/// @notice when the auction of a token gets started
/// @param tokenAddress The address of the (ERC20) token
/// @param ntokenAddress The address of the ntoken w.r.t. token for incentives
/// @param owner The address of miner who opened the oracle
event NTokenOpened(address tokenAddress, address ntokenAddress, address owner);
/// @notice ntoken disable event
/// @param tokenAddress token address
event NTokenDisabled(address tokenAddress);
/// @notice ntoken enable event
/// @param tokenAddress token address
event NTokenEnabled(address tokenAddress);
/// @dev ntoken configuration structure
struct Config {
// The number of nest needed to pay for opening ntoken. 10000 ether
uint96 openFeeNestAmount;
// ntoken management is enabled. 0: not enabled, 1: enabled
uint8 state;
}
/// @dev A struct for an ntoken
struct NTokenTag {
// ntoken address
address ntokenAddress;
// How much nest has paid for open this ntoken
uint96 nestFee;
// token address
address tokenAddress;
// Index for this ntoken
uint40 index;
// Create time
uint48 startTime;
// State of this ntoken. 0: disabled; 1 normal
uint8 state;
}
/* ========== Governance ========== */
/// @dev Modify configuration
/// @param config Configuration object
function setConfig(Config calldata config) external;
/// @dev Get configuration
/// @return Configuration object
function getConfig() external view returns (Config memory);
/// @dev Set the token mapping
/// @param tokenAddress Destination token address
/// @param ntokenAddress Destination ntoken address
/// @param state status for this map
function setNTokenMapping(address tokenAddress, address ntokenAddress, uint state) external;
/// @dev Get token address from ntoken address
/// @param ntokenAddress Destination ntoken address
/// @return token address
function getTokenAddress(address ntokenAddress) external view returns (address);
/// @dev Get ntoken address from token address
/// @param tokenAddress Destination token address
/// @return ntoken address
function getNTokenAddress(address tokenAddress) external view returns (address);
/* ========== ntoken management ========== */
/// @dev Bad tokens should be banned
function disable(address tokenAddress) external;
/// @dev enable ntoken
function enable(address tokenAddress) external;
/// @notice Open a NToken for a token by anyone (contracts aren't allowed)
/// @dev Create and map the (Token, NToken) pair in NestPool
/// @param tokenAddress The address of token contract
function open(address tokenAddress) external;
/* ========== VIEWS ========== */
/// @dev Get ntoken information
/// @param tokenAddress Destination token address
/// @return ntoken information
function getNTokenTag(address tokenAddress) external view returns (NTokenTag memory);
/// @dev Get opened ntoken count
/// @return ntoken count
function getNTokenCount() external view returns (uint);
/// @dev List ntoken information by page
/// @param offset Skip previous (offset) records
/// @param count Return (count) records
/// @param order Order. 0 reverse order, non-0 positive order
/// @return ntoken information by page
function list(uint offset, uint count, uint order) external view returns (NTokenTag[] memory);
}
// File: contracts\interface\INestLedger.sol
/// @dev This interface defines the nest ledger methods
interface INestLedger {
/// @dev Application Flag Changed event
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
event ApplicationChanged(address addr, uint flag);
/// @dev Configuration structure of nest ledger contract
struct Config {
// nest reward scale(10000 based). 2000
uint16 nestRewardScale;
// // ntoken reward scale(10000 based). 8000
// uint16 ntokenRewardScale;
}
/// @dev Modify configuration
/// @param config Configuration object
function setConfig(Config calldata config) external;
/// @dev Get configuration
/// @return Configuration object
function getConfig() external view returns (Config memory);
/// @dev Set DAO application
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
function setApplication(address addr, uint flag) external;
/// @dev Check DAO application flag
/// @param addr DAO application contract address
/// @return Authorization flag, 1 means authorization, 0 means cancel authorization
function checkApplication(address addr) external view returns (uint);
/// @dev Carve reward
/// @param ntokenAddress Destination ntoken address
function carveETHReward(address ntokenAddress) external payable;
/// @dev Add reward
/// @param ntokenAddress Destination ntoken address
function addETHReward(address ntokenAddress) external payable;
/// @dev The function returns eth rewards of specified ntoken
/// @param ntokenAddress The ntoken address
function totalETHRewards(address ntokenAddress) external view returns (uint);
/// @dev Pay
/// @param ntokenAddress Destination ntoken address. Indicates which ntoken to pay with
/// @param tokenAddress Token address of receiving funds (0 means ETH)
/// @param to Address to receive
/// @param value Amount to receive
function pay(address ntokenAddress, address tokenAddress, address to, uint value) external;
/// @dev Settlement
/// @param ntokenAddress Destination ntoken address. Indicates which ntoken to settle with
/// @param tokenAddress Token address of receiving funds (0 means ETH)
/// @param to Address to receive
/// @param value Amount to receive
function settle(address ntokenAddress, address tokenAddress, address to, uint value) external payable;
}
// File: contracts\interface\INToken.sol
/// @dev ntoken interface
interface INToken {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/// @dev Mint
/// @param value The amount of NToken to add
function increaseTotal(uint256 value) external;
/// @notice The view of variables about minting
/// @dev The naming follows Nestv3.0
/// @return createBlock The block number where the contract was created
/// @return recentlyUsedBlock The block number where the last minting went
function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock);
/// @dev The ABI keeps unchanged with old NTokens, so as to support token-and-ntoken-mining
/// @return The address of bidder
function checkBidder() external view returns(address);
/// @notice The view of totalSupply
/// @return The total supply of ntoken
function totalSupply() external view returns (uint256);
/// @dev The view of balances
/// @param owner The address of an account
/// @return The balance of the account
function balanceOf(address owner) 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);
}
// File: contracts\interface\INestMapping.sol
/// @dev The interface defines methods for nest builtin contract address mapping
interface INestMapping {
/// @dev Set the built-in contract address of the system
/// @param nestTokenAddress Address of nest token contract
/// @param nestNodeAddress Address of nest node contract
/// @param nestLedgerAddress INestLedger implementation contract address
/// @param nestMiningAddress INestMining implementation contract address for nest
/// @param ntokenMiningAddress INestMining implementation contract address for ntoken
/// @param nestPriceFacadeAddress INestPriceFacade implementation contract address
/// @param nestVoteAddress INestVote implementation contract address
/// @param nestQueryAddress INestQuery implementation contract address
/// @param nnIncomeAddress NNIncome contract address
/// @param nTokenControllerAddress INTokenController implementation contract address
function setBuiltinAddress(
address nestTokenAddress,
address nestNodeAddress,
address nestLedgerAddress,
address nestMiningAddress,
address ntokenMiningAddress,
address nestPriceFacadeAddress,
address nestVoteAddress,
address nestQueryAddress,
address nnIncomeAddress,
address nTokenControllerAddress
) external;
/// @dev Get the built-in contract address of the system
/// @return nestTokenAddress Address of nest token contract
/// @return nestNodeAddress Address of nest node contract
/// @return nestLedgerAddress INestLedger implementation contract address
/// @return nestMiningAddress INestMining implementation contract address for nest
/// @return ntokenMiningAddress INestMining implementation contract address for ntoken
/// @return nestPriceFacadeAddress INestPriceFacade implementation contract address
/// @return nestVoteAddress INestVote implementation contract address
/// @return nestQueryAddress INestQuery implementation contract address
/// @return nnIncomeAddress NNIncome contract address
/// @return nTokenControllerAddress INTokenController implementation contract address
function getBuiltinAddress() external view returns (
address nestTokenAddress,
address nestNodeAddress,
address nestLedgerAddress,
address nestMiningAddress,
address ntokenMiningAddress,
address nestPriceFacadeAddress,
address nestVoteAddress,
address nestQueryAddress,
address nnIncomeAddress,
address nTokenControllerAddress
);
/// @dev Get address of nest token contract
/// @return Address of nest token contract
function getNestTokenAddress() external view returns (address);
/// @dev Get address of nest node contract
/// @return Address of nest node contract
function getNestNodeAddress() external view returns (address);
/// @dev Get INestLedger implementation contract address
/// @return INestLedger implementation contract address
function getNestLedgerAddress() external view returns (address);
/// @dev Get INestMining implementation contract address for nest
/// @return INestMining implementation contract address for nest
function getNestMiningAddress() external view returns (address);
/// @dev Get INestMining implementation contract address for ntoken
/// @return INestMining implementation contract address for ntoken
function getNTokenMiningAddress() external view returns (address);
/// @dev Get INestPriceFacade implementation contract address
/// @return INestPriceFacade implementation contract address
function getNestPriceFacadeAddress() external view returns (address);
/// @dev Get INestVote implementation contract address
/// @return INestVote implementation contract address
function getNestVoteAddress() external view returns (address);
/// @dev Get INestQuery implementation contract address
/// @return INestQuery implementation contract address
function getNestQueryAddress() external view returns (address);
/// @dev Get NNIncome contract address
/// @return NNIncome contract address
function getNnIncomeAddress() external view returns (address);
/// @dev Get INTokenController implementation contract address
/// @return INTokenController implementation contract address
function getNTokenControllerAddress() external view returns (address);
/// @dev Registered address. The address registered here is the address accepted by nest system
/// @param key The key
/// @param addr Destination address. 0 means to delete the registration information
function registerAddress(string memory key, address addr) external;
/// @dev Get registered address
/// @param key The key
/// @return Destination address. 0 means empty
function checkAddress(string memory key) external view returns (address);
}
// File: contracts\interface\INestGovernance.sol
/// @dev This interface defines the governance methods
interface INestGovernance is INestMapping {
/// @dev Set governance authority
/// @param addr Destination address
/// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function setGovernance(address addr, uint flag) external;
/// @dev Get governance rights
/// @param addr Destination address
/// @return Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function getGovernance(address addr) external view returns (uint);
/// @dev Check whether the target address has governance rights for the given target
/// @param addr Destination address
/// @param flag Permission weight. The permission of the target address must be greater than this weight to pass the check
/// @return True indicates permission
function checkGovernance(address addr, uint flag) external view returns (bool);
}
// File: contracts\NestBase.sol
/// @dev Base contract of nest
contract NestBase {
// Address of nest token contract
address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C;
// Genesis block number of nest
// NEST token contract is created at block height 6913517. However, because the mining algorithm of nest1.0
// is different from that at present, a new mining algorithm is adopted from nest2.0. The new algorithm
// includes the attenuation logic according to the block. Therefore, it is necessary to trace the block
// where the nest begins to decay. According to the circulation when nest2.0 is online, the new mining
// algorithm is used to deduce and convert the nest, and the new algorithm is used to mine the nest2.0
// on-line flow, the actual block is 5120000
uint constant NEST_GENESIS_BLOCK = 5120000;
/// @dev To support open-zeppelin/upgrades
/// @param nestGovernanceAddress INestGovernance implementation contract address
function initialize(address nestGovernanceAddress) virtual public {
require(_governance == address(0), 'NEST:!initialize');
_governance = nestGovernanceAddress;
}
/// @dev INestGovernance implementation contract address
address public _governance;
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance
/// @param nestGovernanceAddress INestGovernance implementation contract address
function update(address nestGovernanceAddress) virtual public {
address governance = _governance;
require(governance == msg.sender || INestGovernance(governance).checkGovernance(msg.sender, 0), "NEST:!gov");
_governance = nestGovernanceAddress;
}
/// @dev Migrate funds from current contract to NestLedger
/// @param tokenAddress Destination token address.(0 means eth)
/// @param value Migrate amount
function migrate(address tokenAddress, uint value) external onlyGovernance {
address to = INestGovernance(_governance).getNestLedgerAddress();
if (tokenAddress == address(0)) {
INestLedger(to).addETHReward { value: value } (address(0));
} else {
TransferHelper.safeTransfer(tokenAddress, to, value);
}
}
//---------modifier------------
modifier onlyGovernance() {
require(INestGovernance(_governance).checkGovernance(msg.sender, 0), "NEST:!gov");
_;
}
modifier noContract() {
require(msg.sender == tx.origin, "NEST:!contract");
_;
}
}
// File: contracts\NestMining.sol
/// @dev This contract implemented the mining logic of nest
contract NestMining is NestBase, INestMining, INestQuery {
// /// @param nestTokenAddress Address of nest token contract
// /// @param nestGenesisBlock Genesis block number of nest
// constructor(address nestTokenAddress, uint nestGenesisBlock) {
// NEST_TOKEN_ADDRESS = nestTokenAddress;
// NEST_GENESIS_BLOCK = nestGenesisBlock;
// // Placeholder in _accounts, the index of a real account must greater than 0
// _accounts.push();
// }
/// @dev To support open-zeppelin/upgrades
/// @param nestGovernanceAddress INestGovernance implementation contract address
function initialize(address nestGovernanceAddress) override public {
super.initialize(nestGovernanceAddress);
// Placeholder in _accounts, the index of a real account must greater than 0
_accounts.push();
}
///@dev Definitions for the price sheet, include the full information. (use 256-bits, a storage unit in ethereum evm)
struct PriceSheet {
// Index of miner account in _accounts. for this way, mapping an address(which need 160-bits) to a 32-bits
// integer, support 4 billion accounts
uint32 miner;
// The block number of this price sheet packaged
uint32 height;
// The remain number of this price sheet
uint32 remainNum;
// The eth number which miner will got
uint32 ethNumBal;
// The eth number which equivalent to token's value which miner will got
uint32 tokenNumBal;
// The pledged number of nest in this sheet. (Unit: 1000nest)
uint24 nestNum1k;
// The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet
uint8 level;
// Post fee shares, if there are many sheets in one block, this value is used to divide up mining value
uint8 shares;
// Represent price as this way, may lose precision, the error less than 1/10^14
// price = priceFraction * 16 ^ priceExponent
uint56 priceFloat;
}
/// @dev Definitions for the price information
struct PriceInfo {
// Record the index of price sheet, for update price information from price sheet next time.
uint32 index;
// The block number of this price
uint32 height;
// The remain number of this price sheet
uint32 remainNum;
// Price, represent as float
// Represent price as this way, may lose precision, the error less than 1/10^14
uint56 priceFloat;
// Avg Price, represent as float
// Represent price as this way, may lose precision, the error less than 1/10^14
uint56 avgFloat;
// Square of price volatility, need divide by 2^48
uint48 sigmaSQ;
}
/// @dev Price channel
struct PriceChannel {
// Array of price sheets
PriceSheet[] sheets;
// Price information
PriceInfo price;
// Commission is charged for every post(post2), the commission should be deposited to NestLedger,
// for saving gas, according to sheets.length, every increase of 256 will deposit once, The calculation formula is:
//
// totalFee = fee * increment
//
// In consideration of takeToken, takeEth, change postFeeUnit or miner pay more fee, the formula will be invalid,
// at this point, it is need to settle immediately, the details of triggering settlement logic are as follows
//
// 1. When there is a bite transaction(currentFee is 0), the counter of no fee sheets will be increase 1
// 2. If the Commission of this time is inconsistent with that of last time, deposit immediately
// 3. When the increment of sheets.length is 256, deposit immediately
// 4. Everyone can trigger immediate settlement by manually calling the settle() method
//
// In order to realize the logic above, the following values are defined
//
// 1. PriceChannel.feeInfo
// Low 128-bits represent last fee per post
// High 128-bits represent the current counter of no fee sheets (including settled)
//
// 2. COLLECT_REWARD_MASK
// The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit,
// COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once),
// and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once)
// The information of mining fee
// Low 128-bits represent fee per post
// High 128-bits represent the current counter of no fee sheets (including settled)
uint feeInfo;
}
/// @dev Structure is used to represent a storage location. Storage variable can be used to avoid indexing from mapping many times
struct UINT {
uint value;
}
/// @dev Account information
struct Account {
// Address of account
address addr;
// Balances of mining account
// tokenAddress=>balance
mapping(address=>UINT) balances;
}
// Configuration
Config _config;
// Registered account information
Account[] _accounts;
// Mapping from address to index of account. address=>accountIndex
mapping(address=>uint) _accountMapping;
// Mapping from token address to price channel. tokenAddress=>PriceChannel
mapping(address=>PriceChannel) _channels;
// Mapping from token address to ntoken address. tokenAddress=>ntokenAddress
mapping(address=>address) _addressCache;
// Cache for genesis block number of ntoken. ntokenAddress=>genesisBlockNumber
mapping(address=>uint) _genesisBlockNumberCache;
// INestPriceFacade implementation contract address
address _nestPriceFacadeAddress;
// INTokenController implementation contract address
address _nTokenControllerAddress;
// INestLegder implementation contract address
address _nestLedgerAddress;
// Unit of post fee. 0.0001 ether
uint constant DIMI_ETHER = 0.0001 ether;
// The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit,
// COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once),
// and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once)
uint constant COLLECT_REWARD_MASK = 0xFF;
// Ethereum average block time interval, 14 seconds
uint constant ETHEREUM_BLOCK_TIMESPAN = 14;
/* ========== Governance ========== */
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance
/// @param nestGovernanceAddress INestGovernance implementation contract address
function update(address nestGovernanceAddress) override public {
super.update(nestGovernanceAddress);
(
//address nestTokenAddress
,
//address nestNodeAddress
,
//address nestLedgerAddress
_nestLedgerAddress,
//address nestMiningAddress
,
//address ntokenMiningAddress
,
//address nestPriceFacadeAddress
_nestPriceFacadeAddress,
//address nestVoteAddress
,
//address nestQueryAddress
,
//address nnIncomeAddress
,
//address nTokenControllerAddress
_nTokenControllerAddress
) = INestGovernance(nestGovernanceAddress).getBuiltinAddress();
}
/// @dev Modify configuration
/// @param config Configuration object
function setConfig(Config calldata config) override external onlyGovernance {
_config = config;
}
/// @dev Get configuration
/// @return Configuration object
function getConfig() override external view returns (Config memory) {
return _config;
}
/// @dev Clear chache of token. while ntoken recreated, this method is need to call
/// @param tokenAddress Token address
function resetNTokenCache(address tokenAddress) external onlyGovernance {
// Clear cache
address ntokenAddress = _getNTokenAddress(tokenAddress);
_genesisBlockNumberCache[ntokenAddress] = 0;
_addressCache[tokenAddress] = _addressCache[ntokenAddress] = address(0);
}
/// @dev Set the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled
/// @param tokenAddress Destination token address
/// @param ntokenAddress The ntoken address
function setNTokenAddress(address tokenAddress, address ntokenAddress) override external onlyGovernance {
_addressCache[tokenAddress] = ntokenAddress;
}
/// @dev Get the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled
/// @param tokenAddress Destination token address
/// @return The ntoken address
function getNTokenAddress(address tokenAddress) override external view returns (address) {
return _addressCache[tokenAddress];
}
/* ========== Mining ========== */
// Get ntoken address of from token address
function _getNTokenAddress(address tokenAddress) private returns (address) {
address ntokenAddress = _addressCache[tokenAddress];
if (ntokenAddress == address(0)) {
ntokenAddress = INTokenController(_nTokenControllerAddress).getNTokenAddress(tokenAddress);
if (ntokenAddress != address(0)) {
_addressCache[tokenAddress] = ntokenAddress;
}
}
return ntokenAddress;
}
// Get genesis block number of ntoken
function _getNTokenGenesisBlock(address ntokenAddress) private returns (uint) {
uint genesisBlockNumber = _genesisBlockNumberCache[ntokenAddress];
if (genesisBlockNumber == 0) {
(genesisBlockNumber,) = INToken(ntokenAddress).checkBlockInfo();
_genesisBlockNumberCache[ntokenAddress] = genesisBlockNumber;
}
return genesisBlockNumber;
}
/// @notice Post a price sheet for TOKEN
/// @dev It is for TOKEN (except USDT and NTOKENs) whose NTOKEN has a total supply below a threshold (e.g. 5,000,000 * 1e18)
/// @param tokenAddress The address of TOKEN contract
/// @param ethNum The numbers of ethers to post sheets
/// @param tokenAmountPerEth The price of TOKEN
function post(address tokenAddress, uint ethNum, uint tokenAmountPerEth) override external payable {
Config memory config = _config;
// 1. Check arguments
require(ethNum > 0 && ethNum == uint(config.postEthUnit), "NM:!ethNum");
require(tokenAmountPerEth > 0, "NM:!price");
// 2. Check price channel
// Check if the token allow post()
address ntokenAddress = _getNTokenAddress(tokenAddress);
require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress");
// Unit of nest is different, but the total supply already exceeded the number of this issue. No additional judgment will be made
// ntoken is mint when the price sheet is closed (or withdrawn), this may be the problem that the user
// intentionally does not close or withdraw, which leads to the inaccurate judgment of the total amount. ignore
require(INToken(ntokenAddress).totalSupply() < uint(config.doublePostThreshold) * 10000 ether, "NM:!post2");
// 3. Load token channel and sheets
PriceChannel storage channel = _channels[tokenAddress];
PriceSheet[] storage sheets = channel.sheets;
// 4. Freeze assets
uint accountIndex = _addressIndex(msg.sender);
// Freeze token and nest
// Because of the use of floating-point representation(fraction * 16 ^ exponent), it may bring some precision loss
// After assets are frozen according to tokenAmountPerEth * ethNum, the part with poor accuracy may be lost when
// the assets are returned, It should be frozen according to decodeFloat(fraction, exponent) * ethNum
// However, considering that the loss is less than 1 / 10 ^ 14, the loss here is ignored, and the part of
// precision loss can be transferred out as system income in the future
_freeze2(
_accounts[accountIndex].balances,
tokenAddress,
tokenAmountPerEth * ethNum,
uint(config.pledgeNest) * 1000 ether
);
// 5. Deposit fee
// The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part
uint length = sheets.length;
uint shares = _collect(config, channel, ntokenAddress, length, msg.value - ethNum * 1 ether);
require(shares > 0 && shares < 256, "NM:!fee");
// Calculate the price
// According to the current mechanism, the newly added sheet cannot take effect, so the calculated price
// is placed before the sheet is added, which can reduce unnecessary traversal
_stat(config, channel, sheets);
// 6. Create token price sheet
emit Post(tokenAddress, msg.sender, length, ethNum, tokenAmountPerEth);
_createPriceSheet(sheets, accountIndex, uint32(ethNum), uint(config.pledgeNest), shares, tokenAmountPerEth);
}
/// @notice Post two price sheets for a token and its ntoken simultaneously
/// @dev Support dual-posts for TOKEN/NTOKEN, (ETH, TOKEN) + (ETH, NTOKEN)
/// @param tokenAddress The address of TOKEN contract
/// @param ethNum The numbers of ethers to post sheets
/// @param tokenAmountPerEth The price of TOKEN
/// @param ntokenAmountPerEth The price of NTOKEN
function post2(
address tokenAddress,
uint ethNum,
uint tokenAmountPerEth,
uint ntokenAmountPerEth
) override external payable {
Config memory config = _config;
// 1. Check arguments
require(ethNum > 0 && ethNum == uint(config.postEthUnit), "NM:!ethNum");
require(tokenAmountPerEth > 0 && ntokenAmountPerEth > 0, "NM:!price");
// 2. Check price channel
address ntokenAddress = _getNTokenAddress(tokenAddress);
require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress");
// 3. Load token channel and sheets
PriceChannel storage channel = _channels[tokenAddress];
PriceSheet[] storage sheets = channel.sheets;
// 4. Freeze assets
uint pledgeNest = uint(config.pledgeNest);
uint accountIndex = _addressIndex(msg.sender);
{
mapping(address=>UINT) storage balances = _accounts[accountIndex].balances;
_freeze(balances, tokenAddress, ethNum * tokenAmountPerEth);
_freeze2(balances, ntokenAddress, ethNum * ntokenAmountPerEth, pledgeNest * 2000 ether);
}
// 5. Deposit fee
// The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part
uint length = sheets.length;
uint shares = _collect(config, channel, ntokenAddress, length, msg.value - ethNum * 2 ether);
require(shares > 0 && shares < 256, "NM:!fee");
// Calculate the price
// According to the current mechanism, the newly added sheet cannot take effect, so the calculated price
// is placed before the sheet is added, which can reduce unnecessary traversal
_stat(config, channel, sheets);
// 6. Create token price sheet
emit Post(tokenAddress, msg.sender, length, ethNum, tokenAmountPerEth);
_createPriceSheet(sheets, accountIndex, uint32(ethNum), pledgeNest, shares, tokenAmountPerEth);
// 7. Load ntoken channel and sheets
channel = _channels[ntokenAddress];
sheets = channel.sheets;
// Calculate the price
// According to the current mechanism, the newly added sheet cannot take effect, so the calculated price
// is placed before the sheet is added, which can reduce unnecessary traversal
_stat(config, channel, sheets);
// 8. Create token price sheet
emit Post(ntokenAddress, msg.sender, sheets.length, ethNum, ntokenAmountPerEth);
_createPriceSheet(sheets, accountIndex, uint32(ethNum), pledgeNest, 0, ntokenAmountPerEth);
}
/// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet
/// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal)
/// @param tokenAddress The address of token(ntoken)
/// @param index The position of the sheet in priceSheetList[token]
/// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth
/// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth
function takeToken(
address tokenAddress,
uint index,
uint takeNum,
uint newTokenAmountPerEth
) override external payable {
Config memory config = _config;
// 1. Check arguments
require(takeNum > 0 && takeNum % uint(config.postEthUnit) == 0, "NM:!takeNum");
require(newTokenAmountPerEth > 0, "NM:!price");
// 2. Load price sheet
PriceChannel storage channel = _channels[tokenAddress];
PriceSheet[] storage sheets = channel.sheets;
PriceSheet memory sheet = sheets[index];
// 3. Check state
require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum");
require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state");
// 4. Deposit fee
{
// The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part
address ntokenAddress = _getNTokenAddress(tokenAddress);
if (tokenAddress != ntokenAddress) {
_collect(config, channel, ntokenAddress, sheets.length, 0);
}
}
// 5. Calculate the number of eth, token and nest needed, and freeze them
uint needEthNum;
uint level = uint(sheet.level);
// When the level of the sheet is less than 4, both the nest and the scale of the offer are doubled
if (level < uint(config.maxBiteNestedLevel)) {
// Double scale sheet
needEthNum = takeNum << 1;
++level;
}
// When the level of the sheet reaches 4 or more, nest doubles, but the scale does not
else {
// Single scale sheet
needEthNum = takeNum;
// It is possible that the length of a single chain exceeds 255. When the length of a chain reaches 4
// or more, there is no logical dependence on the specific value of the contract, and the count will
// not increase after it is accumulated to 255
if (level < 255) ++level;
}
require(msg.value == (needEthNum + takeNum) * 1 ether, "NM:!value");
// Number of nest to be pledged
//uint needNest1k = ((takeNum << 1) / uint(config.postEthUnit)) * uint(config.pledgeNest);
// sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum
uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal));
// Freeze nest and token
uint accountIndex = _addressIndex(msg.sender);
{
mapping(address=>UINT) storage balances = _accounts[accountIndex].balances;
uint backTokenValue = decodeFloat(sheet.priceFloat) * takeNum;
if (needEthNum * newTokenAmountPerEth > backTokenValue) {
_freeze2(
balances,
tokenAddress,
needEthNum * newTokenAmountPerEth - backTokenValue,
needNest1k * 1000 ether
);
} else {
_freeze(balances, NEST_TOKEN_ADDRESS, needNest1k * 1000 ether);
_unfreeze(balances, tokenAddress, backTokenValue - needEthNum * newTokenAmountPerEth);
}
}
// 6. Update the biten sheet
sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum);
sheet.ethNumBal = uint32(uint(sheet.ethNumBal) + takeNum);
sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) - takeNum);
sheets[index] = sheet;
// 7. Calculate the price
// According to the current mechanism, the newly added sheet cannot take effect, so the calculated price
// is placed before the sheet is added, which can reduce unnecessary traversal
_stat(config, channel, sheets);
// 8. Create price sheet
emit Post(tokenAddress, msg.sender, sheets.length, needEthNum, newTokenAmountPerEth);
_createPriceSheet(sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newTokenAmountPerEth);
}
/// @notice Call the function to buy ETH from a posted price sheet
/// @dev bite ETH by TOKEN(NTOKEN), (-ethNumBal, +tokenNumBal)
/// @param tokenAddress The address of token(ntoken)
/// @param index The position of the sheet in priceSheetList[token]
/// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum
/// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth
function takeEth(
address tokenAddress,
uint index,
uint takeNum,
uint newTokenAmountPerEth
) override external payable {
Config memory config = _config;
// 1. Check arguments
require(takeNum > 0 && takeNum % uint(config.postEthUnit) == 0, "NM:!takeNum");
require(newTokenAmountPerEth > 0, "NM:!price");
// 2. Load price sheet
PriceChannel storage channel = _channels[tokenAddress];
PriceSheet[] storage sheets = channel.sheets;
PriceSheet memory sheet = sheets[index];
// 3. Check state
require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum");
require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state");
// 4. Deposit fee
{
// The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part
address ntokenAddress = _getNTokenAddress(tokenAddress);
if (tokenAddress != ntokenAddress) {
_collect(config, channel, ntokenAddress, sheets.length, 0);
}
}
// 5. Calculate the number of eth, token and nest needed, and freeze them
uint needEthNum;
uint level = uint(sheet.level);
// When the level of the sheet is less than 4, both the nest and the scale of the offer are doubled
if (level < uint(config.maxBiteNestedLevel)) {
// Double scale sheet
needEthNum = takeNum << 1;
++level;
}
// When the level of the sheet reaches 4 or more, nest doubles, but the scale does not
else {
// Single scale sheet
needEthNum = takeNum;
// It is possible that the length of a single chain exceeds 255. When the length of a chain reaches 4
// or more, there is no logical dependence on the specific value of the contract, and the count will
// not increase after it is accumulated to 255
if (level < 255) ++level;
}
require(msg.value == (needEthNum - takeNum) * 1 ether, "NM:!value");
// Number of nest to be pledged
//uint needNest1k = ((takeNum << 1) / uint(config.postEthUnit)) * uint(config.pledgeNest);
// sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum
uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal));
// Freeze nest and token
uint accountIndex = _addressIndex(msg.sender);
_freeze2(
_accounts[accountIndex].balances,
tokenAddress,
needEthNum * newTokenAmountPerEth + decodeFloat(sheet.priceFloat) * takeNum,
needNest1k * 1000 ether
);
// 6. Update the biten sheet
sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum);
sheet.ethNumBal = uint32(uint(sheet.ethNumBal) - takeNum);
sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) + takeNum);
sheets[index] = sheet;
// 7. Calculate the price
// According to the current mechanism, the newly added sheet cannot take effect, so the calculated price
// is placed before the sheet is added, which can reduce unnecessary traversal
_stat(config, channel, sheets);
// 8. Create price sheet
emit Post(tokenAddress, msg.sender, sheets.length, needEthNum, newTokenAmountPerEth);
_createPriceSheet(sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newTokenAmountPerEth);
}
// Create price sheet
function _createPriceSheet(
PriceSheet[] storage sheets,
uint accountIndex,
uint32 ethNum,
uint nestNum1k,
uint level_shares,
uint tokenAmountPerEth
) private {
sheets.push(PriceSheet(
uint32(accountIndex), // uint32 miner;
uint32(block.number), // uint32 height;
ethNum, // uint32 remainNum;
ethNum, // uint32 ethNumBal;
ethNum, // uint32 tokenNumBal;
uint24(nestNum1k), // uint32 nestNum1k;
uint8(level_shares >> 8), // uint8 level;
uint8(level_shares & 0xFF),
encodeFloat(tokenAmountPerEth)
));
}
// Nest ore drawing attenuation interval. 2400000 blocks, about one year
uint constant NEST_REDUCTION_SPAN = 2400000;
// The decay limit of nest ore drawing becomes stable after exceeding this interval. 24 million blocks, about 10 years
uint constant NEST_REDUCTION_LIMIT = 24000000; //NEST_REDUCTION_SPAN * 10;
// Attenuation gradient array, each attenuation step value occupies 16 bits. The attenuation value is an integer
uint constant NEST_REDUCTION_STEPS = 0x280035004300530068008300A300CC010001400190;
// 0
// | (uint(400 / uint(1)) << (16 * 0))
// | (uint(400 * 8 / uint(10)) << (16 * 1))
// | (uint(400 * 8 * 8 / uint(10 * 10)) << (16 * 2))
// | (uint(400 * 8 * 8 * 8 / uint(10 * 10 * 10)) << (16 * 3))
// | (uint(400 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10)) << (16 * 4))
// | (uint(400 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10)) << (16 * 5))
// | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10)) << (16 * 6))
// | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 7))
// | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 8))
// | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 9))
// //| (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 10));
// | (uint(40) << (16 * 10));
// Calculation of attenuation gradient
function _redution(uint delta) private pure returns (uint) {
if (delta < NEST_REDUCTION_LIMIT) {
return (NEST_REDUCTION_STEPS >> ((delta / NEST_REDUCTION_SPAN) << 4)) & 0xFFFF;
}
return (NEST_REDUCTION_STEPS >> 160) & 0xFFFF;
}
/// @notice Close a price sheet of (ETH, USDx) | (ETH, NEST) | (ETH, TOKEN) | (ETH, NTOKEN)
/// @dev Here we allow an empty price sheet (still in VERIFICATION-PERIOD) to be closed
/// @param tokenAddress The address of TOKEN contract
/// @param index The index of the price sheet w.r.t. `token`
function close(address tokenAddress, uint index) override external {
Config memory config = _config;
PriceChannel storage channel = _channels[tokenAddress];
PriceSheet[] storage sheets = channel.sheets;
// Load the price channel
address ntokenAddress = _getNTokenAddress(tokenAddress);
// Call _close() method to close price sheet
(uint accountIndex, Tunple memory total) = _close(config, sheets, index, ntokenAddress);
if (accountIndex > 0) {
// Return eth
if (uint(total.ethNum) > 0) {
payable(indexAddress(accountIndex)).transfer(uint(total.ethNum) * 1 ether);
}
// Unfreeze assets
_unfreeze3(
_accounts[accountIndex].balances,
tokenAddress,
total.tokenValue,
ntokenAddress,
uint(total.ntokenValue),
uint(total.nestValue)
);
}
// Calculate the price
_stat(config, channel, sheets);
}
/// @notice Close a batch of price sheets passed VERIFICATION-PHASE
/// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed
/// @param tokenAddress The address of TOKEN contract
/// @param indices A list of indices of sheets w.r.t. `token`
function closeList(address tokenAddress, uint[] memory indices) override external {
// Call _closeList() method to close price sheets
(
uint accountIndex,
Tunple memory total,
address ntokenAddress
) = _closeList(_config, _channels[tokenAddress], tokenAddress, indices);
// Return eth
payable(indexAddress(accountIndex)).transfer(uint(total.ethNum) * 1 ether);
// Unfreeze assets
_unfreeze3(
_accounts[accountIndex].balances,
tokenAddress,
uint(total.tokenValue),
ntokenAddress,
uint(total.ntokenValue),
uint(total.nestValue)
);
}
/// @notice Close two batch of price sheets passed VERIFICATION-PHASE
/// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed
/// @param tokenAddress The address of TOKEN1 contract
/// @param tokenIndices A list of indices of sheets w.r.t. `token`
/// @param ntokenIndices A list of indices of sheets w.r.t. `ntoken`
function closeList2(
address tokenAddress,
uint[] memory tokenIndices,
uint[] memory ntokenIndices
) override external {
Config memory config = _config;
mapping(address=>PriceChannel) storage channels = _channels;
// Call _closeList() method to close price sheets
(
uint accountIndex1,
Tunple memory total1,
address ntokenAddress
) = _closeList(config, channels[tokenAddress], tokenAddress, tokenIndices);
(
uint accountIndex2,
Tunple memory total2,
//address ntokenAddress2
) = _closeList(config, channels[ntokenAddress], ntokenAddress, ntokenIndices);
require(accountIndex1 == accountIndex2, "NM:!miner");
//require(ntokenAddress1 == tokenAddress2, "NM:!tokenAddress");
require(uint(total2.ntokenValue) == 0, "NM!ntokenValue");
// Return eth
payable(indexAddress(accountIndex1)).transfer((uint(total1.ethNum) + uint(total2.ethNum)) * 1 ether);
// Unfreeze assets
_unfreeze3(
_accounts[accountIndex1].balances,
tokenAddress,
uint(total1.tokenValue),
ntokenAddress,
uint(total1.ntokenValue) + uint(total2.tokenValue)/* + uint(total2.ntokenValue) */,
uint(total1.nestValue) + uint(total2.nestValue)
);
}
// Calculation number of blocks which mined
function _calcMinedBlocks(
PriceSheet[] storage sheets,
uint index,
PriceSheet memory sheet
) private view returns (uint minedBlocks, uint totalShares) {
uint length = sheets.length;
uint height = uint(sheet.height);
totalShares = uint(sheet.shares);
// Backward looking for sheets in the same block
for (uint i = index; ++i < length && uint(sheets[i].height) == height;) {
// Multiple sheets in the same block is a small probability event at present, so it can be ignored
// to read more than once, if there are always multiple sheets in the same block, it means that the
// sheets are very intensive, and the gas consumed here does not have a great impact
totalShares += uint(sheets[i].shares);
}
//i = index;
// Find sheets in the same block forward
uint prev = height;
while (index > 0 && uint(prev = sheets[--index].height) == height) {
// Multiple sheets in the same block is a small probability event at present, so it can be ignored
// to read more than once, if there are always multiple sheets in the same block, it means that the
// sheets are very intensive, and the gas consumed here does not have a great impact
totalShares += uint(sheets[index].shares);
}
if (index > 0 || height > prev) {
minedBlocks = height - prev;
} else {
minedBlocks = 10;
}
}
// This structure is for the _close() method to return multiple values
struct Tunple {
uint tokenValue;
uint64 ethNum;
uint96 nestValue;
uint96 ntokenValue;
}
// Close price sheet
function _close(
Config memory config,
PriceSheet[] storage sheets,
uint index,
address ntokenAddress
) private returns (uint accountIndex, Tunple memory value) {
PriceSheet memory sheet = sheets[index];
uint height = uint(sheet.height);
// Check the status of the price sheet to see if it has reached the effective block interval or has been finished
if ((accountIndex = uint(sheet.miner)) > 0 && (height + uint(config.priceEffectSpan) < block.number)) {
// TMP: tmp is a polysemous name, here means sheet.shares
uint tmp = uint(sheet.shares);
// Mining logic
// The price sheet which shares is zero dosen't mining
if (tmp > 0) {
// Currently, mined represents the number of blocks has mined
(uint mined, uint totalShares) = _calcMinedBlocks(sheets, index, sheet);
// nest mining
if (ntokenAddress == NEST_TOKEN_ADDRESS) {
// Since then, mined represents the amount of mining
// mined = (
// mined
// * uint(sheet.shares)
// * _redution(height - NEST_GENESIS_BLOCK)
// * 1 ether
// * uint(config.minerNestReward)
// / 10000
// / totalShares
// );
// The original expression is shown above. In order to save gas,
// the part that can be calculated in advance is calculated first
mined = (
mined
* tmp
* _redution(height - NEST_GENESIS_BLOCK)
* uint(config.minerNestReward)
* 0.0001 ether
/ totalShares
);
}
// ntoken mining
else {
// The limit blocks can be mined
if (mined > uint(config.ntokenMinedBlockLimit)) {
mined = uint(config.ntokenMinedBlockLimit);
}
// Since then, mined represents the amount of mining
mined = (
mined
* tmp
* _redution(height - _getNTokenGenesisBlock(ntokenAddress))
* 0.01 ether
/ totalShares
);
// Put this logic into widhdran() method to reduce gas consumption
// ntoken bidders
address bidder = INToken(ntokenAddress).checkBidder();
// Legacy ntoken, need separate
if (bidder != address(this)) {
// Considering that multiple sheets in the same block are small probability events,
// we can send token to bidders in each closing operation
// 5% for bidder
// TMP: tmp is a polysemous name, here means mint ntoken amount for miner
tmp = mined * uint(config.minerNTokenReward) / 10000;
_unfreeze(
_accounts[_addressIndex(bidder)].balances,
ntokenAddress,
mined - tmp
);
// Miner take according proportion which set
mined = tmp;
}
}
value.ntokenValue = uint96(mined);
}
value.nestValue = uint96(uint(sheet.nestNum1k) * 1000 ether);
value.ethNum = uint64(sheet.ethNumBal);
value.tokenValue = decodeFloat(sheet.priceFloat) * uint(sheet.tokenNumBal);
// Set sheet.miner to 0, express the sheet is closed
sheet.miner = uint32(0);
sheet.ethNumBal = uint32(0);
sheet.tokenNumBal = uint32(0);
sheets[index] = sheet;
}
}
// Batch close sheets
function _closeList(
Config memory config,
PriceChannel storage channel,
address tokenAddress,
uint[] memory indices
) private returns (uint accountIndex, Tunple memory total, address ntokenAddress) {
ntokenAddress = _getNTokenAddress(tokenAddress);
PriceSheet[] storage sheets = channel.sheets;
accountIndex = 0;
// 1. Traverse sheets
for (uint i = indices.length; i > 0;) {
// Because too many variables need to be returned, too many variables will be defined, so the structure of tunple is defined
(uint minerIndex, Tunple memory value) = _close(config, sheets, indices[--i], ntokenAddress);
// Batch closing quotation can only close sheet of the same user
if (accountIndex == 0) {
// accountIndex == 0 means the first sheet, and the number of this sheet is taken
accountIndex = minerIndex;
} else {
// accountIndex != 0 means that it is a follow-up sheet, and the miner number must be consistent with the previous record
require(accountIndex == minerIndex, "NM:!miner");
}
total.ntokenValue += value.ntokenValue;
total.nestValue += value.nestValue;
total.ethNum += value.ethNum;
total.tokenValue += value.tokenValue;
}
_stat(config, channel, sheets);
}
// Calculate price, average price and volatility
function _stat(Config memory config, PriceChannel storage channel, PriceSheet[] storage sheets) private {
// Load token price information
PriceInfo memory p0 = channel.price;
// Length of sheets
uint length = sheets.length;
// The index of the sheet to be processed in the sheet array
uint index = uint(p0.index);
// The latest block number for which the price has been calculated
uint prev = uint(p0.height);
// It's not necessary to load the price information in p0
// Eth count variable used to calculate price
uint totalEthNum = 0;
// Token count variable for price calculation
uint totalTokenValue = 0;
// Block number of current sheet
uint height = 0;
// Traverse the sheets to find the effective price
uint effectBlock = block.number - uint(config.priceEffectSpan);
PriceSheet memory sheet;
for (; ; ++index) {
// Gas attack analysis, each post transaction, calculated according to post, needs to write
// at least one sheet and freeze two kinds of assets, which needs to consume at least 30000 gas,
// In addition to the basic cost of the transaction, at least 50000 gas is required.
// In addition, there are other reading and calculation operations. The gas consumed by each
// transaction is impossible less than 70000 gas, The attacker can accumulate up to 20 blocks
// of sheets to be generated. To ensure that the calculation can be completed in one block,
// it is necessary to ensure that the consumption of each price does not exceed 70000 / 20 = 3500 gas,
// According to the current logic, each calculation of a price needs to read a storage unit (800)
// and calculate the consumption, which can not reach the dangerous value of 3500, so the gas attack
// is not considered
// Traverse the sheets that has reached the effective interval from the current position
bool flag = index >= length || (height = uint((sheet = sheets[index]).height)) >= effectBlock;
// Not the same block (or flag is false), calculate the price and update it
if (flag || prev != height) {
// totalEthNum > 0 Can calculate the price
if (totalEthNum > 0) {
// Calculate average price and Volatility
// Calculation method of volatility of follow-up price
uint tmp = decodeFloat(p0.priceFloat);
// New price
uint price = totalTokenValue / totalEthNum;
// Update price
p0.remainNum = uint32(totalEthNum);
p0.priceFloat = encodeFloat(price);
// Clear cumulative values
totalEthNum = 0;
totalTokenValue = 0;
if (tmp > 0) {
// Calculate average price
// avgPrice[i + 1] = avgPrice[i] * 90% + price[i] * 10%
p0.avgFloat = encodeFloat((decodeFloat(p0.avgFloat) * 9 + price) / 10);
// When the accuracy of the token is very high or the value of the token relative to
// eth is very low, the price may be very large, and there may be overflow problem,
// it is not considered for the moment
tmp = (price << 48) / tmp;
if (tmp > 0x1000000000000) {
tmp = tmp - 0x1000000000000;
} else {
tmp = 0x1000000000000 - tmp;
}
// earn = price[i] / price[i - 1] - 1;
// seconds = time[i] - time[i - 1];
// sigmaSQ[i + 1] = sigmaSQ[i] * 90% + (earn ^ 2 / seconds) * 10%
tmp = (
uint(p0.sigmaSQ) * 9 +
// It is inevitable that prev greatter than p0.height
((tmp * tmp / ETHEREUM_BLOCK_TIMESPAN / (prev - uint(p0.height))) >> 48)
) / 10;
// The current implementation assumes that the volatility cannot exceed 1, and
// corresponding to this, when the calculated value exceeds 1, expressed as 0xFFFFFFFFFFFF
if (tmp > 0xFFFFFFFFFFFF) {
tmp = 0xFFFFFFFFFFFF;
}
p0.sigmaSQ = uint48(tmp);
}
// The calculation methods of average price and volatility are different for first price
else {
// The average price is equal to the price
//p0.avgTokenAmount = uint64(price);
p0.avgFloat = p0.priceFloat;
// The volatility is 0
p0.sigmaSQ = uint48(0);
}
// Update price block number
p0.height = uint32(prev);
}
// Move to new block number
prev = height;
}
if (flag) {
break;
}
// Cumulative price information
totalEthNum += uint(sheet.remainNum);
totalTokenValue += decodeFloat(sheet.priceFloat) * uint(sheet.remainNum);
}
// Update price infomation
if (index > uint(p0.index)) {
p0.index = uint32(index);
channel.price = p0;
}
}
/// @dev The function updates the statistics of price sheets
/// It calculates from priceInfo to the newest that is effective.
function stat(address tokenAddress) override external {
PriceChannel storage channel = _channels[tokenAddress];
_stat(_config, channel, channel.sheets);
}
// Collect and deposit the commission into NestLedger
function _collect(
Config memory config,
PriceChannel storage channel,
address ntokenAddress,
uint length,
uint currentFee
) private returns (uint) {
// Commission is charged for every post(post2), the commission should be deposited to NestLedger,
// for saving gas, according to sheets.length, every increase of 256 will deposit once, The calculation formula is:
//
// totalFee = fee * increment
//
// In consideration of takeToken, takeEth, change postFeeUnit or miner pay more fee, the formula will be invalid,
// at this point, it is need to settle immediately, the details of triggering settlement logic are as follows
//
// 1. When there is a bite transaction(currentFee is 0), the counter of no fee sheets will be increase 1
// 2. If the Commission of this time is inconsistent with that of last time, deposit immediately
// 3. When the increment of sheets.length is 256, deposit immediately
// 4. Everyone can trigger immediate settlement by manually calling the settle() method
//
// In order to realize the logic above, the following values are defined
//
// 1. PriceChannel.feeInfo
// Low 128-bits represent last fee per post
// High 128-bits represent the current counter of no fee sheets (including settled)
//
// 2. COLLECT_REWARD_MASK
// The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit,
// COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once),
// and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once)
uint feeUnit = uint(config.postFeeUnit) * DIMI_ETHER;
require(currentFee % feeUnit == 0, "NM:!fee");
uint feeInfo = channel.feeInfo;
uint oldFee = feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
// length == 255 means is time to save reward
// currentFee != oldFee means the fee is changed, need to settle
if (length & COLLECT_REWARD_MASK == COLLECT_REWARD_MASK || (currentFee != oldFee && currentFee > 0)) {
// Save reward
INestLedger(_nestLedgerAddress).carveETHReward {
value: currentFee + oldFee * ((length & COLLECT_REWARD_MASK) - (feeInfo >> 128))
} (ntokenAddress);
// Update fee information
channel.feeInfo = currentFee | (((length + 1) & COLLECT_REWARD_MASK) << 128);
}
// currentFee is 0, increase no fee counter
else if (currentFee == 0) {
// channel.feeInfo = feeInfo + (1 << 128);
channel.feeInfo = feeInfo + 0x100000000000000000000000000000000;
}
// Calculate share count
return currentFee / feeUnit;
}
/// @dev Settlement Commission
/// @param tokenAddress The token address
function settle(address tokenAddress) override external {
address ntokenAddress = _getNTokenAddress(tokenAddress);
// ntoken is no reward
if (tokenAddress != ntokenAddress) {
PriceChannel storage channel = _channels[tokenAddress];
uint length = channel.sheets.length & COLLECT_REWARD_MASK;
uint feeInfo = channel.feeInfo;
// Save reward
INestLedger(_nestLedgerAddress).carveETHReward {
value: (feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) * (length - (feeInfo >> 128))
} (ntokenAddress);
// Manual settlement does not need to update Commission variables
channel.feeInfo = (feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | (length << 128);
}
}
// Convert PriceSheet to PriceSheetView
function _toPriceSheetView(PriceSheet memory sheet, uint index) private view returns (PriceSheetView memory) {
return PriceSheetView(
// Index number
uint32(index),
// Miner address
indexAddress(sheet.miner),
// The block number of this price sheet packaged
sheet.height,
// The remain number of this price sheet
sheet.remainNum,
// The eth number which miner will got
sheet.ethNumBal,
// The eth number which equivalent to token's value which miner will got
sheet.tokenNumBal,
// The pledged number of nest in this sheet. (Unit: 1000nest)
sheet.nestNum1k,
// The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet
sheet.level,
// Post fee shares
sheet.shares,
// Price
uint152(decodeFloat(sheet.priceFloat))
);
}
/// @dev List sheets by page
/// @param tokenAddress Destination token address
/// @param offset Skip previous (offset) records
/// @param count Return (count) records
/// @param order Order. 0 reverse order, non-0 positive order
/// @return List of price sheets
function list(
address tokenAddress,
uint offset,
uint count,
uint order
) override external view noContract returns (PriceSheetView[] memory) {
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
PriceSheetView[] memory result = new PriceSheetView[](count);
uint length = sheets.length;
uint i = 0;
// Reverse order
if (order == 0) {
uint index = length - offset;
uint end = index > count ? index - count : 0;
while (index > end) {
--index;
result[i++] = _toPriceSheetView(sheets[index], index);
}
}
// Positive order
else {
uint index = offset;
uint end = index + count;
if (end > length) {
end = length;
}
while (index < end) {
result[i++] = _toPriceSheetView(sheets[index], index);
++index;
}
}
return result;
}
/// @dev Estimated mining amount
/// @param tokenAddress Destination token address
/// @return Estimated mining amount
function estimate(address tokenAddress) override external view returns (uint) {
address ntokenAddress = INTokenController(_nTokenControllerAddress).getNTokenAddress(tokenAddress);
if (tokenAddress != ntokenAddress) {
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
uint index = sheets.length;
while (index > 0) {
PriceSheet memory sheet = sheets[--index];
if (uint(sheet.shares) > 0) {
// Standard mining amount
uint standard = (block.number - uint(sheet.height)) * 1 ether;
// Genesis block number of ntoken
uint genesisBlock = NEST_GENESIS_BLOCK;
// Not nest, the calculation methods of standard mining amount and genesis block number are different
if (ntokenAddress != NEST_TOKEN_ADDRESS) {
// The standard mining amount of ntoken is 1/100 of nest
standard /= 100;
// Genesis block number of ntoken is obtained separately
(genesisBlock,) = INToken(ntokenAddress).checkBlockInfo();
}
return standard * _redution(block.number - genesisBlock);
}
}
}
return 0;
}
/// @dev Query the quantity of the target quotation
/// @param tokenAddress Token address. The token can't mine. Please make sure you don't use the token address when calling
/// @param index The index of the sheet
/// @return minedBlocks Mined block period from previous block
/// @return totalShares Total shares of sheets in the block
function getMinedBlocks(
address tokenAddress,
uint index
) override external view returns (uint minedBlocks, uint totalShares) {
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
PriceSheet memory sheet = sheets[index];
// The bite sheet or ntoken sheet dosen't mining
if (uint(sheet.shares) == 0) {
return (0, 0);
}
return _calcMinedBlocks(sheets, index, sheet);
}
/* ========== Accounts ========== */
/// @dev Withdraw assets
/// @param tokenAddress Destination token address
/// @param value The value to withdraw
function withdraw(address tokenAddress, uint value) override external {
// The user's locked nest and the mining pool's nest are stored together. When the nest is mined over,
// the problem of taking the locked nest as the ore drawing will appear
// As it will take a long time for nest to finish mining, this problem will not be considered for the time being
UINT storage balance = _accounts[_accountMapping[msg.sender]].balances[tokenAddress];
//uint balanceValue = balance.value;
//require(balanceValue >= value, "NM:!balance");
balance.value -= value;
// ntoken mining
uint ntokenBalance = INToken(tokenAddress).balanceOf(address(this));
if (ntokenBalance < value) {
// mining
INToken(tokenAddress).increaseTotal(value - ntokenBalance);
}
TransferHelper.safeTransfer(tokenAddress, msg.sender, value);
}
/// @dev View the number of assets specified by the user
/// @param tokenAddress Destination token address
/// @param addr Destination address
/// @return Number of assets
function balanceOf(address tokenAddress, address addr) override external view returns (uint) {
return _accounts[_accountMapping[addr]].balances[tokenAddress].value;
}
/// @dev Gets the index number of the specified address. If it does not exist, register
/// @param addr Destination address
/// @return The index number of the specified address
function _addressIndex(address addr) private returns (uint) {
uint index = _accountMapping[addr];
if (index == 0) {
// If it exceeds the maximum number that 32 bits can store, you can't continue to register a new account.
// If you need to support a new account, you need to update the contract
require((_accountMapping[addr] = index = _accounts.length) < 0x100000000, "NM:!accounts");
_accounts.push().addr = addr;
}
return index;
}
/// @dev Gets the address corresponding to the given index number
/// @param index The index number of the specified address
/// @return The address corresponding to the given index number
function indexAddress(uint index) override public view returns (address) {
return _accounts[index].addr;
}
/// @dev Gets the registration index number of the specified address
/// @param addr Destination address
/// @return 0 means nonexistent, non-0 means index number
function getAccountIndex(address addr) override external view returns (uint) {
return _accountMapping[addr];
}
/// @dev Get the length of registered account array
/// @return The length of registered account array
function getAccountCount() override external view returns (uint) {
return _accounts.length;
}
/* ========== Asset management ========== */
/// @dev Freeze token
/// @param balances Balances ledger
/// @param tokenAddress Destination token address
/// @param value token amount
function _freeze(mapping(address=>UINT) storage balances, address tokenAddress, uint value) private {
UINT storage balance = balances[tokenAddress];
uint balanceValue = balance.value;
if (balanceValue < value) {
balance.value = 0;
TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), value - balanceValue);
} else {
balance.value = balanceValue - value;
}
}
/// @dev Unfreeze token
/// @param balances Balances ledgerBalances ledger
/// @param tokenAddress Destination token address
/// @param value token amount
function _unfreeze(mapping(address=>UINT) storage balances, address tokenAddress, uint value) private {
UINT storage balance = balances[tokenAddress];
balance.value += value;
}
/// @dev freeze token and nest
/// @param balances Balances ledger
/// @param tokenAddress Destination token address
/// @param tokenValue token amount
/// @param nestValue nest amount
function _freeze2(
mapping(address=>UINT) storage balances,
address tokenAddress,
uint tokenValue,
uint nestValue
) private {
UINT storage balance;
uint balanceValue;
// If tokenAddress is NEST_TOKEN_ADDRESS, add it to nestValue
if (NEST_TOKEN_ADDRESS == tokenAddress) {
nestValue += tokenValue;
}
// tokenAddress is not NEST_TOKEN_ADDRESS, unfreeze it
else {
balance = balances[tokenAddress];
balanceValue = balance.value;
if (balanceValue < tokenValue) {
balance.value = 0;
TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), tokenValue - balanceValue);
} else {
balance.value = balanceValue - tokenValue;
}
}
// Unfreeze nest
balance = balances[NEST_TOKEN_ADDRESS];
balanceValue = balance.value;
if (balanceValue < nestValue) {
balance.value = 0;
TransferHelper.safeTransferFrom(NEST_TOKEN_ADDRESS, msg.sender, address(this), nestValue - balanceValue);
} else {
balance.value = balanceValue - nestValue;
}
}
/// @dev Unfreeze token, ntoken and nest
/// @param balances Balances ledger
/// @param tokenAddress Destination token address
/// @param tokenValue token amount
/// @param ntokenAddress Destination ntoken address
/// @param ntokenValue ntoken amount
/// @param nestValue nest amount
function _unfreeze3(
mapping(address=>UINT) storage balances,
address tokenAddress,
uint tokenValue,
address ntokenAddress,
uint ntokenValue,
uint nestValue
) private {
UINT storage balance;
// If tokenAddress is ntokenAddress, add it to ntokenValue
if (ntokenAddress == tokenAddress) {
ntokenValue += tokenValue;
}
// tokenAddress is not ntokenAddress, unfreeze it
else {
balance = balances[tokenAddress];
balance.value += tokenValue;
}
// If ntokenAddress is NEST_TOKEN_ADDRESS, add it to nestValue
if (NEST_TOKEN_ADDRESS == ntokenAddress) {
nestValue += ntokenValue;
}
// ntokenAddress is NEST_TOKEN_ADDRESS, unfreeze it
else {
balance = balances[ntokenAddress];
balance.value += ntokenValue;
}
// Unfreeze nest
balance = balances[NEST_TOKEN_ADDRESS];
balance.value += nestValue;
}
/* ========== INestQuery ========== */
// Check msg.sender
function _check() private view {
require(msg.sender == _nestPriceFacadeAddress || msg.sender == tx.origin);
}
/// @dev Get the latest trigger price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function triggeredPrice(address tokenAddress) override public view returns (uint blockNumber, uint price) {
_check();
PriceInfo memory priceInfo = _channels[tokenAddress].price;
if (uint(priceInfo.remainNum) > 0) {
return (uint(priceInfo.height) + uint(_config.priceEffectSpan), decodeFloat(priceInfo.priceFloat));
}
return (0, 0);
}
/// @dev Get the full information of latest trigger price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo(address tokenAddress) override public view returns (
uint blockNumber,
uint price,
uint avgPrice,
uint sigmaSQ
) {
_check();
PriceInfo memory priceInfo = _channels[tokenAddress].price;
if (uint(priceInfo.remainNum) > 0) {
return (
uint(priceInfo.height) + uint(_config.priceEffectSpan),
decodeFloat(priceInfo.priceFloat),
decodeFloat(priceInfo.avgFloat),
(uint(priceInfo.sigmaSQ) * 1 ether) >> 48
);
}
return (0, 0, 0, 0);
}
/// @dev Find the price at block number
/// @param tokenAddress Destination token address
/// @param height Destination block number
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function findPrice(
address tokenAddress,
uint height
) override external view returns (uint blockNumber, uint price) {
_check();
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
uint priceEffectSpan = uint(_config.priceEffectSpan);
uint length = sheets.length;
uint index = 0;
uint sheetHeight;
height -= priceEffectSpan;
{
// If there is no sheet in this channel, length is 0, length - 1 will overflow,
uint right = length - 1;
uint left = 0;
// Find the index use Binary Search
while (left < right) {
index = (left + right) >> 1;
sheetHeight = uint(sheets[index].height);
if (height > sheetHeight) {
left = ++index;
} else if (height < sheetHeight) {
// When index = 0, this statement will have an underflow exception, which usually
// indicates that the effective block height passed during the call is lower than
// the block height of the first quotation
right = --index;
} else {
break;
}
}
}
// Calculate price
uint totalEthNum = 0;
uint totalTokenValue = 0;
uint h = 0;
uint remainNum;
PriceSheet memory sheet;
// Find sheets forward
for (uint i = index; i < length;) {
sheet = sheets[i++];
sheetHeight = uint(sheet.height);
if (height < sheetHeight) {
break;
}
remainNum = uint(sheet.remainNum);
if (remainNum > 0) {
if (h == 0) {
h = sheetHeight;
} else if (h != sheetHeight) {
break;
}
totalEthNum += remainNum;
totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum;
}
}
// Find sheets backward
while (index > 0) {
sheet = sheets[--index];
remainNum = uint(sheet.remainNum);
if (remainNum > 0) {
sheetHeight = uint(sheet.height);
if (h == 0) {
h = sheetHeight;
} else if (h != sheetHeight) {
break;
}
totalEthNum += remainNum;
totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum;
}
}
if (totalEthNum > 0) {
return (h + priceEffectSpan, totalTokenValue / totalEthNum);
}
return (0, 0);
}
/// @dev Get the latest effective price
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function latestPrice(address tokenAddress) override public view returns (uint blockNumber, uint price) {
_check();
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
PriceSheet memory sheet;
uint priceEffectSpan = uint(_config.priceEffectSpan);
uint h = block.number - priceEffectSpan;
uint index = sheets.length;
uint totalEthNum = 0;
uint totalTokenValue = 0;
uint height = 0;
for (; ; ) {
bool flag = index == 0;
if (flag || height != uint((sheet = sheets[--index]).height)) {
if (totalEthNum > 0 && height <= h) {
return (height + priceEffectSpan, totalTokenValue / totalEthNum);
}
if (flag) {
break;
}
totalEthNum = 0;
totalTokenValue = 0;
height = uint(sheet.height);
}
uint remainNum = uint(sheet.remainNum);
totalEthNum += remainNum;
totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum;
}
return (0, 0);
}
/// @dev Get the last (num) effective price
/// @param tokenAddress Destination token address
/// @param count The number of prices that want to return
/// @return An array which length is num * 2, each two element expresses one price like blockNumber|price
function lastPriceList(address tokenAddress, uint count) override public view returns (uint[] memory) {
_check();
PriceSheet[] storage sheets = _channels[tokenAddress].sheets;
PriceSheet memory sheet;
uint[] memory array = new uint[](count <<= 1);
uint priceEffectSpan = uint(_config.priceEffectSpan);
uint h = block.number - priceEffectSpan;
uint index = sheets.length;
uint totalEthNum = 0;
uint totalTokenValue = 0;
uint height = 0;
for (uint i = 0; i < count;) {
bool flag = index == 0;
if (flag || height != uint((sheet = sheets[--index]).height)) {
if (totalEthNum > 0 && height <= h) {
array[i++] = height + priceEffectSpan;
array[i++] = totalTokenValue / totalEthNum;
}
if (flag) {
break;
}
totalEthNum = 0;
totalTokenValue = 0;
height = uint(sheet.height);
}
uint remainNum = uint(sheet.remainNum);
totalEthNum += remainNum;
totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum;
}
return array;
}
/// @dev Returns the results of latestPrice() and triggeredPriceInfo()
/// @param tokenAddress Destination token address
/// @return latestPriceBlockNumber The block number of latest price
/// @return latestPriceValue The token latest price. (1eth equivalent to (price) token)
/// @return triggeredPriceBlockNumber The block number of triggered price
/// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// @return triggeredAvgPrice Average price
/// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function latestPriceAndTriggeredPriceInfo(address tokenAddress) override external view
returns (
uint latestPriceBlockNumber,
uint latestPriceValue,
uint triggeredPriceBlockNumber,
uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
) {
(latestPriceBlockNumber, latestPriceValue) = latestPrice(tokenAddress);
(
triggeredPriceBlockNumber,
triggeredPriceValue,
triggeredAvgPrice,
triggeredSigmaSQ
) = triggeredPriceInfo(tokenAddress);
}
/// @dev Returns lastPriceList and triggered price info
/// @param tokenAddress Destination token address
/// @param count The number of prices that want to return
/// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price
/// @return triggeredPriceBlockNumber The block number of triggered price
/// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// @return triggeredAvgPrice Average price
/// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function lastPriceListAndTriggeredPriceInfo(address tokenAddress, uint count) override external view
returns (
uint[] memory prices,
uint triggeredPriceBlockNumber,
uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
) {
prices = lastPriceList(tokenAddress, count);
(
triggeredPriceBlockNumber,
triggeredPriceValue,
triggeredAvgPrice,
triggeredSigmaSQ
) = triggeredPriceInfo(tokenAddress);
}
/// @dev Get the latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function triggeredPrice2(address tokenAddress) override external view returns (
uint blockNumber,
uint price,
uint ntokenBlockNumber,
uint ntokenPrice
) {
(blockNumber, price) = triggeredPrice(tokenAddress);
(ntokenBlockNumber, ntokenPrice) = triggeredPrice(_addressCache[tokenAddress]);
}
/// @dev Get the full information of latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
/// @return ntokenAvgPrice Average price of ntoken
/// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo2(address tokenAddress) override external view returns (
uint blockNumber,
uint price,
uint avgPrice,
uint sigmaSQ,
uint ntokenBlockNumber,
uint ntokenPrice,
uint ntokenAvgPrice,
uint ntokenSigmaSQ
) {
(blockNumber, price, avgPrice, sigmaSQ) = triggeredPriceInfo(tokenAddress);
(
ntokenBlockNumber,
ntokenPrice,
ntokenAvgPrice,
ntokenSigmaSQ
) = triggeredPriceInfo(_addressCache[tokenAddress]);
}
/// @dev Get the latest effective price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function latestPrice2(address tokenAddress) override external view returns (
uint blockNumber,
uint price,
uint ntokenBlockNumber,
uint ntokenPrice
) {
(blockNumber, price) = latestPrice(tokenAddress);
(ntokenBlockNumber, ntokenPrice) = latestPrice(_addressCache[tokenAddress]);
}
/* ========== Tools and methods ========== */
/// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent
/// @param value Destination uint value
/// @return float format
function encodeFloat(uint value) private pure returns (uint56) {
uint exponent = 0;
while (value > 0x3FFFFFFFFFFFF) {
value >>= 4;
++exponent;
}
return uint56((value << 6) | exponent);
}
/// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint
/// @param floatValue fraction value
/// @return decode format
function decodeFloat(uint56 floatValue) private pure returns (uint) {
return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2);
}
} | Freeze token balances Balances ledger tokenAddress Destination token address value token amount | function _freeze(mapping(address=>UINT) storage balances, address tokenAddress, uint value) private {
UINT storage balance = balances[tokenAddress];
uint balanceValue = balance.value;
if (balanceValue < value) {
balance.value = 0;
TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), value - balanceValue);
balance.value = balanceValue - value;
}
}
| 52,786 |
pragma solidity ^0.4.17;
import "ds-test/test.sol";
import "./OMT.sol";
import "./ERC223ReceivingContract.sol";
contract TokenReceivingEchoDemo {
OMT omt;
function TokenReceivingEchoDemo(address _token)
{
omt = OMT(_token);
}
function tokenFallback(address _from, uint256 _value, bytes _data) public
{
// check that the msg.sender _token is equal to token address
require(msg.sender == address(omt));
omt.transfer(_from, _value);
}
function anotherTokenFallback(address _from, uint256 _value, bytes _data) public
{
// check that the msg.sender _token is equal to token address
require(msg.sender == address(omt));
omt.transfer(_from, _value);
}
function tokenFallback(address _from, uint256 _value) public
{
// check that the msg.sender _token is equal to token address
require(msg.sender == address(omt));
omt.transfer(_from, _value);
}
}
contract Nothing {
// do not have receiveToken API
}
contract ERC223ReceivingContractTest is DSTest, TokenController {
TokenReceivingEchoDemo echo;
OMT omt;
Nothing nothing;
function proxyPayment(address _owner) payable returns(bool){
return true;
}
function onTransfer(address _from, address _to, uint _amount) returns(bool){
return true;
}
function onApprove(address _owner, address _spender, uint _amount)
returns(bool)
{
return true;
}
function setUp() {
omt = new OMT();
echo = new TokenReceivingEchoDemo(address(omt));
nothing = new Nothing();
}
function testFail_basic_sanity() {
omt.mint(this, 10000);
assertEq(omt.balanceOf(this) , 10000);
// fail
omt.transfer(address(nothing), 100, "0x");
assertEq(omt.balanceOf(this) , 10000);
}
function test_token_fall_back_with_data() {
omt.mint(this, 10000);
omt.transfer(address(echo), 5000, "");
assertEq(omt.balanceOf(this) , 10000);
// https://github.com/dapphub/dapp/issues/65
// need manual testing
omt.transfer(address(echo), 5000, "0x", "anotherTokenFallback(address,uint256,bytes)");
assertEq(omt.balanceOf(this) , 10000);
omt.transfer(address(nothing), 100);
}
function test_token_fall_back_direct() {
omt.mint(this, 10000);
assertTrue(omt.balanceOf(this) == 10000);
omt.transfer(address(echo), 5000);
assertTrue(omt.balanceOf(this) == 10000);
}
}
| check that the msg.sender _token is equal to token address | function tokenFallback(address _from, uint256 _value, bytes _data) public
{
require(msg.sender == address(omt));
omt.transfer(_from, _value);
}
| 6,422,843 |
/**
*Submitted for verification at Etherscan.io on 2021-09-12
*/
/**
*Submitted for verification at Etherscan.io on 2021-01-27
*/
pragma solidity ^0.5.0;
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas
* @param _interfaceId The interface identifier, as specified in ERC-165
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
/**
* @dev ERC-1155 interface for accepting safe transfers.
*/
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external returns (bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external returns (bytes4);
/**
* @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types.
* @param interfaceID The ERC-165 interface ID that is queried for support.s
* @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface.
* This function MUST NOT consume more than 5,000 gas.
* @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported.
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath#mul: OVERFLOW");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath#div: DIVISION_BY_ZERO");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath#sub: UNDERFLOW");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath#add: OVERFLOW");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath#mod: DIVISION_BY_ZERO");
return a % b;
}
}
/**
* Copyright 2018 ZeroEx Intl.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash
= 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly {
codehash := extcodehash(account)
}
return (codehash != 0x0 && codehash != accountHash);
}
}
/**
* @dev Implementation of Multi-Token Standard contract
*/
contract ERC1155 is IERC165 {
using SafeMath for uint256;
using Address for address;
/***********************************|
| Variables and Events |
|__________________________________*/
// onReceive function signatures
bytes4 internal constant ERC1155_RECEIVED_VALUE = 0xf23a6e61;
bytes4 internal constant ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81;
// Objects balances
mapping(address => mapping(uint256 => uint256)) internal balances;
// Objects balances pending order
mapping(address => mapping(uint256 => uint256)) internal balancesPending;
// Order receive payment address
mapping(address => mapping(uint256 => address)) internal receivePaymentAddress;
// Objects price
mapping(address => mapping(uint256 => uint256)) internal tokenPrice;
// Objects is agent
mapping(address => mapping(uint256 => bool)) internal isAgent;
// Objects agent commission
mapping(address => mapping(uint256 => uint256)) internal agentCommission;
// Objects agent address
mapping(address => mapping(uint256 => address)) internal agentAddress;
// Operator Functions
mapping(address => mapping(address => bool)) internal operators;
// Events
event TransferSingle(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _amount
);
event TransferBatch(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _amounts
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Public Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data,
bool _buyrequest
// uint256 _tokenSupply
) internal {
require(
(msg.sender == _from) || isApprovedForAll(_from, msg.sender),
"ERC1155#safeTransferFrom: INVALID_OPERATOR"
);
require(
_to != address(0),
"ERC1155#safeTransferFrom: INVALID_RECIPIENT"
);
// require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations
_safeTransferFrom(_from, _to, _id, _amount, _buyrequest);
_callonERC1155Received(_from, _to, _id, _amount, _data);
}
/***********************************|
| Internal Transfer Functions |
|__________________________________*/
/**
* @notice Transfers amount amount of an _id from the _from address to the _to address specified
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
*/
function _safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bool _buyrequest
) internal {
if(_buyrequest){
// Update balances
balancesPending[_from][_id] = balancesPending[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
}
else{
// Update balances
balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount
balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount
}
// Emit event
emit TransferSingle(msg.sender, _from, _to, _id, _amount);
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...)
*/
function _callonERC1155Received(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data
) internal {
// Check if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(
msg.sender,
_from,
_id,
_amount,
_data
);
require(
retval == ERC1155_RECEIVED_VALUE,
"ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"
);
}
}
/**
* @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...)
*/
function _callonERC1155BatchReceived(
address _from,
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) internal {
// Pass data if recipient is contract
if (_to.isContract()) {
bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(
msg.sender,
_from,
_ids,
_amounts,
_data
);
require(
retval == ERC1155_BATCH_RECEIVED_VALUE,
"ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"
);
}
}
/***********************************|
| Operator Functions |
|__________________________________*/
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external {
// Update operator status
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool isOperator)
{
return operators[_owner][_operator];
}
/***********************************|
| Balance Functions |
|__________________________________*/
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
public
view
returns (uint256)
{
return balances[_owner][_id];
}
function getTokenPrice(address _owner, uint256 _id)
public
view
returns (uint256)
{
return tokenPrice[_owner][_id];
}
function getAgentFees(address _owner, uint256 _id)
public
view
returns (uint256)
{
return agentCommission[_owner][_id];
}
function getAgentAddress(address _owner, uint256 _id)
public
view
returns (address)
{
return agentAddress[_owner][_id];
}
function balanceOfOrder(address _owner, uint256 _id)
public
view
returns (uint256)
{
return balancesPending[_owner][_id];
}
function receivePaymentAddressForOrder(address _owner, uint256 _id)
public
view
returns (address)
{
return receivePaymentAddress[_owner][_id];
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)"));
*/
bytes4 private constant INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;
/**
* INTERFACE_SIGNATURE_ERC1155 =
* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
* bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
* bytes4(keccak256("balanceOf(address,uint256)")) ^
* bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
* bytes4(keccak256("setApprovalForAll(address,bool)")) ^
* bytes4(keccak256("isApprovedForAll(address,address)"));
*/
bytes4 private constant INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID` and
*/
function supportsInterface(bytes4 _interfaceID)
external
view
returns (bool)
{
if (
_interfaceID == INTERFACE_SIGNATURE_ERC165 ||
_interfaceID == INTERFACE_SIGNATURE_ERC1155
) {
return true;
}
return false;
}
}
/**
* @dev Multi-Fungible Tokens with minting and burning methods. These methods assume
* a parent contract to be executed as they are `internal` functions
*/
contract ERC1155MintBurn is ERC1155 {
/****************************************|
| Minting Functions |
|_______________________________________*/
/**
* @notice Mint _amount of tokens of a given id
* @param _to The address to mint tokens to
* @param _id Token id to mint
* @param _amount The amount to be minted
* @param _data Data to pass if receiver is contract
*/
function _mint(
address _to,
uint256 _id,
uint256 _amount,
bytes memory _data
) internal {
// Add _amount
balances[_to][_id] = balances[_to][_id].add(_amount);
// Emit event
emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount);
// Calling onReceive method if recipient is contract
_callonERC1155Received(address(0x0), _to, _id, _amount, _data);
}
/****************************************|
| Burning Functions |
|_______________________________________*/
/**
* @notice Burn _amount of tokens of a given token id
* @param _from The address to burn tokens from
* @param _id Token id to burn
* @param _amount The amount to be burned
*/
function _burn(
address _from,
uint256 _id,
uint256 _amount
) internal {
//Substract _amount
balances[_from][_id] = balances[_from][_id].sub(_amount);
// Emit event
emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount);
}
}
/**
* @notice Contract that handles metadata related methods.
* @dev Methods assume a deterministic generation of URI based on token IDs.
* Methods also assume that URI uses hex representation of token IDs.
*/
contract ERC1155Metadata {
// URI's default URI prefix
string internal baseMetadataURI;
event URI(string _uri, uint256 indexed _id);
/***********************************|
| Metadata Public Function s |
|__________________________________*/
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given token.
* @dev URIs are defined in RFC 3986.
* URIs are assumed to be deterministically generated based on token ID
* Token IDs are assumed to be represented in their hex format in URIs
* @return URI string
*/
function uri(uint256 _id) public view returns (string memory) {
return
string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json"));
}
/***********************************|
| Metadata Internal Functions |
|__________________________________*/
/**
* @notice Will emit default URI log event for corresponding token _id
* @param _tokenIDs Array of IDs of tokens to log default URI
*/
function _logURIs(uint256[] memory _tokenIDs) internal {
string memory baseURL = baseMetadataURI;
string memory tokenURI;
for (uint256 i = 0; i < _tokenIDs.length; i++) {
tokenURI = string(
abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")
);
emit URI(tokenURI, _tokenIDs[i]);
}
}
/**
* @notice Will emit a specific URI log event for corresponding token
* @param _tokenIDs IDs of the token corresponding to the _uris logged
* @param _URIs The URIs of the specified _tokenIDs
*/
function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs)
internal
{
require(
_tokenIDs.length == _URIs.length,
"ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH"
);
for (uint256 i = 0; i < _tokenIDs.length; i++) {
emit URI(_URIs[i], _tokenIDs[i]);
}
}
/**
* @notice Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal {
baseMetadataURI = _newBaseMetadataURI;
}
/***********************************|
| Utility Internal Functions |
|__________________________________*/
/**
* @notice Convert uint256 to string
* @param _i Unsigned integer to convert to string
*/
function _uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 ii = _i;
uint256 len;
// Get number of bytes
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
// Get each individual ASCII
while (ii != 0) {
bstr[k--] = bytes1(uint8(48 + (ii % 10)));
ii /= 10;
}
// Convert to string
return string(bstr);
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d,
string memory _e
) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(
_ba.length + _bb.length + _bc.length + _bd.length + _be.length
);
bytes memory babcde = bytes(abcde);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (uint256 i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d
) internal pure returns (string memory) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(
string memory _a,
string memory _b,
string memory _c
) internal pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b)
internal
pure
returns (string memory)
{
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping(address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor() internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(
isMinter(_msgSender()),
"MinterRole: caller does not have the Minter role"
);
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor() internal {
_addWhitelistAdmin(_msgSender());
}
modifier onlyWhitelistAdmin() {
require(
isWhitelistAdmin(_msgSender()),
"WhitelistAdminRole: caller does not have the WhitelistAdmin role"
);
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address,
* has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
contract ERC1155Tradable is
ERC1155,
ERC1155MintBurn,
ERC1155Metadata,
Ownable
// MinterRole,
// WhitelistAdminRole
{
event TransferSingle(address indexed _from, address indexed _to, uint256 indexed _tokenId);
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
uint256 private _currentListID = 0;
mapping(uint256 => address) public creators;
mapping(string => uint256) public queryId;
mapping(uint256 => uint256) public tokenSupply;
mapping(uint256 => uint256) public tokenMaxSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
constructor(
string memory _name,
string memory _symbol
) public {
name = _name;
symbol = _symbol;
}
function uri(uint256 _id) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(baseMetadataURI, Strings.uint2str(_id));
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @dev Returns the max quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function maxSupply(uint256 _id) public view returns (uint256) {
return tokenMaxSupply[_id];
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(string memory _newBaseMetadataURI)
public
onlyOwner
{
_setBaseMetadataURI(_newBaseMetadataURI);
}
function MintToken(
string calldata _queryId,
uint256 _supply,
bytes calldata _data
) external {
require(_supply > 0, "Supply must be more than 0");
//Check if item is not minted
require(queryId[_queryId] == 0, "Query Id is not available");
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
queryId[_queryId] = _id;
if (_supply != 0) _mint(msg.sender, _id, _supply, _data);
tokenSupply[_id] = _supply;
tokenMaxSupply[_id] = _supply;
}
function CreateOrder(
string calldata _queryId,
uint256 _tokenId,
uint256 _amount,
uint256 _price,
address _paymenrReceiveAddress,
bool _isagent,
uint256 _agentcommission,
uint256 _supply
) external {
require(_supply > 0, "Supply must be more than 0");
require(_price > 0, "Price must be more than 0");
uint256 tokenId = 0;
//Check if item is not minted
if(_tokenId == 0){
require(queryId[_queryId] == 0, "Query Id is not available");
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
queryId[_queryId] = _id;
if (_supply != 0) _mint(msg.sender, _id, _supply, "0x00");
tokenSupply[_id] = _supply;
tokenMaxSupply[_id] = _supply;
tokenId = _id;
}
else{
tokenId = _tokenId;
require(_exists(tokenId) == true, "Token does not exist");
}
//Check if order is curcurrently running
if(balancesPending[msg.sender][tokenId] > 0){
CancelOrder(tokenId);
}
//Check is item listed by owner
require(balancesPending[msg.sender][tokenId] == 0, "Item already listed by owner");
require(balances[msg.sender][tokenId] >= _amount, "Insufficient item balance.");
//Set item listed quantity
balances[msg.sender][tokenId] = balances[msg.sender][tokenId].sub(_amount);
balancesPending[msg.sender][tokenId] = balancesPending[msg.sender][tokenId].add(_amount);
//Set agentcommission
isAgent[msg.sender][tokenId] = _isagent;
if(_isagent){
agentCommission[msg.sender][tokenId] = _agentcommission;
agentAddress[msg.sender][tokenId] = msg.sender;
}
//Set item price
tokenPrice[msg.sender][tokenId] = _price;
//Set receive payment address
receivePaymentAddress[msg.sender][tokenId] = _paymenrReceiveAddress;
}
function CancelOrder(uint256 _tokenId) public {
//Check is item listed by owner
require(balancesPending[msg.sender][_tokenId] > 0, "No item to remove from order.");
//Set owner delisted item
uint256 _amount = balancesPending[msg.sender][_tokenId];
balances[msg.sender][_tokenId] = balances[msg.sender][_tokenId].add(_amount);
balancesPending[msg.sender][_tokenId] = balancesPending[msg.sender][_tokenId].sub(_amount);
//Set item price
tokenPrice[msg.sender][_tokenId] = 0;
//Remove agent
isAgent[msg.sender][_tokenId] = false;
agentCommission[msg.sender][_tokenId] = 0;
agentAddress[msg.sender][_tokenId] = address(0);
receivePaymentAddress[msg.sender][_tokenId] = address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextListID() private view returns (uint256) {
return _currentListID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementListId() private {
_currentListID++;
}
function GetTokenId(string memory _queryId) view public returns (uint256) {
return queryId[_queryId];
}
/**
* @dev Burns some amount of tokens from an address
* @param _from Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
*/
function burn(
address _from,
uint256 _id,
uint256 _quantity
) public {
uint256 tokenId = _id;
require(
balances[_from][tokenId] >= _quantity,
"Exceed the amount of balance"
);
_burn(_from, tokenId, _quantity);
tokenMaxSupply[tokenId] = tokenMaxSupply[tokenId].sub(_quantity);
tokenSupply[tokenId] = tokenSupply[tokenId].sub(_quantity);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool isOperator)
{
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 _id) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() private {
_currentTokenID++;
}
}
contract Sonce is ERC1155Tradable {
event Purchase(address indexed previousOwner, address indexed newOwner, uint price, uint nftID, string uri);
address payable _contractOwner;
address payable _platformAcount;
uint256 public _platformCommission;
constructor()
public
ERC1155Tradable("Sonce", "SONCE")
{
_setBaseMetadataURI("https://meta-sonce.rivex.finance/api/meta/");
_contractOwner = msg.sender;
_platformAcount = msg.sender;
_platformCommission = 2;
}
function contractURI() public view returns (string memory) {
return baseMetadataURI;
}
function setContractURI(string memory _uri) public {
_setBaseMetadataURI(_uri);
}
function buy(address _ownerAddress, uint256 _tokenId, uint _amount) external payable {
uint256 quantity = balancesPending[_ownerAddress][_tokenId];
uint256 price = tokenPrice[_ownerAddress][_tokenId];
address payable paymentReceiver = address(uint160(receivePaymentAddress[_ownerAddress][_tokenId]));
operators[_ownerAddress][msg.sender] = true;
require(balancesPending[_ownerAddress][_tokenId] > 0, "Item not listed currently");
require(quantity >= _amount, "Error, the amount is more than the quantity available");
require(msg.value >= price * _amount, "Error, the amount is lower");
address previousOwner = _ownerAddress;
address newOwner = msg.sender;
require(previousOwner != newOwner, "Can not buy what you sell");
bool isagent = isAgent[_ownerAddress][_tokenId];
uint256 agentcommission = agentCommission[_ownerAddress][_tokenId];
address payable agentaddress = address(uint160(agentAddress[_ownerAddress][_tokenId]));
_trade(_tokenId, _amount, _ownerAddress, price, isagent, agentcommission, agentaddress ,paymentReceiver);
emit Purchase(previousOwner, newOwner, price * _amount, _tokenId, contractURI());
}
function _trade(uint _tokenId, uint _amount, address _owner, uint256 _price, bool _isagent, uint256 _agentCommission, address payable _agentAddress ,address payable paymentReceiver) internal {
address payable _buyer = msg.sender;
safeTransferFrom(_owner, _buyer, _tokenId, _amount, "", true);
uint _sellerValue = 0;
uint _clientValue = 0;
uint _platformValue = (_price * _platformCommission / 100) * _amount;
if(_isagent){
_clientValue = (_price * _agentCommission / 100) * _amount;
_sellerValue = (_price * _amount) - (_clientValue + _platformValue);
}
else{
_sellerValue = (_price * _amount) - _platformValue;
}
paymentReceiver.transfer(_sellerValue);
if(_clientValue > 0){
_agentAddress.transfer(_clientValue);
}
_platformAcount.transfer(_platformValue);
if (msg.value > _price * _amount) {
_buyer.transfer(msg.value - _price * _amount);
}
}
function trasnferToken(uint256 _tokenId, uint256 _amount, address _to) public {
require(balances[msg.sender][_tokenId] > _amount, "Amount is more than available balance");
safeTransferFrom(msg.sender, _to, _tokenId, _amount, "", false);
}
function setPlatformAccount(address payable _platformaccountaddress) public onlyOwner{
_platformAcount = _platformaccountaddress;
}
function setPlatformCommission(uint platformCommission) public onlyOwner{
_platformCommission = platformCommission;
}
} | Transfers amount amount of an _id from the _from address to the _to address specified _from Source address _to Target address _id ID of the token type _amount Transfered amount/ Update balances Update balances | function _safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bool _buyrequest
) internal {
if(_buyrequest){
}
else{
}
}
| 10,054,437 |
./full_match/1/0x5478a4e605D7AA798dC70eCD0A1C3299aaeaFDD7/sources/contracts/utils/AnalyticMath.sol | The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] This function supports the rational approximation of "(a / b) ^ (c / d)" via "e ^ (log(a / b) c / d)". The value of "log(a / b)" is represented with an integer slightly smaller than "log(a / b) 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (a maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute the result with maximum accuracy and without exceeding 256 bits in any of the intermediate computations./ | function findPosition(uint256 x) internal view returns (uint8) { unchecked {
uint8 lo = MIN_PRECISION;
uint8 hi = MAX_PRECISION;
while (lo + 1 < hi) {
uint8 mid = (lo + hi) / 2;
if (maxExpArray[mid] >= x)
lo = mid;
else
hi = mid;
}
if (maxExpArray[hi] >= x)
return hi;
if (maxExpArray[lo] >= x)
return lo;
revert("findPosition: x > max");
}}
| 4,962,038 |
./full_match/1/0x88d0D1a1472307d1853809C3aA455B1B76c9bCfe/sources/contracts/Wrapper.sol | Set the SwapERC20 contract _swapERC20Contract address Address of the new swap contract/ | function setSwapERC20Contract(address _swapERC20Contract) external onlyOwner {
require(_swapERC20Contract != address(0), "INVALID_SWAP_ERC20_CONTRACT");
wethContract.approve(address(swapERC20Contract), 0);
swapERC20Contract = ISwapERC20(_swapERC20Contract);
wethContract.approve(_swapERC20Contract, MAX_UINT);
}
| 17,176,973 |
./full_match/80001/0xC3111E853d888D7f919361f162e82a93CA486044/sources/contracts/BurnToMintFightMe.sol | emit BurnedToMint( _tokenId, msg.sender ); 1. Check if the burner is the owner of the token 2. Burn the token 3. Call a mint function on another contract to mint a new token to the burnerfighterContract.mintViaLootbox(_tokenId, msg.sender); | function burnToMint(uint256 _tokenId) external {
_burn(_tokenId, true);
fighterContract.testExternalCall();
}
| 5,662,235 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: ICurveFi
interface ICurveFi {
function calc_withdraw_one_coin(uint256, int128) external view returns(uint256);
function remove_liquidity_one_coin(uint256, int128, uint256) external;
}
// Part: ISwap
interface ISwap {
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external;
function getAmountsOut(uint amountIn, address[] memory path) external view returns (uint[] memory amounts);
}
// Part: IVoterProxy
interface IVoterProxy {
function lock() external;
}
// Part: IyveCRV
interface IyveCRV {
function claimable(address) external view returns(uint256);
function supplyIndex(address) external view returns(uint256);
function balanceOf(address) external view returns(uint256);
function index() external view returns(uint256);
function claim() external;
function depositAll() external;
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Part: iearn-finance/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.3.5";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external virtual view returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(
msg.sender == vault.management() || msg.sender == governance(),
"!authorized"
);
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public virtual view returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public virtual view returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public virtual view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(
HealthCheck(healthCheck).check(
profit,
loss,
debtPayment,
debtOutstanding,
totalDebt
),
"!healthcheck"
);
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// sanity check
require(_amountNeeded == amountFreed.add(_loss), "!withdraw");
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal virtual view returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// File: Strategy.sol
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant yvBoost = 0x9d409a0A012CFbA9B15F6D4B36Ac57A46966Ab9a;
address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant crv3 = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;
address public constant crv3Pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F;
address public constant ethCrvPair = 0x58Dc5a51fE44589BEb22E8CE67720B5BC5378009; // Sushi
address public constant ethYvBoostPair = 0x9461173740D27311b176476FA27e94C681b1Ea6b; // Sushi
address public constant ethUsdcPair = 0x397FF1542f962076d0BFE58eA045FfA2d347ACa0;
address public proxy = 0xA420A63BbEFfbda3B147d0585F1852C358e2C152;
// Configurable preference for locking CRV in vault vs market-buying yvBOOST.
// Default: Buy only when yvBOOST price becomes > 3% price of CRV
uint256 public vaultBuffer = 30;
uint256 internal constant DENOMINATOR = 1000;
event UpdatedBuffer(uint256 newBuffer);
event BuyOrMint(bool shouldMint, uint256 projBuyAmount, uint256 projMintAmount);
constructor(address _vault) public BaseStrategy(_vault) {
healthCheck = address(0xDDCea799fF1699e98EDF118e0629A974Df7DF012);
IERC20(crv).safeApprove(address(want), type(uint256).max);
IERC20(usdc).safeApprove(sushiswap, type(uint256).max);
}
function name() external view override returns (string memory) {
return "StrategyYearnVECRV";
}
function estimatedTotalAssets() public view override returns (uint256) {
return want.balanceOf(address(this));
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
if (_debtOutstanding > 0) {
(_debtPayment, _loss) = liquidatePosition(_debtOutstanding);
}
// Figure out how much want we have
uint256 claimable = getClaimable3Crv();
claimable = claimable > 0 ? claimable : IERC20(crv3).balanceOf(address(this)); // We do this to make testing harvest easier
uint256 debt = vault.strategies(address(this)).totalDebt;
if (claimable > 0 || estimatedTotalAssets() > debt) {
IyveCRV(address(want)).claim();
withdrawFrom3CrvToUSDC(); // Convert 3crv to USDC
uint256 usdcBalance = IERC20(usdc).balanceOf(address(this));
if(usdcBalance > 0){
// Aquire yveCRV either via:
// 1) buy CRV and mint or
// 2) market-buy yvBOOST and unwrap
if(shouldMint(usdcBalance)){
swap(usdc, crv, usdcBalance);
deposityveCRV(); // Mints yveCRV
}
else{
// Avoid rugging pre-existing strategist rewards (which are denominated in same token we're swapping fore)
uint256 strategistRewards = vault.balanceOf(address(this));
swap(usdc, yvBoost, usdcBalance);
uint256 swapGain = vault.balanceOf(address(this)).sub(strategistRewards);
if(swapGain > 0){
// Here we burn our new vault shares. But because strategy is withdrawing to itself,
// the want balance will not increase. Overall strategy debt is reduced, while want balance stays the same.
vault.withdraw(swapGain);
// The withdraw action above reduces the strategy's debt, so let's update this value we set earlier.
debt = vault.strategies(address(this)).totalDebt;
}
}
}
uint256 assets = estimatedTotalAssets();
if(assets >= debt){
_profit = assets.sub(debt);
}
else{
_loss = debt.sub(assets);
}
}
}
// Here we lock curve in the voter contract. Lock doesn't require approval.
function adjustPosition(uint256 _debtOutstanding) internal override {
IVoterProxy(proxy).lock();
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 totalAssets = want.balanceOf(address(this));
if (_amountNeeded > totalAssets) {
_liquidatedAmount = totalAssets;
_loss = _amountNeeded.sub(totalAssets);
} else {
_liquidatedAmount = _amountNeeded;
}
}
// NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary
function prepareMigration(address _newStrategy) internal override {
uint256 balance3crv = IERC20(crv3).balanceOf(address(this));
uint256 balanceYveCrv = IERC20(address(want)).balanceOf(address(this));
if(balance3crv > 0){
IERC20(crv3).safeTransfer(_newStrategy, balance3crv);
}
if(balanceYveCrv > 0){
IERC20(address(want)).safeTransfer(_newStrategy, balanceYveCrv);
}
IERC20(crv).safeApprove(address(want), 0);
IERC20(usdc).safeApprove(sushiswap, 0);
}
// Here we determine if better to market-buy yvBOOST or mint it via backscratcher
function shouldMint(uint256 _amountIn) internal returns (bool) {
// Using reserve ratios of swap pairs will allow us to compare whether it's more efficient to:
// 1) Buy yvBOOST (unwrapped for yveCRV)
// 2) Buy CRV (and use to mint yveCRV 1:1)
address[] memory path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = yvBoost;
uint256[] memory amounts = ISwap(sushiswap).getAmountsOut(_amountIn, path);
uint256 projectedYvBoost = amounts[2];
// Convert yvBOOST to yveCRV
uint256 projectedYveCrv = projectedYvBoost.mul(vault.pricePerShare()).div(1e18); // save some gas by hardcoding 1e18
path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = crv;
amounts = ISwap(sushiswap).getAmountsOut(_amountIn, path);
uint256 projectedCrv = amounts[2];
// Here we favor minting by a % value defined by "vaultBuffer"
bool shouldMint = projectedCrv.mul(DENOMINATOR.add(vaultBuffer)).div(DENOMINATOR) > projectedYveCrv;
emit BuyOrMint(shouldMint, projectedYveCrv, projectedCrv);
return shouldMint;
}
function withdrawFrom3CrvToUSDC() internal {
uint256 amount = IERC20(crv3).balanceOf(address(this));
if(amount > 0){
ICurveFi(crv3Pool).remove_liquidity_one_coin(amount, 1, 0);
}
}
function quoteWithdrawFrom3Crv(uint256 _amount) internal view returns(uint256) {
return ICurveFi(crv3Pool).calc_withdraw_one_coin(_amount, 1);
}
function getClaimable3Crv() public view returns (uint256) {
IyveCRV YveCrv = IyveCRV(address(want));
uint256 claimable = YveCrv.claimable(address(this));
uint256 claimableToAdd = (YveCrv.index().sub(YveCrv.supplyIndex(address(this))))
.mul(YveCrv.balanceOf(address(this)))
.div(1e18);
return claimable.mul(1e18).add(claimableToAdd);
}
// Common API used to update Yearn's StrategyProxy if needed in case of upgrades.
function setProxy(address _proxy) external onlyGovernance {
proxy = _proxy;
}
function swap(address token_in, address token_out, uint256 amount_in) internal {
// Don't swap if amount in is 0
if(amount_in == 0){
return;
}
bool is_weth = token_in == weth || token_out == weth;
address[] memory path = new address[](is_weth ? 2 : 3);
path[0] = token_in;
if (is_weth) {
path[1] = token_out;
} else {
path[1] = weth;
path[2] = token_out;
}
ISwap(sushiswap).swapExactTokensForTokens(
amount_in,
0,
path,
address(this),
now
);
}
function deposityveCRV() internal {
IyveCRV(address(want)).depositAll();
}
function setBuffer(uint256 _newBuffer) external onlyGovernance {
require(_newBuffer < DENOMINATOR);
vaultBuffer = _newBuffer;
emit UpdatedBuffer(_newBuffer);
}
function restoreApprovals() external onlyGovernance {
IERC20(crv).safeApprove(address(want), 0); // CRV must go to zero first before increase
IERC20(usdc).safeApprove(sushiswap, 0); // USDC must go to zero first before increase
IERC20(crv).safeApprove(address(want), type(uint256).max);
IERC20(usdc).safeApprove(sushiswap, type(uint256).max);
}
// internal helpers
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
} | Here we determine if better to market-buy yvBOOST or mint it via backscratcher Using reserve ratios of swap pairs will allow us to compare whether it's more efficient to: 1) Buy yvBOOST (unwrapped for yveCRV) 2) Buy CRV (and use to mint yveCRV 1:1) Convert yvBOOST to yveCRV Here we favor minting by a % value defined by "vaultBuffer" | function shouldMint(uint256 _amountIn) internal returns (bool) {
address[] memory path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = yvBoost;
uint256[] memory amounts = ISwap(sushiswap).getAmountsOut(_amountIn, path);
uint256 projectedYvBoost = amounts[2];
path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = crv;
amounts = ISwap(sushiswap).getAmountsOut(_amountIn, path);
uint256 projectedCrv = amounts[2];
bool shouldMint = projectedCrv.mul(DENOMINATOR.add(vaultBuffer)).div(DENOMINATOR) > projectedYveCrv;
emit BuyOrMint(shouldMint, projectedYveCrv, projectedCrv);
return shouldMint;
}
| 14,747,200 |
/**
*Submitted for verification at Etherscan.io on 2021-11-01
*/
// Sources flattened with hardhat v2.6.7 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
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 ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/security/[email protected]
pragma solidity ^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/token/ERC721/[email protected]
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);
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
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);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @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;
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
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 ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
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);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
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 CountersUpgradeable {
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/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
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);
}
}
// File contracts/interfaces/IAccessControl.sol
pragma solidity ^0.8.7;
/// @title IAccessControl
/// @author Forked from OpenZeppelin
/// @notice Interface for `AccessControl` contracts
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
// File contracts/external/AccessControlUpgradeable.sol
pragma solidity ^0.8.7;
/**
* @dev This contract is fully forked from OpenZeppelin `AccessControlUpgradeable`.
* The only difference is the removal of the ERC165 implementation as it's not
* needed in Angle.
*
* 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, IAccessControl {
function __AccessControl_init() internal initializer {
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, msg.sender);
_;
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external 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) external override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external override {
require(account == msg.sender, "71");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) internal {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, msg.sender);
}
}
function _revokeRole(bytes32 role, address account) internal {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, msg.sender);
}
}
uint256[49] private __gap;
}
// File contracts/interfaces/IFeeManager.sol
pragma solidity ^0.8.7;
/// @title IFeeManagerFunctions
/// @author Angle Core Team
/// @dev Interface for the `FeeManager` contract
interface IFeeManagerFunctions is IAccessControl {
// ================================= Keepers ===================================
function updateUsersSLP() external;
function updateHA() external;
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
address _perpetualManager
) external;
function setFees(
uint256[] memory xArray,
uint64[] memory yArray,
uint8 typeChange
) external;
function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external;
}
/// @title IFeeManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev We need these getters as they are used in other contracts of the protocol
interface IFeeManager is IFeeManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
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 contracts/interfaces/IERC721.sol
pragma solidity ^0.8.7;
interface IERC721 is IERC165 {
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;
}
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File contracts/interfaces/IOracle.sol
pragma solidity ^0.8.7;
/// @title IOracle
/// @author Angle Core Team
/// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink
/// from just UniswapV3 or from just Chainlink
interface IOracle {
function read() external view returns (uint256);
function readAll() external view returns (uint256 lowerRate, uint256 upperRate);
function readLower() external view returns (uint256);
function readUpper() external view returns (uint256);
function readQuote(uint256 baseAmount) external view returns (uint256);
function readQuoteLower(uint256 baseAmount) external view returns (uint256);
function inBase() external view returns (uint256);
}
// File contracts/interfaces/IPerpetualManager.sol
pragma solidity ^0.8.7;
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev Front interface, meaning only user-facing functions
interface IPerpetualManagerFront is IERC721Metadata {
function openPerpetual(
address owner,
uint256 amountBrought,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin
) external returns (uint256 perpetualID);
function closePerpetual(
uint256 perpetualID,
address to,
uint256 minCashOutAmount
) external;
function addToPerpetual(uint256 perpetualID, uint256 amount) external;
function removeFromPerpetual(
uint256 perpetualID,
uint256 amount,
address to
) external;
function liquidatePerpetuals(uint256[] memory perpetualIDs) external;
function forceClosePerpetuals(uint256[] memory perpetualIDs) external;
// ========================= External View Functions =============================
function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256);
function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool);
}
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev This interface does not contain user facing functions, it just has functions that are
/// interacted with in other parts of the protocol
interface IPerpetualManagerFunctions is IAccessControl {
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
IFeeManager feeManager,
IOracle oracle_
) external;
function setFeeManager(IFeeManager feeManager_) external;
function setHAFees(
uint64[] memory _xHAFees,
uint64[] memory _yHAFees,
uint8 deposit
) external;
function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external;
function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external;
function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external;
function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external;
function setLockTime(uint64 _lockTime) external;
function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external;
function pause() external;
function unpause() external;
// ==================================== Keepers ================================
function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external;
// =============================== StableMaster ================================
function setOracle(IOracle _oracle) external;
}
/// @title IPerpetualManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables
interface IPerpetualManager is IPerpetualManagerFunctions {
function poolManager() external view returns (address);
function oracle() external view returns (address);
function targetHAHedge() external view returns (uint64);
function totalHedgeAmount() external view returns (uint256);
}
// File contracts/interfaces/IPoolManager.sol
pragma solidity ^0.8.7;
// Struct for the parameters associated to a strategy interacting with a collateral `PoolManager`
// contract
struct StrategyParams {
// Timestamp of last report made by this strategy
// It is also used to check if a strategy has been initialized
uint256 lastReport;
// Total amount the strategy is expected to have
uint256 totalStrategyDebt;
// The share of the total assets in the `PoolManager` contract that the `strategy` can access to.
uint256 debtRatio;
}
/// @title IPoolManagerFunctions
/// @author Angle Core Team
/// @notice Interface for the collateral poolManager contracts handling each one type of collateral for
/// a given stablecoin
/// @dev Only the functions used in other contracts of the protocol are left here
interface IPoolManagerFunctions {
// ============================ Constructor ====================================
function deployCollateral(
address[] memory governorList,
address guardian,
IPerpetualManager _perpetualManager,
IFeeManager feeManager,
IOracle oracle
) external;
// ============================ Yield Farming ==================================
function creditAvailable() external view returns (uint256);
function debtOutstanding() external view returns (uint256);
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external;
// ============================ Governance =====================================
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address _guardian, address guardian) external;
function revokeGuardian(address guardian) external;
function setFeeManager(IFeeManager _feeManager) external;
// ============================= Getters =======================================
function getBalance() external view returns (uint256);
function getTotalAsset() external view returns (uint256);
}
/// @title IPoolManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev Used in other contracts of the protocol
interface IPoolManager is IPoolManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
function token() external view returns (address);
function feeManager() external view returns (address);
function totalDebt() external view returns (uint256);
function strategies(address _strategy) external view returns (StrategyParams memory);
}
// File contracts/interfaces/IStakingRewards.sol
pragma solidity ^0.8.7;
/// @title IStakingRewardsFunctions
/// @author Angle Core Team
/// @notice Interface for the staking rewards contract that interact with the `RewardsDistributor` contract
interface IStakingRewardsFunctions {
function notifyRewardAmount(uint256 reward) external;
function recoverERC20(
address tokenAddress,
address to,
uint256 tokenAmount
) external;
function setNewRewardsDistribution(address newRewardsDistribution) external;
}
/// @title IStakingRewards
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables
interface IStakingRewards is IStakingRewardsFunctions {
function rewardToken() external view returns (IERC20);
}
// File contracts/interfaces/IRewardsDistributor.sol
pragma solidity ^0.8.7;
/// @title IRewardsDistributor
/// @author Angle Core Team, inspired from Fei protocol
/// (https://github.com/fei-protocol/fei-protocol-core/blob/master/contracts/staking/IRewardsDistributor.sol)
/// @notice Rewards Distributor interface
interface IRewardsDistributor {
// ========================= Public Parameter Getter ===========================
function rewardToken() external view returns (IERC20);
// ======================== External User Available Function ===================
function drip(IStakingRewards stakingContract) external returns (uint256);
// ========================= Governor Functions ================================
function governorWithdrawRewardToken(uint256 amount, address governance) external;
function governorRecover(
address tokenAddress,
address to,
uint256 amount,
IStakingRewards stakingContract
) external;
function setUpdateFrequency(uint256 _frequency, IStakingRewards stakingContract) external;
function setIncentiveAmount(uint256 _incentiveAmount, IStakingRewards stakingContract) external;
function setAmountToDistribute(uint256 _amountToDistribute, IStakingRewards stakingContract) external;
function setDuration(uint256 _duration, IStakingRewards stakingContract) external;
function setStakingContract(
address _stakingContract,
uint256 _duration,
uint256 _incentiveAmount,
uint256 _dripFrequency,
uint256 _amountToDistribute
) external;
function setNewRewardsDistributor(address newRewardsDistributor) external;
function removeStakingContract(IStakingRewards stakingContract) external;
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/interfaces/ISanToken.sol
pragma solidity ^0.8.7;
/// @title ISanToken
/// @author Angle Core Team
/// @notice Interface for Angle's `SanToken` contract that handles sanTokens, tokens that are given to SLPs
/// contributing to a collateral for a given stablecoin
interface ISanToken is IERC20Upgradeable {
// ================================== StableMaster =============================
function mint(address account, uint256 amount) external;
function burnFrom(
uint256 amount,
address burner,
address sender
) external;
function burnSelf(uint256 amount, address burner) external;
function stableMaster() external view returns (address);
function poolManager() external view returns (address);
}
// File contracts/interfaces/IStableMaster.sol
pragma solidity ^0.8.7;
// Normally just importing `IPoolManager` should be sufficient, but for clarity here
// we prefer to import all concerned interfaces
// Struct to handle all the parameters to manage the fees
// related to a given collateral pool (associated to the stablecoin)
struct MintBurnData {
// Values of the thresholds to compute the minting fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeMint;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeMint;
// Values of the thresholds to compute the burning fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeBurn;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeBurn;
// Max proportion of collateral from users that can be covered by HAs
// It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated
// the other changes accordingly
uint64 targetHAHedge;
// Minting fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusMint;
// Burning fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusBurn;
// Parameter used to limit the number of stablecoins that can be issued using the concerned collateral
uint256 capOnStableMinted;
}
// Struct to handle all the variables and parameters to handle SLPs in the protocol
// including the fraction of interests they receive or the fees to be distributed to
// them
struct SLPData {
// Last timestamp at which the `sanRate` has been updated for SLPs
uint256 lastBlockUpdated;
// Fees accumulated from previous blocks and to be distributed to SLPs
uint256 lockedInterests;
// Max interests used to update the `sanRate` in a single block
// Should be in collateral token base
uint256 maxInterestsDistributed;
// Amount of fees left aside for SLPs and that will be distributed
// when the protocol is collateralized back again
uint256 feesAside;
// Part of the fees normally going to SLPs that is left aside
// before the protocol is collateralized back again (depends on collateral ratio)
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippageFee;
// Portion of the fees from users minting and burning
// that goes to SLPs (the rest goes to surplus)
uint64 feesForSLPs;
// Slippage factor that's applied to SLPs exiting (depends on collateral ratio)
// If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippage;
// Portion of the interests from lending
// that goes to SLPs (the rest goes to surplus)
uint64 interestsForSLPs;
}
/// @title IStableMasterFunctions
/// @author Angle Core Team
/// @notice Interface for the `StableMaster` contract
interface IStableMasterFunctions {
function deploy(
address[] memory _governorList,
address _guardian,
address _agToken
) external;
// ============================== Lending ======================================
function accumulateInterest(uint256 gain) external;
function signalLoss(uint256 loss) external;
// ============================== HAs ==========================================
function getStocksUsers() external view returns (uint256 maxCAmountInStable);
function convertToSLP(uint256 amount, address user) external;
// ============================== Keepers ======================================
function getCollateralRatio() external returns (uint256);
function setFeeKeeper(
uint64 feeMint,
uint64 feeBurn,
uint64 _slippage,
uint64 _slippageFee
) external;
// ============================== AgToken ======================================
function updateStocksUsers(uint256 amount, address poolManager) external;
// ============================= Governance ====================================
function setCore(address newCore) external;
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address newGuardian, address oldGuardian) external;
function revokeGuardian(address oldGuardian) external;
function setCapOnStableAndMaxInterests(
uint256 _capOnStableMinted,
uint256 _maxInterestsDistributed,
IPoolManager poolManager
) external;
function setIncentivesForSLPs(
uint64 _feesForSLPs,
uint64 _interestsForSLPs,
IPoolManager poolManager
) external;
function setUserFees(
IPoolManager poolManager,
uint64[] memory _xFee,
uint64[] memory _yFee,
uint8 _mint
) external;
function setTargetHAHedge(uint64 _targetHAHedge) external;
function pause(bytes32 agent, IPoolManager poolManager) external;
function unpause(bytes32 agent, IPoolManager poolManager) external;
}
/// @title IStableMaster
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
interface IStableMaster is IStableMasterFunctions {
function agToken() external view returns (address);
function collateralMap(IPoolManager poolManager)
external
view
returns (
IERC20 token,
ISanToken sanToken,
IPerpetualManager perpetualManager,
IOracle oracle,
uint256 stocksUsers,
uint256 sanRate,
uint256 collatBase,
SLPData memory slpData,
MintBurnData memory feeData
);
}
// File contracts/utils/FunctionUtils.sol
pragma solidity ^0.8.7;
/// @title FunctionUtils
/// @author Angle Core Team
/// @notice Contains all the utility functions that are needed in different places of the protocol
/// @dev Functions in this contract should typically be pure functions
/// @dev This contract is voluntarily a contract and not a library to save some gas cost every time it is used
contract FunctionUtils {
/// @notice Base that is used to compute ratios and floating numbers
uint256 public constant BASE_TOKENS = 10**18;
/// @notice Base that is used to define parameters that need to have a floating value (for instance parameters
/// that are defined as ratios)
uint256 public constant BASE_PARAMS = 10**9;
/// @notice Computes the value of a linear by part function at a given point
/// @param x Point of the function we want to compute
/// @param xArray List of breaking points (in ascending order) that define the linear by part function
/// @param yArray List of values at breaking points (not necessarily in ascending order)
/// @dev The evolution of the linear by part function between two breaking points is linear
/// @dev Before the first breaking point and after the last one, the function is constant with a value
/// equal to the first or last value of the yArray
/// @dev This function is relevant if `x` is between O and `BASE_PARAMS`. If `x` is greater than that, then
/// everything will be as if `x` is equal to the greater element of the `xArray`
function _piecewiseLinear(
uint64 x,
uint64[] memory xArray,
uint64[] memory yArray
) internal pure returns (uint64) {
if (x >= xArray[xArray.length - 1]) {
return yArray[xArray.length - 1];
} else if (x <= xArray[0]) {
return yArray[0];
} else {
uint256 lower;
uint256 upper = xArray.length - 1;
uint256 mid;
while (upper - lower > 1) {
mid = lower + (upper - lower) / 2;
if (xArray[mid] <= x) {
lower = mid;
} else {
upper = mid;
}
}
if (yArray[upper] > yArray[lower]) {
// There is no risk of overflow here as in the product of the difference of `y`
// with the difference of `x`, the product is inferior to `BASE_PARAMS**2` which does not
// overflow for `uint64`
return
yArray[lower] +
((yArray[upper] - yArray[lower]) * (x - xArray[lower])) /
(xArray[upper] - xArray[lower]);
} else {
return
yArray[lower] -
((yArray[lower] - yArray[upper]) * (x - xArray[lower])) /
(xArray[upper] - xArray[lower]);
}
}
}
/// @notice Checks if the input arrays given by governance to update the fee structure is valid
/// @param xArray List of breaking points (in ascending order) that define the linear by part function
/// @param yArray List of values at breaking points (not necessarily in ascending order)
/// @dev This function is a way to avoid some governance attacks or errors
/// @dev The modifier checks if the arrays have a non null length, if their length is the same, if the values
/// in the `xArray` are in ascending order and if the values in the `xArray` and in the `yArray` are not superior
/// to `BASE_PARAMS`
modifier onlyCompatibleInputArrays(uint64[] memory xArray, uint64[] memory yArray) {
require(xArray.length == yArray.length && xArray.length > 0, "5");
for (uint256 i = 0; i <= yArray.length - 1; i++) {
require(yArray[i] <= uint64(BASE_PARAMS) && xArray[i] <= uint64(BASE_PARAMS), "6");
if (i > 0) {
require(xArray[i] > xArray[i - 1], "7");
}
}
_;
}
/// @notice Checks if the new value given for the parameter is consistent (it should be inferior to 1
/// if it corresponds to a ratio)
/// @param fees Value of the new parameter to check
modifier onlyCompatibleFees(uint64 fees) {
require(fees <= BASE_PARAMS, "4");
_;
}
/// @notice Checks if the new address given is not null
/// @param newAddress Address to check
/// @dev Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#missing-zero-address-validation
modifier zeroCheck(address newAddress) {
require(newAddress != address(0), "0");
_;
}
}
// File contracts/perpetualManager/PerpetualManagerEvents.sol
pragma solidity ^0.8.7;
// Used in the `forceCashOutPerpetuals` function to store owners of perpetuals which have been force cashed
// out, along with the amount associated to it
struct Pairs {
address owner;
uint256 netCashOutAmount;
}
/// @title PerpetualManagerEvents
/// @author Angle Core Team
/// @notice `PerpetualManager` is the contract handling all the Hedging Agents perpetuals
/// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol
/// @dev This file contains all the events of the `PerpetualManager` contract
contract PerpetualManagerEvents {
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);
event PerpetualUpdated(uint256 _perpetualID, uint256 _margin);
event PerpetualOpened(uint256 _perpetualID, uint256 _entryRate, uint256 _margin, uint256 _committedAmount);
event PerpetualClosed(uint256 _perpetualID, uint256 _closeAmount);
event PerpetualsForceClosed(uint256[] perpetualIDs, Pairs[] ownerAndCashOut, address keeper, uint256 reward);
event KeeperTransferred(address keeperAddress, uint256 liquidationFees);
// ============================== Parameters ===================================
event BaseURIUpdated(string _baseURI);
event LockTimeUpdated(uint64 _lockTime);
event KeeperFeesCapUpdated(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap);
event TargetAndLimitHAHedgeUpdated(uint64 _targetHAHedge, uint64 _limitHAHedge);
event BoundsPerpetualUpdated(uint64 _maxLeverage, uint64 _maintenanceMargin);
event HAFeesUpdated(uint64[] _xHAFees, uint64[] _yHAFees, uint8 deposit);
event KeeperFeesLiquidationRatioUpdated(uint64 _keeperFeesLiquidationRatio);
event KeeperFeesClosingUpdated(uint64[] xKeeperFeesClosing, uint64[] yKeeperFeesClosing);
// =============================== Reward ======================================
event RewardAdded(uint256 _reward);
event RewardPaid(address indexed _user, uint256 _reward);
event RewardsDistributionUpdated(address indexed _rewardsDistributor);
event RewardsDistributionDurationUpdated(uint256 _rewardsDuration, address indexed _rewardsDistributor);
event Recovered(address indexed tokenAddress, address indexed to, uint256 amount);
}
// File contracts/perpetualManager/PerpetualManagerStorage.sol
pragma solidity ^0.8.7;
struct Perpetual {
// Oracle value at the moment of perpetual opening
uint256 entryRate;
// Timestamp at which the perpetual was opened
uint256 entryTimestamp;
// Amount initially brought in the perpetual (net from fees) + amount added - amount removed from it
// This is the only element that can be modified in the perpetual after its creation
uint256 margin;
// Amount of collateral covered by the perpetual. This cannot be modified once the perpetual is opened.
// The amount covered is used interchangeably with the amount hedged
uint256 committedAmount;
}
/// @title PerpetualManagerStorage
/// @author Angle Core Team
/// @notice `PerpetualManager` is the contract handling all the Hedging Agents positions and perpetuals
/// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol
/// @dev This file contains all the parameters and references used in the `PerpetualManager` contract
// solhint-disable-next-line max-states-count
contract PerpetualManagerStorage is PerpetualManagerEvents, FunctionUtils {
// Base used in the collateral implementation (ERC20 decimal)
uint256 internal _collatBase;
// ============================== Perpetual Variables ==========================
/// @notice Total amount of stablecoins that are insured (i.e. that could be redeemed against
/// collateral thanks to HAs)
/// When a HA opens a perpetual, it covers/hedges a fixed amount of stablecoins for the protocol, equal to
/// the committed amount times the entry rate
/// `totalHedgeAmount` is the sum of all these hedged amounts
uint256 public totalHedgeAmount;
// Counter to generate a unique `perpetualID` for each perpetual
CountersUpgradeable.Counter internal _perpetualIDcount;
// ========================== Mutable References ============================
/// @notice `Oracle` to give the rate feed, that is the price of the collateral
/// with respect to the price of the stablecoin
/// This reference can be modified by the corresponding `StableMaster` contract
IOracle public oracle;
// `FeeManager` address allowed to update the way fees are computed for this contract
// This reference can be modified by the `PoolManager` contract
IFeeManager internal _feeManager;
// ========================== Immutable References ==========================
/// @notice Interface for the `rewardToken` distributed as a reward
/// As of Angle V1, only a single `rewardToken` can be distributed to HAs who own a perpetual
/// This implementation assumes that reward tokens have a base of 18 decimals
IERC20 public rewardToken;
/// @notice Address of the `PoolManager` instance
IPoolManager public poolManager;
// Address of the `StableMaster` instance
IStableMaster internal _stableMaster;
// Interface for the underlying token accepted by this contract
// This reference cannot be changed, it is taken from the `PoolManager`
IERC20 internal _token;
// ======================= Fees and other Parameters ===========================
/// Deposit fees for HAs depend on the hedge ratio that is the ratio between what is hedged
/// (or covered, this is a synonym) by HAs compared with the total amount to hedge
/// @notice Thresholds for the ratio between to amount hedged and the amount to hedge
/// The bigger the ratio the bigger the fees will be because this means that the max amount
/// to insure is soon to be reached
uint64[] public xHAFeesDeposit;
/// @notice Deposit fees at threshold values
/// This array should have the same length as the array above
/// The evolution of the fees between two threshold values is linear
uint64[] public yHAFeesDeposit;
/// Withdraw fees for HAs also depend on the hedge ratio
/// @notice Thresholds for the hedge ratio
uint64[] public xHAFeesWithdraw;
/// @notice Withdraw fees at threshold values
uint64[] public yHAFeesWithdraw;
/// @notice Maintenance Margin (in `BASE_PARAMS`) for each perpetual
/// The margin ratio is defined for a perpetual as: `(initMargin + PnL) / committedAmount` where
/// `PnL = committedAmount * (1 - initRate/currentRate)`
/// If the `marginRatio` is below `maintenanceMargin`: then the perpetual can be liquidated
uint64 public maintenanceMargin;
/// @notice Maximum leverage multiplier authorized for HAs (`in BASE_PARAMS`)
/// Leverage for a perpetual here corresponds to the ratio between the amount committed
/// and the margin of the perpetual
uint64 public maxLeverage;
/// @notice Target proportion of stablecoins issued using this collateral to insure with HAs.
/// This variable is exactly the same as the one in the `StableMaster` contract for this collateral.
/// Above this hedge ratio, HAs cannot open new perpetuals
/// When keepers are forcing the closing of some perpetuals, they are incentivized to bringing
/// the hedge ratio to this proportion
uint64 public targetHAHedge;
/// @notice Limit proportion of stablecoins issued using this collateral that HAs can insure
/// Above this ratio `forceCashOut` is activated and anyone can see its perpetual cashed out
uint64 public limitHAHedge;
/// @notice Extra parameter from the `FeeManager` contract that is multiplied to the fees from above and that
/// can be used to change deposit fees. It works as a bonus - malus fee, if `haBonusMalusDeposit > BASE_PARAMS`,
/// then the fee will be larger than `haFeesDeposit`, if `haBonusMalusDeposit < BASE_PARAMS`, fees will be smaller.
/// This parameter, updated by keepers in the `FeeManager` contract, could most likely depend on the collateral ratio
uint64 public haBonusMalusDeposit;
/// @notice Extra parameter from the `FeeManager` contract that is multiplied to the fees from above and that
/// can be used to change withdraw fees. It works as a bonus - malus fee, if `haBonusMalusWithdraw > BASE_PARAMS`,
/// then the fee will be larger than `haFeesWithdraw`, if `haBonusMalusWithdraw < BASE_PARAMS`, fees will be smaller
uint64 public haBonusMalusWithdraw;
/// @notice Amount of time before HAs are allowed to withdraw funds from their perpetuals
/// either using `removeFromPerpetual` or `closePerpetual`. New perpetuals cannot be forced closed in
/// situations where the `forceClosePerpetuals` function is activated before this `lockTime` elapsed
uint64 public lockTime;
// ================================= Keeper fees ======================================
// All these parameters can be modified by their corresponding governance function
/// @notice Portion of the leftover cash out amount of liquidated perpetuals that go to
/// liquidating keepers
uint64 public keeperFeesLiquidationRatio;
/// @notice Cap on the fees that go to keepers liquidating a perpetual
/// If a keeper liquidates n perpetuals in a single transaction, then this keeper is entitled to get as much as
/// `n * keeperFeesLiquidationCap` as a reward
uint256 public keeperFeesLiquidationCap;
/// @notice Cap on the fees that go to keepers closing perpetuals when too much collateral is hedged by HAs
/// (hedge ratio above `limitHAHedge`)
/// If a keeper forces the closing of n perpetuals in a single transaction, then this keeper is entitled to get
/// as much as `keeperFeesClosingCap`. This cap amount is independent of the number of perpetuals closed
uint256 public keeperFeesClosingCap;
/// @notice Thresholds on the values of the rate between the current hedged amount (`totalHedgeAmount`) and the
/// target hedged amount by HAs (`targetHedgeAmount`) divided by 2. A value of `0.5` corresponds to a hedge ratio
/// of `1`. Doing this allows to maintain an array with values of `x` inferior to `BASE_PARAMS`.
uint64[] public xKeeperFeesClosing;
/// @notice Values at thresholds of the proportions of the fees that should go to keepers closing perpetuals
uint64[] public yKeeperFeesClosing;
// =========================== Staking Parameters ==============================
/// @notice Below are parameters that can also be found in other staking contracts
/// to be able to compute rewards from staking (having perpetuals here) correctly
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public rewardsDuration;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
address public rewardsDistribution;
// ============================== ERC721 Base URI ==============================
/// @notice URI used for the metadata of the perpetuals
string public baseURI;
// =============================== Mappings ====================================
/// @notice Mapping from `perpetualID` to perpetual data
mapping(uint256 => Perpetual) public perpetualData;
/// @notice Mapping used to compute the rewards earned by a perpetual in a timeframe
mapping(uint256 => uint256) public perpetualRewardPerTokenPaid;
/// @notice Mapping used to get how much rewards in governance tokens are gained by a perpetual
// identified by its ID
mapping(uint256 => uint256) public rewards;
// Mapping from `perpetualID` to owner address
mapping(uint256 => address) internal _owners;
// Mapping from owner address to perpetual owned count
mapping(address => uint256) internal _balances;
// Mapping from `perpetualID` to approved address
mapping(uint256 => address) internal _perpetualApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) internal _operatorApprovals;
}
// File contracts/perpetualManager/PerpetualManagerInternal.sol
pragma solidity ^0.8.7;
/// @title PerpetualManagerInternal
/// @author Angle Core Team
/// @notice `PerpetualManager` is the contract handling all the Hedging Agents perpetuals
/// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol
/// @dev This file contains all the internal functions of the `PerpetualManager` contract
contract PerpetualManagerInternal is PerpetualManagerStorage {
using Address for address;
using SafeERC20 for IERC20;
// ======================== State Modifying Functions ==========================
/// @notice Cashes out a perpetual, which means that it simply deletes the references to the perpetual
/// in the contract
/// @param perpetualID ID of the perpetual
/// @param perpetual Data of the perpetual
function _closePerpetual(uint256 perpetualID, Perpetual memory perpetual) internal {
// Handling the staking logic
// Reward should always be updated before the `totalHedgeAmount`
// Rewards are distributed to the perpetual which is liquidated
uint256 hedge = perpetual.committedAmount * perpetual.entryRate;
_getReward(perpetualID, hedge);
delete perpetualRewardPerTokenPaid[perpetualID];
// Updating `totalHedgeAmount` to represent the fact that less money is insured
totalHedgeAmount -= hedge / _collatBase;
_burn(perpetualID);
}
/// @notice Allows the protocol to transfer collateral to an address while handling the case where there are
/// not enough reserves
/// @param owner Address of the receiver
/// @param amount The amount of collateral sent
/// @dev If there is not enough collateral in balance (this can happen when money has been lent to strategies),
/// then the owner is reimbursed by receiving what is missing in sanTokens at the correct value
function _secureTransfer(address owner, uint256 amount) internal {
uint256 curBalance = poolManager.getBalance();
if (curBalance >= amount && amount > 0) {
// Case where there is enough in reserves to reimburse the person
_token.safeTransferFrom(address(poolManager), owner, amount);
} else if (amount > 0) {
// When there is not enough to reimburse the entire amount, the protocol reimburses
// what it can using its reserves and the rest is paid in sanTokens at the current
// exchange rate
uint256 amountLeft = amount - curBalance;
_token.safeTransferFrom(address(poolManager), owner, curBalance);
_stableMaster.convertToSLP(amountLeft, owner);
}
}
/// @notice Checks whether the perpetual should be liquidated or not, and if so liquidates the perpetual
/// @param perpetualID ID of the perpetual to check and potentially liquidate
/// @param perpetual Data of the perpetual to check
/// @param rateDown Oracle value to compute the cash out amount of the perpetual
/// @return Cash out amount of the perpetual
/// @return Whether the perpetual was liquidated or not
/// @dev Generally, to check for the liquidation of a perpetual, we use the lowest oracle value possible:
/// it's the one that is most at the advantage of the protocol, hence the `rateDown` parameter
function _checkLiquidation(
uint256 perpetualID,
Perpetual memory perpetual,
uint256 rateDown
) internal returns (uint256, uint256) {
uint256 liquidated;
(uint256 cashOutAmount, uint256 reachMaintenanceMargin) = _getCashOutAmount(perpetual, rateDown);
if (cashOutAmount == 0 || reachMaintenanceMargin == 1) {
_closePerpetual(perpetualID, perpetual);
// No need for an event to find out that a perpetual is liquidated
liquidated = 1;
}
return (cashOutAmount, liquidated);
}
// ========================= Internal View Functions ===========================
/// @notice Gets the current cash out amount of a perpetual
/// @param perpetual Data of the concerned perpetual
/// @param rate Value of the oracle
/// @return cashOutAmount Amount that the HA could get by closing this perpetual
/// @return reachMaintenanceMargin Whether the position of the perpetual is now too small
/// compared with its initial position
/// @dev Refer to the whitepaper or the doc for the formulas of the cash out amount
/// @dev The notion of `maintenanceMargin` is standard in centralized platforms offering perpetual futures
function _getCashOutAmount(Perpetual memory perpetual, uint256 rate)
internal
view
returns (uint256 cashOutAmount, uint256 reachMaintenanceMargin)
{
// All these computations are made just because we are working with uint and not int
// so we cannot do x-y if x<y
uint256 newCommit = (perpetual.committedAmount * perpetual.entryRate) / rate;
// Checking if a liquidation is needed: for this to happen the `cashOutAmount` should be inferior
// to the maintenance margin of the perpetual
reachMaintenanceMargin;
if (newCommit >= perpetual.committedAmount + perpetual.margin) cashOutAmount = 0;
else {
// The definition of the margin ratio is `(margin + PnL) / committedAmount`
// where `PnL = commit * (1-entryRate/currentRate)`
// So here: `newCashOutAmount = margin + PnL`
cashOutAmount = perpetual.committedAmount + perpetual.margin - newCommit;
if (cashOutAmount * BASE_PARAMS <= perpetual.committedAmount * maintenanceMargin)
reachMaintenanceMargin = 1;
}
}
/// @notice Calls the oracle to read both Chainlink and Uniswap rates
/// @return The lowest oracle value (between Chainlink and Uniswap) is the first outputted value
/// @return The highest oracle value is the second output
/// @dev If the oracle only involves a single oracle fees (like just Chainlink for USD-EUR),
/// the same value is returned twice
function _getOraclePrice() internal view returns (uint256, uint256) {
return oracle.readAll();
}
/// @notice Computes the incentive for the keeper as a function of the cash out amount of a liquidated perpetual
/// which value falls below its maintenance margin
/// @param cashOutAmount Value remaining in the perpetual
/// @dev By computing keeper fees as a fraction of the cash out amount of a perpetual rather than as a fraction
/// of the `committedAmount`, keepers are incentivized to react fast when a perpetual is below the maintenance margin
/// @dev Perpetual exchange protocols typically compute liquidation fees using an equivalent of the `committedAmount`,
/// this is not the case here
function _computeKeeperLiquidationFees(uint256 cashOutAmount) internal view returns (uint256 keeperFees) {
keeperFees = (cashOutAmount * keeperFeesLiquidationRatio) / BASE_PARAMS;
keeperFees = keeperFees < keeperFeesLiquidationCap ? keeperFees : keeperFeesLiquidationCap;
}
/// @notice Gets the value of the hedge ratio that is the ratio between the amount currently hedged by HAs
/// and the target amount that should be hedged by them
/// @param currentHedgeAmount Amount currently covered by HAs
/// @return ratio Ratio between the amount of collateral (in stablecoin value) currently hedged
/// and the target amount to hedge
function _computeHedgeRatio(uint256 currentHedgeAmount) internal view returns (uint64 ratio) {
// Fetching info from the `StableMaster`: the amount to hedge is based on the `stocksUsers`
// of the given collateral
uint256 targetHedgeAmount = (_stableMaster.getStocksUsers() * targetHAHedge) / BASE_PARAMS;
if (currentHedgeAmount < targetHedgeAmount)
ratio = uint64((currentHedgeAmount * BASE_PARAMS) / targetHedgeAmount);
else ratio = uint64(BASE_PARAMS);
}
// =========================== Fee Computation =================================
/// @notice Gets the net margin corrected from the fees at perpetual opening
/// @param margin Amount brought in the perpetual at creation
/// @param totalHedgeAmountUpdate Amount of stablecoins that this perpetual is going to insure
/// @param committedAmount Committed amount in the perpetual, we need it to compute the fees
/// paid by the HA
/// @return netMargin Amount that will be written in the perpetual as the `margin`
/// @dev The amount of stablecoins insured by a perpetual is `committedAmount * oracleRate / _collatBase`
function _getNetMargin(
uint256 margin,
uint256 totalHedgeAmountUpdate,
uint256 committedAmount
) internal view returns (uint256 netMargin) {
// Checking if the HA has the right to open a perpetual with such amount
// If HAs hedge more than the target amount, then new HAs will not be able to create perpetuals
// The amount hedged by HAs after opening the perpetual is going to be:
uint64 ratio = _computeHedgeRatio(totalHedgeAmount + totalHedgeAmountUpdate);
require(ratio < uint64(BASE_PARAMS), "25");
// Computing the net margin of HAs to store in the perpetual: it consists simply in deducing fees
// Those depend on how much is already hedged by HAs compared with what's to hedge
uint256 haFeesDeposit = (haBonusMalusDeposit * _piecewiseLinear(ratio, xHAFeesDeposit, yHAFeesDeposit)) /
BASE_PARAMS;
// Fees are rounded to the advantage of the protocol
haFeesDeposit = committedAmount - (committedAmount * (BASE_PARAMS - haFeesDeposit)) / BASE_PARAMS;
// Fees are computed based on the committed amount of the perpetual
// The following reverts if fees are too big compared to the margin
netMargin = margin - haFeesDeposit;
}
/// @notice Gets the net amount to give to a HA (corrected from the fees) in case of a perpetual closing
/// @param committedAmount Committed amount in the perpetual
/// @param cashOutAmount The current cash out amount of the perpetual
/// @param ratio What's hedged divided by what's to hedge
/// @return netCashOutAmount Amount that will be distributed to the HA
/// @return feesPaid Amount of fees paid by the HA at perpetual closing
/// @dev This function is called by the `closePerpetual` and by the `forceClosePerpetuals`
/// function
/// @dev The amount of fees paid by the HA is used to compute the incentive given to HAs closing perpetuals
/// when too much is covered
function _getNetCashOutAmount(
uint256 cashOutAmount,
uint256 committedAmount,
uint64 ratio
) internal view returns (uint256 netCashOutAmount, uint256 feesPaid) {
feesPaid = (haBonusMalusWithdraw * _piecewiseLinear(ratio, xHAFeesWithdraw, yHAFeesWithdraw)) / BASE_PARAMS;
// Rounding the fees at the protocol's advantage
feesPaid = committedAmount - (committedAmount * (BASE_PARAMS - feesPaid)) / BASE_PARAMS;
if (feesPaid >= cashOutAmount) {
netCashOutAmount = 0;
feesPaid = cashOutAmount;
} else {
netCashOutAmount = cashOutAmount - feesPaid;
}
}
// ========================= Reward Distribution ===============================
/// @notice View function to query the last timestamp at which a reward was distributed
/// @return Current timestamp if a reward is being distributed or the last timestamp
function _lastTimeRewardApplicable() internal view returns (uint256) {
uint256 returnValue = block.timestamp < periodFinish ? block.timestamp : periodFinish;
return returnValue;
}
/// @notice Used to actualize the `rewardPerTokenStored`
/// @dev It adds to the reward per token: the time elapsed since the `rewardPerTokenStored`
/// was last updated multiplied by the `rewardRate` divided by the number of tokens
/// @dev Specific attention should be placed on the base here: `rewardRate` is in the base of the reward token
/// and `totalHedgeAmount` is in `BASE_TOKENS` here: as this function concerns an amount of reward
/// tokens, the output of this function should be in the base of the reward token too
function _rewardPerToken() internal view returns (uint256) {
if (totalHedgeAmount == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored +
((_lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * BASE_TOKENS) /
totalHedgeAmount;
}
/// @notice Allows a perpetual owner to withdraw rewards
/// @param perpetualID ID of the perpetual which accumulated tokens
/// @param hedge Perpetual commit amount times the entry rate
/// @dev Internal version of the `getReward` function
/// @dev In case where an approved address calls to close a perpetual, rewards are still going to get distributed
/// to the owner of the perpetual, and not necessarily to the address getting the proceeds of the perpetual
function _getReward(uint256 perpetualID, uint256 hedge) internal {
_updateReward(perpetualID, hedge);
uint256 reward = rewards[perpetualID];
if (reward > 0) {
rewards[perpetualID] = 0;
address owner = _owners[perpetualID];
// Attention here, there may be reentrancy attacks because of the following call
// to an external contract done before other things are modified. Yet since the `rewardToken`
// is mostly going to be a trusted contract controlled by governance (namely the ANGLE token), then
// there is no point in putting an expensive `nonReentrant` modifier in the functions in `PerpetualManagerFront`
// that allow indirect interactions with `_updateReward`. If new `rewardTokens` are set, we could think about
// upgrading the `PerpetualManagerFront` contract
rewardToken.safeTransfer(owner, reward);
emit RewardPaid(owner, reward);
}
}
/// @notice Allows to check the amount of gov tokens earned by a perpetual
/// @param perpetualID ID of the perpetual which accumulated tokens
/// @param hedge Perpetual commit amount times the entry rate
/// @return Amount of gov tokens earned by the perpetual
/// @dev A specific attention should be paid to have the base here: we consider that each HA stakes an amount
/// equal to `committedAmount * entryRate / _collatBase`, here as the `hedge` corresponds to `committedAmount * entryRate`,
/// we just need to divide by `_collatBase`
/// @dev HAs earn reward tokens which are in base `BASE_TOKENS`
function _earned(uint256 perpetualID, uint256 hedge) internal view returns (uint256) {
return
(hedge * (_rewardPerToken() - perpetualRewardPerTokenPaid[perpetualID])) /
BASE_TOKENS /
_collatBase +
rewards[perpetualID];
}
/// @notice Updates the amount of gov tokens earned by a perpetual
/// @param perpetualID of the perpetual which earns tokens
/// @param hedge Perpetual commit amount times the entry rate
/// @dev When this function is called in the code, it has already been checked that the `perpetualID`
/// exists
function _updateReward(uint256 perpetualID, uint256 hedge) internal {
rewardPerTokenStored = _rewardPerToken();
lastUpdateTime = _lastTimeRewardApplicable();
// No need to check if the `perpetualID` exists here, it has already been checked
// in the code before when this internal function is called
rewards[perpetualID] = _earned(perpetualID, hedge);
perpetualRewardPerTokenPaid[perpetualID] = rewardPerTokenStored;
}
// =============================== ERC721 Logic ================================
/// @notice Gets the owner of a perpetual
/// @param perpetualID ID of the concerned perpetual
/// @return owner Owner of the perpetual
function _ownerOf(uint256 perpetualID) internal view returns (address owner) {
owner = _owners[perpetualID];
require(owner != address(0), "2");
}
/// @notice Gets the addresses approved for a perpetual
/// @param perpetualID ID of the concerned perpetual
/// @return Address approved for this perpetual
function _getApproved(uint256 perpetualID) internal view returns (address) {
return _perpetualApprovals[perpetualID];
}
/// @notice Safely transfers `perpetualID` token from `from` to `to`, checking first that contract recipients
/// are aware of the ERC721 protocol to prevent tokens from being forever locked
/// @param perpetualID ID of the concerned perpetual
/// @param _data Additional data, it has no specified format and it is sent in call to `to`
/// @dev 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
/// @dev Requirements:
/// - `from` cannot be the zero address.
/// - `to` cannot be the zero address.
/// - `perpetualID` 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.
function _safeTransfer(
address from,
address to,
uint256 perpetualID,
bytes memory _data
) internal {
_transfer(from, to, perpetualID);
require(_checkOnERC721Received(from, to, perpetualID, _data), "24");
}
/// @notice Returns whether `perpetualID` exists
/// @dev Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}
/// @dev Tokens start existing when they are minted (`_mint`),
/// and stop existing when they are burned (`_burn`)
function _exists(uint256 perpetualID) internal view returns (bool) {
return _owners[perpetualID] != address(0);
}
/// @notice Returns whether `spender` is allowed to manage `perpetualID`
/// @dev `perpetualID` must exist
function _isApprovedOrOwner(address spender, uint256 perpetualID) internal view returns (bool) {
// The following checks if the perpetual exists
address owner = _ownerOf(perpetualID);
return (spender == owner || _getApproved(perpetualID) == spender || _operatorApprovals[owner][spender]);
}
/// @notice Mints `perpetualID` and transfers it to `to`
/// @dev This method is equivalent to the `_safeMint` method used in OpenZeppelin ERC721 contract
/// @dev `perpetualID` must not exist and `to` cannot be the zero address
/// @dev Before calling this function it is checked that the `perpetualID` does not exist as it
/// comes from a counter that has been incremented
/// @dev Emits a {Transfer} event
function _mint(address to, uint256 perpetualID) internal {
_balances[to] += 1;
_owners[perpetualID] = to;
emit Transfer(address(0), to, perpetualID);
require(_checkOnERC721Received(address(0), to, perpetualID, ""), "24");
}
/// @notice Destroys `perpetualID`
/// @dev `perpetualID` must exist
/// @dev Emits a {Transfer} event
function _burn(uint256 perpetualID) internal {
address owner = _ownerOf(perpetualID);
// Clear approvals
_approve(address(0), perpetualID);
_balances[owner] -= 1;
delete _owners[perpetualID];
delete perpetualData[perpetualID];
emit Transfer(owner, address(0), perpetualID);
}
/// @notice Transfers `perpetualID` from `from` to `to` as opposed to {transferFrom},
/// this imposes no restrictions on msg.sender
/// @dev `to` cannot be the zero address and `perpetualID` must be owned by `from`
/// @dev Emits a {Transfer} event
function _transfer(
address from,
address to,
uint256 perpetualID
) internal {
require(_ownerOf(perpetualID) == from, "1");
require(to != address(0), "26");
// Clear approvals from the previous owner
_approve(address(0), perpetualID);
_balances[from] -= 1;
_balances[to] += 1;
_owners[perpetualID] = to;
emit Transfer(from, to, perpetualID);
}
/// @notice Approves `to` to operate on `perpetualID`
function _approve(address to, uint256 perpetualID) internal {
_perpetualApprovals[perpetualID] = to;
emit Approval(_ownerOf(perpetualID), to, perpetualID);
}
/// @notice Internal function to invoke {IERC721Receiver-onERC721Received} on a target address
/// The call is not executed if the target address is not a contract
/// @param from Address representing the previous owner of the given token ID
/// @param to Target address that will receive the tokens
/// @param perpetualID 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 perpetualID,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(msg.sender, from, perpetualID, _data) returns (
bytes4 retval
) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("24");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
}
// File contracts/perpetualManager/PerpetualManager.sol
pragma solidity ^0.8.7;
/// @title PerpetualManager
/// @author Angle Core Team
/// @notice `PerpetualManager` is the contract handling all the Hedging Agents positions and perpetuals
/// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol
/// @dev This file contains the functions of the `PerpetualManager` that can be interacted with
/// by `StableMaster`, by the `PoolManager`, by the `FeeManager` and by governance
contract PerpetualManager is
PerpetualManagerInternal,
IPerpetualManagerFunctions,
IStakingRewardsFunctions,
AccessControlUpgradeable,
PausableUpgradeable
{
using SafeERC20 for IERC20;
/// @notice Role for guardians, governors and `StableMaster`
/// Made for the `StableMaster` to be able to update some parameters
bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
/// @notice Role for `PoolManager` only
bytes32 public constant POOLMANAGER_ROLE = keccak256("POOLMANAGER_ROLE");
// ============================== Modifiers ====================================
/// @notice Checks if the person interacting with the perpetual with `perpetualID` is approved
/// @param caller Address of the person seeking to interact with the perpetual
/// @param perpetualID ID of the concerned perpetual
/// @dev Generally in `PerpetualManager`, perpetual owners should store the ID of the perpetuals
/// they are able to interact with
modifier onlyApprovedOrOwner(address caller, uint256 perpetualID) {
require(_isApprovedOrOwner(caller, perpetualID), "21");
_;
}
/// @notice Checks if the message sender is the rewards distribution address
modifier onlyRewardsDistribution() {
require(msg.sender == rewardsDistribution, "1");
_;
}
// =============================== Deployer ====================================
/// @notice Notifies the address of the `_feeManager` and of the `oracle`
/// to this contract and grants the correct roles
/// @param governorList List of governor addresses of the protocol
/// @param guardian Address of the guardian of the protocol
/// @param feeManager_ Reference to the `FeeManager` contract which will be able to update fees
/// @param oracle_ Reference to the `oracle` contract which will be able to update fees
/// @dev Called by the `PoolManager` contract when it is activated by the `StableMaster`
/// @dev The `governorList` and `guardian` here are those of the `Core` contract
function deployCollateral(
address[] memory governorList,
address guardian,
IFeeManager feeManager_,
IOracle oracle_
) external override onlyRole(POOLMANAGER_ROLE) {
for (uint256 i = 0; i < governorList.length; i++) {
_grantRole(GUARDIAN_ROLE, governorList[i]);
}
// In the end guardian should be revoked by governance
_grantRole(GUARDIAN_ROLE, guardian);
_grantRole(GUARDIAN_ROLE, address(_stableMaster));
_feeManager = feeManager_;
oracle = oracle_;
}
// ========================== Rewards Distribution =============================
/// @notice Notifies the contract that rewards are going to be shared among HAs of this pool
/// @param reward Amount of governance tokens to be distributed to HAs
/// @dev Only the reward distributor contract is allowed to call this function which starts a staking cycle
/// @dev This function is the equivalent of the `notifyRewardAmount` function found in all staking contracts
function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution {
rewardPerTokenStored = _rewardPerToken();
if (block.timestamp >= periodFinish) {
// If the period is not done, then the reward rate changes
rewardRate = reward / rewardsDuration;
} else {
uint256 remaining = periodFinish - block.timestamp;
uint256 leftover = remaining * rewardRate;
// If the period is not over, we compute the reward left and increase reward duration
rewardRate = (reward + leftover) / rewardsDuration;
}
// Ensuring the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of `rewardRate` in the earned and `rewardsPerToken` functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardToken.balanceOf(address(this));
require(rewardRate <= balance / rewardsDuration, "22");
lastUpdateTime = block.timestamp;
// Change the duration
periodFinish = block.timestamp + rewardsDuration;
emit RewardAdded(reward);
}
/// @notice Supports recovering LP Rewards from other systems such as BAL to be distributed to holders
/// or tokens that were mistakenly
/// @param tokenAddress Address of the token to transfer
/// @param to Address to give tokens to
/// @param tokenAmount Amount of tokens to transfer
function recoverERC20(
address tokenAddress,
address to,
uint256 tokenAmount
) external override onlyRewardsDistribution {
require(tokenAddress != address(rewardToken), "20");
IERC20(tokenAddress).safeTransfer(to, tokenAmount);
emit Recovered(tokenAddress, to, tokenAmount);
}
/// @notice Changes the `rewardsDistribution` associated to this contract
/// @param _rewardsDistribution Address of the new rewards distributor contract
/// @dev This function is part of the staking rewards interface and it is used to propagate
/// a change of rewards distributor notified by the current `rewardsDistribution` address
/// @dev It has already been checked in the `RewardsDistributor` contract calling
/// this function that the `newRewardsDistributor` had a compatible reward token
/// @dev With this function, everything is as if `rewardsDistribution` was admin of its own role
function setNewRewardsDistribution(address _rewardsDistribution) external override onlyRewardsDistribution {
rewardsDistribution = _rewardsDistribution;
emit RewardsDistributionUpdated(_rewardsDistribution);
}
// ================================= Keepers ===================================
/// @notice Updates all the fees not depending on individual HA conditions via keeper utils functions
/// @param feeDeposit New deposit global fees
/// @param feeWithdraw New withdraw global fees
/// @dev Governance may decide to incorporate a collateral ratio dependence in the fees for HAs,
/// in this case it will be done through the `FeeManager` contract
/// @dev This dependence can either be a bonus or a malus
function setFeeKeeper(uint64 feeDeposit, uint64 feeWithdraw) external override {
require(msg.sender == address(_feeManager), "1");
haBonusMalusDeposit = feeDeposit;
haBonusMalusWithdraw = feeWithdraw;
}
// ======== Governance - Guardian Functions - Staking and Pauses ===============
/// @notice Pauses the `getReward` method as well as the functions allowing to open, modify or close perpetuals
/// @dev After calling this function, it is going to be impossible for HAs to interact with their perpetuals
/// or claim their rewards on it
function pause() external override onlyRole(GUARDIAN_ROLE) {
_pause();
}
/// @notice Unpauses HAs functions
function unpause() external override onlyRole(GUARDIAN_ROLE) {
_unpause();
}
/// @notice Sets the conditions and specifies the duration of the reward distribution
/// @param _rewardsDuration Duration for the rewards for this contract
/// @param _rewardsDistribution Address which will give the reward tokens
/// @dev It allows governance to directly change the rewards distribution contract and the conditions
/// at which this distribution is done
/// @dev The compatibility of the reward token is not checked here: it is checked
/// in the rewards distribution contract when activating this as a staking contract,
/// so if a reward distributor is set here but does not have a compatible reward token, then this reward
/// distributor will not be able to set this contract as a staking contract
function setRewardDistribution(uint256 _rewardsDuration, address _rewardsDistribution)
external
onlyRole(GUARDIAN_ROLE)
zeroCheck(_rewardsDistribution)
{
rewardsDuration = _rewardsDuration;
rewardsDistribution = _rewardsDistribution;
emit RewardsDistributionDurationUpdated(rewardsDuration, rewardsDistribution);
}
// ============ Governance - Guardian Functions - Parameters ===================
/// @notice Sets `baseURI` that is the URI to access ERC721 metadata
/// @param _baseURI New `baseURI` parameter
function setBaseURI(string memory _baseURI) external onlyRole(GUARDIAN_ROLE) {
baseURI = _baseURI;
emit BaseURIUpdated(_baseURI);
}
/// @notice Sets `lockTime` that is the minimum amount of time HAs have to stay within the protocol
/// @param _lockTime New `lockTime` parameter
/// @dev This parameter is used to prevent HAs from exiting before a certain amount of time and taking advantage
/// of insiders' information they may have due to oracle latency
function setLockTime(uint64 _lockTime) external override onlyRole(GUARDIAN_ROLE) {
lockTime = _lockTime;
emit LockTimeUpdated(_lockTime);
}
/// @notice Changes the maximum leverage authorized (commit/margin) and the maintenance margin under which
/// perpetuals can be liquidated
/// @param _maxLeverage New value of the maximum leverage allowed
/// @param _maintenanceMargin The new maintenance margin
/// @dev For a perpetual, the leverage is defined as the ratio between the committed amount and the margin
/// @dev For a perpetual, the maintenance margin is defined as the ratio between the margin ratio / the committed amount
function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin)
external
override
onlyRole(GUARDIAN_ROLE)
onlyCompatibleFees(_maintenanceMargin)
{
// Checking the compatibility of the parameters
require(BASE_PARAMS**2 > _maxLeverage * _maintenanceMargin, "8");
maxLeverage = _maxLeverage;
maintenanceMargin = _maintenanceMargin;
emit BoundsPerpetualUpdated(_maxLeverage, _maintenanceMargin);
}
/// @notice Sets `xHAFees` that is the thresholds of values of the ratio between what's covered (hedged)
/// divided by what's to hedge with HAs at which fees will change as well as
/// `yHAFees` that is the value of the deposit or withdraw fees at threshold
/// @param _xHAFees Array of the x-axis value for the fees (deposit or withdraw)
/// @param _yHAFees Array of the y-axis value for the fees (deposit or withdraw)
/// @param deposit Whether deposit or withdraw fees should be updated
/// @dev Evolution of the fees is linear between two values of thresholds
/// @dev These x values should be ranked in ascending order
/// @dev For deposit fees, the higher the x that is the ratio between what's to hedge and what's hedged
/// the higher y should be (the more expensive it should be for HAs to come in)
/// @dev For withdraw fees, evolution should follow an opposite logic
function setHAFees(
uint64[] memory _xHAFees,
uint64[] memory _yHAFees,
uint8 deposit
) external override onlyRole(GUARDIAN_ROLE) onlyCompatibleInputArrays(_xHAFees, _yHAFees) {
if (deposit == 1) {
xHAFeesDeposit = _xHAFees;
yHAFeesDeposit = _yHAFees;
} else {
xHAFeesWithdraw = _xHAFees;
yHAFeesWithdraw = _yHAFees;
}
emit HAFeesUpdated(_xHAFees, _yHAFees, deposit);
}
/// @notice Sets the target and limit proportions of collateral from users that can be insured by HAs
/// @param _targetHAHedge Proportion of collateral from users that HAs should hedge
/// @param _limitHAHedge Proportion of collateral from users above which HAs can see their perpetuals
/// cashed out
/// @dev `targetHAHedge` equal to `BASE_PARAMS` means that all the collateral from users should be insured by HAs
/// @dev `targetHAHedge` equal to 0 means HA should not cover (hedge) anything
function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge)
external
override
onlyRole(GUARDIAN_ROLE)
onlyCompatibleFees(_targetHAHedge)
onlyCompatibleFees(_limitHAHedge)
{
require(_targetHAHedge <= _limitHAHedge, "8");
limitHAHedge = _limitHAHedge;
targetHAHedge = _targetHAHedge;
// Updating the value in the `stableMaster` contract
_stableMaster.setTargetHAHedge(_targetHAHedge);
emit TargetAndLimitHAHedgeUpdated(_targetHAHedge, _limitHAHedge);
}
/// @notice Sets the portion of the leftover cash out amount of liquidated perpetuals that go to keepers
/// @param _keeperFeesLiquidationRatio Proportion to keepers
/// @dev This proportion should be inferior to `BASE_PARAMS`
function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio)
external
override
onlyRole(GUARDIAN_ROLE)
onlyCompatibleFees(_keeperFeesLiquidationRatio)
{
keeperFeesLiquidationRatio = _keeperFeesLiquidationRatio;
emit KeeperFeesLiquidationRatioUpdated(keeperFeesLiquidationRatio);
}
/// @notice Sets the maximum amounts going to the keepers when closing perpetuals
/// because too much was hedged by HAs or when liquidating a perpetual
/// @param _keeperFeesLiquidationCap Maximum reward going to the keeper liquidating a perpetual
/// @param _keeperFeesClosingCap Maximum reward going to the keeper forcing the closing of an ensemble
/// of perpetuals
function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap)
external
override
onlyRole(GUARDIAN_ROLE)
{
keeperFeesLiquidationCap = _keeperFeesLiquidationCap;
keeperFeesClosingCap = _keeperFeesClosingCap;
emit KeeperFeesCapUpdated(keeperFeesLiquidationCap, keeperFeesClosingCap);
}
/// @notice Sets the x-array (ie thresholds) for `FeeManager` when closing perpetuals and the y-array that is the
/// value of the proportions of the fees going to keepers closing perpetuals
/// @param _xKeeperFeesClosing Thresholds for closing fees
/// @param _yKeeperFeesClosing Value of the fees at the different threshold values specified in `xKeeperFeesClosing`
/// @dev The x thresholds correspond to values of the hedge ratio divided by two
/// @dev `xKeeperFeesClosing` and `yKeeperFeesClosing` should have the same length
function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing)
external
override
onlyRole(GUARDIAN_ROLE)
onlyCompatibleInputArrays(_xKeeperFeesClosing, _yKeeperFeesClosing)
{
xKeeperFeesClosing = _xKeeperFeesClosing;
yKeeperFeesClosing = _yKeeperFeesClosing;
emit KeeperFeesClosingUpdated(xKeeperFeesClosing, yKeeperFeesClosing);
}
// ================ Governance - `PoolManager` Functions =======================
/// @notice Changes the reference to the `FeeManager` contract
/// @param feeManager_ New `FeeManager` contract
/// @dev This allows the `PoolManager` contract to propagate changes to the `PerpetualManager`
/// @dev This is the only place where the `_feeManager` can be changed, it is as if there was
/// a `FEEMANAGER_ROLE` for which `PoolManager` was the admin
function setFeeManager(IFeeManager feeManager_) external override onlyRole(POOLMANAGER_ROLE) {
_feeManager = feeManager_;
}
// ======================= `StableMaster` Function =============================
/// @notice Changes the oracle contract used to compute collateral price with respect to the stablecoin's price
/// @param oracle_ Oracle contract
/// @dev The collateral `PoolManager` does not store a reference to an oracle, the value of the oracle
/// is hence directly set by the `StableMaster`
function setOracle(IOracle oracle_) external override {
require(msg.sender == address(_stableMaster), "1");
oracle = oracle_;
}
}
// File contracts/perpetualManager/PerpetualManagerFront.sol
pragma solidity ^0.8.7;
/// @title PerpetualManagerFront
/// @author Angle Core Team
/// @notice `PerpetualManager` is the contract handling all the Hedging Agents perpetuals
/// @dev There is one `PerpetualManager` contract per pair stablecoin/collateral in the protocol
/// @dev This file contains the functions of the `PerpetualManager` that can be directly interacted
/// with by external agents. These functions are the ones that need to be called to open, modify or close
/// perpetuals
/// @dev `PerpetualManager` naturally handles staking, the code allowing HAs to stake has been inspired from
/// https://github.com/SetProtocol/index-coop-contracts/blob/master/contracts/staking/StakingRewardsV2.sol
/// @dev Perpetuals at Angle protocol are treated as NFTs, this contract handles the logic for that
contract PerpetualManagerFront is PerpetualManager, IPerpetualManagerFront {
using SafeERC20 for IERC20;
using CountersUpgradeable for CountersUpgradeable.Counter;
// =============================== Deployer ====================================
/// @notice Initializes the `PerpetualManager` contract
/// @param poolManager_ Reference to the `PoolManager` contract handling the collateral associated to the `PerpetualManager`
/// @param rewardToken_ Reference to the `rewardtoken` that can be distributed to HAs as they have open positions
/// @dev The reward token is most likely going to be the ANGLE token
/// @dev Since this contract is upgradeable, this function is an `initialize` and not a `constructor`
/// @dev Zero checks are only performed on addresses for which no external calls are made, in this case just
/// the `rewardToken_` is checked
/// @dev After initializing this contract, all the fee parameters should be initialized by governance using
/// the setters in this contract
function initialize(IPoolManager poolManager_, IERC20 rewardToken_)
external
initializer
zeroCheck(address(rewardToken_))
{
// Initializing contracts
__Pausable_init();
__AccessControl_init();
// Creating references
poolManager = poolManager_;
_token = IERC20(poolManager_.token());
_stableMaster = IStableMaster(poolManager_.stableMaster());
rewardToken = rewardToken_;
_collatBase = 10**(IERC20Metadata(address(_token)).decimals());
// The references to the `feeManager` and to the `oracle` contracts are to be set when the contract is deployed
// Setting up Access Control for this contract
// There is no need to store the reference to the `PoolManager` address here
// Once the `POOLMANAGER_ROLE` has been granted, no new addresses can be granted or revoked
// from this role: a `PerpetualManager` contract can only have one `PoolManager` associated
_setupRole(POOLMANAGER_ROLE, address(poolManager));
// `PoolManager` is admin of all the roles. Most of the time, changes are propagated from it
_setRoleAdmin(GUARDIAN_ROLE, POOLMANAGER_ROLE);
_setRoleAdmin(POOLMANAGER_ROLE, POOLMANAGER_ROLE);
// Pausing the contract because it is not functional till the collateral has really been deployed by the
// `StableMaster`
_pause();
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
// ================================= HAs =======================================
/// @notice Lets a HA join the protocol and create a perpetual
/// @param owner Address of the future owner of the perpetual
/// @param margin Amount of collateral brought by the HA
/// @param committedAmount Amount of collateral covered by the HA
/// @param maxOracleRate Maximum oracle value that the HA wants to see stored in the perpetual
/// @param minNetMargin Minimum net margin that the HA is willing to see stored in the perpetual
/// @return perpetualID The ID of the perpetual opened by this HA
/// @dev The future owner of the perpetual cannot be the zero address
/// @dev It is possible to open a perpetual on behalf of someone else
/// @dev The `maxOracleRate` parameter serves as a protection against oracle manipulations for HAs opening perpetuals
/// @dev `minNetMargin` is a protection against too big variations in the fees for HAs
function openPerpetual(
address owner,
uint256 margin,
uint256 committedAmount,
uint256 maxOracleRate,
uint256 minNetMargin
) external override whenNotPaused zeroCheck(owner) returns (uint256 perpetualID) {
// Transaction will revert anyway if `margin` is zero
require(committedAmount > 0, "27");
// There could be a reentrancy attack as a call to an external contract is done before state variables
// updates. Yet in this case, the call involves a transfer from the `msg.sender` to the contract which
// eliminates the risk
_token.safeTransferFrom(msg.sender, address(poolManager), margin);
// Computing the oracle value
// Only the highest oracle value (between Chainlink and Uniswap) we get is stored in the perpetual
(, uint256 rateUp) = _getOraclePrice();
// Checking if the oracle rate is not too big: a too big oracle rate could mean for a HA that the price
// has become too high to make it interesting to open a perpetual
require(rateUp <= maxOracleRate, "28");
// Computing the total amount of stablecoins that this perpetual is going to hedge for the protocol
uint256 totalHedgeAmountUpdate = (committedAmount * rateUp) / _collatBase;
// Computing the net amount brought by the HAs to store in the perpetual
uint256 netMargin = _getNetMargin(margin, totalHedgeAmountUpdate, committedAmount);
require(netMargin >= minNetMargin, "29");
// Checking if the perpetual is not too leveraged, even after computing the fees
require((committedAmount * BASE_PARAMS) <= maxLeverage * netMargin, "30");
// ERC721 logic
_perpetualIDcount.increment();
perpetualID = _perpetualIDcount.current();
// In the logic of the staking contract, the `_updateReward` should be called
// before the perpetual is opened
_updateReward(perpetualID, 0);
// Updating the total amount of stablecoins hedged by HAs and creating the perpetual
totalHedgeAmount += totalHedgeAmountUpdate;
perpetualData[perpetualID] = Perpetual(rateUp, block.timestamp, netMargin, committedAmount);
// Following ERC721 logic, the function `_mint(...)` calls `_checkOnERC721Received` and could then be used as
// a reentrancy vector. Minting should then only be done at the very end after updating all variables.
_mint(owner, perpetualID);
emit PerpetualOpened(perpetualID, rateUp, netMargin, committedAmount);
}
/// @notice Lets a HA close a perpetual owned or controlled for the stablecoin/collateral pair associated
/// to this `PerpetualManager` contract
/// @param perpetualID ID of the perpetual to close
/// @param to Address which will receive the proceeds from this perpetual
/// @param minCashOutAmount Minimum net cash out amount that the HA is willing to get for closing the
/// perpetual
/// @dev The HA gets the current amount of her position depending on the entry oracle value
/// and current oracle value minus some transaction fees computed on the committed amount
/// @dev `msg.sender` should be the owner of `perpetualID` or be approved for this perpetual
/// @dev If the `PoolManager` does not have enough collateral, the perpetual owner will be converted to a SLP and
/// receive sanTokens
/// @dev The `minCashOutAmount` serves as a protection for HAs closing their perpetuals: it protects them both
/// from fees that would have become too high and from a too big decrease in oracle value
function closePerpetual(
uint256 perpetualID,
address to,
uint256 minCashOutAmount
) external override whenNotPaused onlyApprovedOrOwner(msg.sender, perpetualID) {
// Loading perpetual data and getting the oracle price
Perpetual memory perpetual = perpetualData[perpetualID];
(uint256 rateDown, ) = _getOraclePrice();
// The lowest oracle price between Chainlink and Uniswap is used to compute the perpetual's position at
// the time of closing: it is the one that is most at the advantage of the protocol
(uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 0) {
// You need to wait `lockTime` before being able to withdraw funds from the protocol as a HA
require(perpetual.entryTimestamp + lockTime <= block.timestamp, "31");
// Cashing out the perpetual internally
_closePerpetual(perpetualID, perpetual);
// Computing exit fees: they depend on how much is already hedgeded by HAs compared with what's to hedge
(uint256 netCashOutAmount, ) = _getNetCashOutAmount(
cashOutAmount,
perpetual.committedAmount,
// The perpetual has already been cashed out when calling this function, so there is no
// `committedAmount` to add to the `totalHedgeAmount` to get the `currentHedgeAmount`
_computeHedgeRatio(totalHedgeAmount)
);
require(netCashOutAmount >= minCashOutAmount, "32");
emit PerpetualClosed(perpetualID, netCashOutAmount);
_secureTransfer(to, netCashOutAmount);
}
}
/// @notice Lets a HA increase the `margin` in a perpetual she controls for this
/// stablecoin/collateral pair
/// @param perpetualID ID of the perpetual to which amount should be added to `margin`
/// @param amount Amount to add to the perpetual's `margin`
/// @dev This decreases the leverage multiple of this perpetual
/// @dev If this perpetual is to be liquidated, the HA is not going to be able to add liquidity to it
/// @dev Since this function can be used to add liquidity to a perpetual, there is no need to restrict
/// it to the owner of the perpetual
/// @dev Calling this function on a non-existing perpetual makes it revert
function addToPerpetual(uint256 perpetualID, uint256 amount) external override whenNotPaused {
// Loading perpetual data and getting the oracle price
Perpetual memory perpetual = perpetualData[perpetualID];
(uint256 rateDown, ) = _getOraclePrice();
(, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 0) {
// Overflow check
_token.safeTransferFrom(msg.sender, address(poolManager), amount);
perpetualData[perpetualID].margin += amount;
emit PerpetualUpdated(perpetualID, perpetual.margin + amount);
}
}
/// @notice Lets a HA decrease the `margin` in a perpetual she controls for this
/// stablecoin/collateral pair
/// @param perpetualID ID of the perpetual from which collateral should be removed
/// @param amount Amount to remove from the perpetual's `margin`
/// @param to Address which will receive the collateral removed from this perpetual
/// @dev This increases the leverage multiple of this perpetual
/// @dev `msg.sender` should be the owner of `perpetualID` or be approved for this perpetual
function removeFromPerpetual(
uint256 perpetualID,
uint256 amount,
address to
) external override whenNotPaused onlyApprovedOrOwner(msg.sender, perpetualID) {
// Loading perpetual data and getting the oracle price
Perpetual memory perpetual = perpetualData[perpetualID];
(uint256 rateDown, ) = _getOraclePrice();
(uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 0) {
// Checking if money can be withdrawn from the perpetual
require(
// The perpetual should not have been opened too soon
(perpetual.entryTimestamp + lockTime <= block.timestamp) &&
// The amount to withdraw should not be more important than the perpetual's `cashOutAmount` and `margin`
(amount < cashOutAmount) &&
(amount < perpetual.margin) &&
// Withdrawing collateral should not make the leverage of the perpetual too important
// Checking both on `cashOutAmount` and `perpetual.margin` (as we can have either
// `cashOutAmount >= perpetual.margin` or `cashOutAmount<perpetual.margin`)
// No checks are done on `maintenanceMargin`, as conditions on `maxLeverage` are more restrictive
perpetual.committedAmount * BASE_PARAMS <= (cashOutAmount - amount) * maxLeverage &&
perpetual.committedAmount * BASE_PARAMS <= (perpetual.margin - amount) * maxLeverage,
"33"
);
perpetualData[perpetualID].margin -= amount;
emit PerpetualUpdated(perpetualID, perpetual.margin - amount);
_secureTransfer(to, amount);
}
}
/// @notice Allows an outside caller to liquidate perpetuals if their margin ratio is
/// under the maintenance margin
/// @param perpetualIDs ID of the targeted perpetuals
/// @dev Liquidation of a perpetual will succeed if the `cashOutAmount` of the perpetual is under the maintenance margin,
/// and nothing will happen if the perpetual is still healthy
/// @dev The outside caller (namely a keeper) gets a portion of the leftover cash out amount of the perpetual
/// @dev As keepers may directly profit from this function, there may be front-running problems with miners bots,
/// we may have to put an access control logic for this function to only allow white-listed addresses to act
/// as keepers for the protocol
function liquidatePerpetuals(uint256[] memory perpetualIDs) external override whenNotPaused {
// Getting the oracle price
(uint256 rateDown, ) = _getOraclePrice();
uint256 liquidationFees;
for (uint256 i = 0; i < perpetualIDs.length; i++) {
uint256 perpetualID = perpetualIDs[i];
if (_exists(perpetualID)) {
// Loading perpetual data
Perpetual memory perpetual = perpetualData[perpetualID];
(uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 1) {
// Computing the incentive for the keeper as a function of the `cashOutAmount` of the perpetual
// This incentivizes keepers to react fast when the price starts to go below the liquidation
// margin
liquidationFees += _computeKeeperLiquidationFees(cashOutAmount);
}
}
}
emit KeeperTransferred(msg.sender, liquidationFees);
_secureTransfer(msg.sender, liquidationFees);
}
/// @notice Allows an outside caller to close perpetuals if too much of the collateral from
/// users is hedged by HAs
/// @param perpetualIDs IDs of the targeted perpetuals
/// @dev This function allows to make sure that the protocol will not have too much HAs for a long period of time
/// @dev A HA that owns a targeted perpetual will get the current value of her perpetual
/// @dev The call to the function above will revert if HAs cannot be cashed out
/// @dev As keepers may directly profit from this function, there may be front-running problems with miners bots,
/// we may have to put an access control logic for this function to only allow white-listed addresses to act
/// as keepers for the protocol
function forceClosePerpetuals(uint256[] memory perpetualIDs) external override whenNotPaused {
// Getting the oracle prices
// `rateUp` is used to compute the cost of manipulation of the covered amounts
(uint256 rateDown, uint256 rateUp) = _getOraclePrice();
// Fetching `stocksUsers` to check if perpetuals cover too much collateral
uint256 stocksUsers = _stableMaster.getStocksUsers();
uint256 targetHedgeAmount = (stocksUsers * targetHAHedge) / BASE_PARAMS;
// `totalHedgeAmount` should be greater than the limit hedge amount
require(totalHedgeAmount > (stocksUsers * limitHAHedge) / BASE_PARAMS, "34");
uint256 liquidationFees;
uint256 cashOutFees;
// Array of pairs `(owner, netCashOutAmount)`
Pairs[] memory outputPairs = new Pairs[](perpetualIDs.length);
for (uint256 i = 0; i < perpetualIDs.length; i++) {
uint256 perpetualID = perpetualIDs[i];
address owner = _owners[perpetualID];
if (owner != address(0)) {
// Loading perpetual data and getting the oracle price
Perpetual memory perpetual = perpetualData[perpetualID];
// First checking if the perpetual should not be liquidated
(uint256 cashOutAmount, uint256 liquidated) = _checkLiquidation(perpetualID, perpetual, rateDown);
if (liquidated == 1) {
// This results in the perpetual being liquidated and the keeper being paid the same amount of fees as
// what would have been paid if the perpetual had been liquidated using the `liquidatePerpetualFunction`
// Computing the incentive for the keeper as a function of the `cashOutAmount` of the perpetual
// This incentivizes keepers to react fast
liquidationFees += _computeKeeperLiquidationFees(cashOutAmount);
} else if (perpetual.entryTimestamp + lockTime <= block.timestamp) {
// It is impossible to force the closing a perpetual that was just created: in the other case, this
// function could be used to do some insider trading and to bypass the `lockTime` limit
// If too much collateral is hedged by HAs, then the perpetual can be cashed out
_closePerpetual(perpetualID, perpetual);
uint64 ratioPostCashOut;
// In this situation, `totalHedgeAmount` is the `currentHedgeAmount`
if (targetHedgeAmount > totalHedgeAmount) {
ratioPostCashOut = uint64((totalHedgeAmount * BASE_PARAMS) / targetHedgeAmount);
} else {
ratioPostCashOut = uint64(BASE_PARAMS);
}
// Computing how much the HA will get and the amount of fees paid at closing
(uint256 netCashOutAmount, uint256 fees) = _getNetCashOutAmount(
cashOutAmount,
perpetual.committedAmount,
ratioPostCashOut
);
cashOutFees += fees;
// Storing the owners of perpetuals that were forced cash out in a memory array to avoid
// reentrancy attacks
outputPairs[i] = Pairs(owner, netCashOutAmount);
}
// Checking if at this point enough perpetuals have been cashed out
if (totalHedgeAmount <= targetHedgeAmount) break;
}
}
uint64 ratio = (targetHedgeAmount == 0)
? 0
: uint64((totalHedgeAmount * BASE_PARAMS) / (2 * targetHedgeAmount));
// Computing the rewards given to the keeper calling this function
// and transferring the rewards to the keeper
// Using a cache value of `cashOutFees` to save some gas
// The value below is the amount of fees that should go to the keeper forcing the closing of perpetuals
// In the linear by part function, if `xKeeperFeesClosing` is greater than 0.5 (meaning we are not at target yet)
// then keepers should get almost no fees
cashOutFees = (cashOutFees * _piecewiseLinear(ratio, xKeeperFeesClosing, yKeeperFeesClosing)) / BASE_PARAMS;
// The amount of fees that can go to keepers is capped by a parameter set by governance
cashOutFees = cashOutFees < keeperFeesClosingCap ? cashOutFees : keeperFeesClosingCap;
// A malicious attacker could take advantage of this function to take a flash loan, burn agTokens
// to diminish the stocks users and then force close some perpetuals. We also need to check that assuming
// really small burn transaction fees (of 0.05%), an attacker could make a profit with such flash loan
// if current hedge is below the target hedge by making such flash loan.
// The formula for the cost of such flash loan is:
// `fees * (limitHAHedge - targetHAHedge) * stocksUsers / oracle`
// In order to avoid doing multiplications after divisions, and to get everything in the correct base, we do:
uint256 estimatedCost = (5 * (limitHAHedge - targetHAHedge) * stocksUsers * _collatBase) /
(rateUp * 10000 * BASE_PARAMS);
cashOutFees = cashOutFees < estimatedCost ? cashOutFees : estimatedCost;
emit PerpetualsForceClosed(perpetualIDs, outputPairs, msg.sender, cashOutFees + liquidationFees);
// Processing transfers after all calculations have been performed
for (uint256 j = 0; j < perpetualIDs.length; j++) {
if (outputPairs[j].netCashOutAmount > 0) {
_secureTransfer(outputPairs[j].owner, outputPairs[j].netCashOutAmount);
}
}
_secureTransfer(msg.sender, cashOutFees + liquidationFees);
}
// =========================== External View Function ==========================
/// @notice Returns the `cashOutAmount` of the perpetual owned by someone at a given oracle value
/// @param perpetualID ID of the perpetual
/// @param rate Oracle value
/// @return The `cashOutAmount` of the perpetual
/// @return Whether the position of the perpetual is now too small compared with its initial position and should hence
/// be liquidated
/// @dev This function is used by the Collateral Settlement contract
function getCashOutAmount(uint256 perpetualID, uint256 rate) external view override returns (uint256, uint256) {
Perpetual memory perpetual = perpetualData[perpetualID];
return _getCashOutAmount(perpetual, rate);
}
// =========================== Reward Distribution =============================
/// @notice Allows to check the amount of reward tokens earned by a perpetual
/// @param perpetualID ID of the perpetual to check
function earned(uint256 perpetualID) external view returns (uint256) {
return _earned(perpetualID, perpetualData[perpetualID].committedAmount * perpetualData[perpetualID].entryRate);
}
/// @notice Allows a perpetual owner to withdraw rewards
/// @param perpetualID ID of the perpetual which accumulated tokens
/// @dev Only an approved caller can claim the rewards for the perpetual with perpetualID
function getReward(uint256 perpetualID) external whenNotPaused onlyApprovedOrOwner(msg.sender, perpetualID) {
_getReward(perpetualID, perpetualData[perpetualID].committedAmount * perpetualData[perpetualID].entryRate);
}
// =============================== ERC721 logic ================================
/// @notice Gets the name of the NFT collection implemented by this contract
function name() external pure override returns (string memory) {
return "AnglePerp";
}
/// @notice Gets the symbol of the NFT collection implemented by this contract
function symbol() external pure override returns (string memory) {
return "AnglePerp";
}
/// @notice Gets the URI containing metadata
/// @param perpetualID ID of the perpetual
function tokenURI(uint256 perpetualID) external view override returns (string memory) {
require(_exists(perpetualID), "2");
// There is no perpetual with `perpetualID` equal to 0, so the following variable is
// always greater than zero
uint256 temp = perpetualID;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (perpetualID != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(perpetualID % 10)));
perpetualID /= 10;
}
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, string(buffer))) : "";
}
/// @notice Gets the balance of an owner
/// @param owner Address of the owner
/// @dev Balance here represents the number of perpetuals owned by a HA
function balanceOf(address owner) external view override returns (uint256) {
require(owner != address(0), "0");
return _balances[owner];
}
/// @notice Gets the owner of the perpetual with ID perpetualID
/// @param perpetualID ID of the perpetual
function ownerOf(uint256 perpetualID) external view override returns (address) {
return _ownerOf(perpetualID);
}
/// @notice Approves to an address specified by `to` a perpetual specified by `perpetualID`
/// @param to Address to approve the perpetual to
/// @param perpetualID ID of the perpetual
/// @dev The approved address will have the right to transfer the perpetual, to cash it out
/// on behalf of the owner, to add or remove collateral in it and to choose the destination
/// address that will be able to receive the proceeds of the perpetual
function approve(address to, uint256 perpetualID) external override {
address owner = _ownerOf(perpetualID);
require(to != owner, "35");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "21");
_approve(to, perpetualID);
}
/// @notice Gets the approved address by a perpetual owner
/// @param perpetualID ID of the concerned perpetual
function getApproved(uint256 perpetualID) external view override returns (address) {
require(_exists(perpetualID), "2");
return _getApproved(perpetualID);
}
/// @notice Sets approval on all perpetuals owned by the owner to an operator
/// @param operator Address to approve (or block) on all perpetuals
/// @param approved Whether the sender wants to approve or block the operator
function setApprovalForAll(address operator, bool approved) external override {
require(operator != msg.sender, "36");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/// @notice Gets if the operator address is approved on all perpetuals by the owner
/// @param owner Owner of perpetuals
/// @param operator Address to check if approved
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/// @notice Gets if the sender address is approved for the perpetualId
/// @param perpetualID ID of the perpetual
function isApprovedOrOwner(address spender, uint256 perpetualID) external view override returns (bool) {
return _isApprovedOrOwner(spender, perpetualID);
}
/// @notice Transfers the `perpetualID` from an address to another
/// @param from Source address
/// @param to Destination a address
/// @param perpetualID ID of the perpetual to transfer
function transferFrom(
address from,
address to,
uint256 perpetualID
) external override onlyApprovedOrOwner(msg.sender, perpetualID) {
_transfer(from, to, perpetualID);
}
/// @notice Safely transfers the `perpetualID` from an address to another without data in it
/// @param from Source address
/// @param to Destination a address
/// @param perpetualID ID of the perpetual to transfer
function safeTransferFrom(
address from,
address to,
uint256 perpetualID
) external override {
safeTransferFrom(from, to, perpetualID, "");
}
/// @notice Safely transfers the `perpetualID` from an address to another with data in the transfer
/// @param from Source address
/// @param to Destination a address
/// @param perpetualID ID of the perpetual to transfer
function safeTransferFrom(
address from,
address to,
uint256 perpetualID,
bytes memory _data
) public override onlyApprovedOrOwner(msg.sender, perpetualID) {
_safeTransfer(from, to, perpetualID, _data);
}
// =============================== ERC165 logic ================================
/// @notice Queries if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function uses less than 30,000 gas.
/// Required by the ERC721 standard, so used to check that the IERC721 is implemented.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceId) external pure override(IERC165) returns (bool) {
return
interfaceId == type(IPerpetualManagerFront).interfaceId ||
interfaceId == type(IPerpetualManagerFunctions).interfaceId ||
interfaceId == type(IStakingRewards).interfaceId ||
interfaceId == type(IStakingRewardsFunctions).interfaceId ||
interfaceId == type(IAccessControl).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC165).interfaceId;
}
} | Returns the `cashOutAmount` of the perpetual owned by someone at a given oracle value perpetualID ID of the perpetual rate Oracle value return The `cashOutAmount` of the perpetual return Whether the position of the perpetual is now too small compared with its initial position and should hence be liquidated This function is used by the Collateral Settlement contract | function getCashOutAmount(uint256 perpetualID, uint256 rate) external view override returns (uint256, uint256) {
Perpetual memory perpetual = perpetualData[perpetualID];
return _getCashOutAmount(perpetual, rate);
}
| 7,761,012 |
./full_match/1/0x06EF85C7DCA052aad296935D44Cef572367E3dE7/sources/contracts/PrimeApeAthletes.sol | will set default royalty info./ | function setDefaultRoyalty(address receiver, uint96 feeNumerator)
public
onlyOwner
{
_setDefaultRoyalty(receiver, feeNumerator);
}
| 16,466,271 |
pragma solidity 0.5.17;
import "./IRewardTransferLogic.sol";
import "./LockedSOVRewardTransferLogicStorage.sol";
import "../locked/ILockedSOV.sol";
import "../openzeppelin/ERC20.sol";
import "../openzeppelin/SafeERC20.sol";
contract LockedSOVRewardTransferLogic is IRewardTransferLogic, LockedSOVRewardTransferLogicStorage {
using SafeERC20 for IERC20;
event LockedSOVChanged(address _newAddress);
event UnlockImmediatelyPercentChanged(uint256 _newAmount);
/**
* @param _lockedSOV The contract instance address of the lockedSOV vault.
* SOV rewards are not paid directly to liquidity providers. Instead they
* are deposited into a lockedSOV vault contract.
* @param _unlockedImmediatelyPercent The % which determines how much will be unlocked immediately.
*/
function initialize(address _lockedSOV, uint256 _unlockedImmediatelyPercent) public onlyAuthorized {
changeLockedSOV(_lockedSOV);
changeUnlockedImmediatelyPercent(_unlockedImmediatelyPercent);
}
/**
* @param _newLockedSOV The contract instance address of the lockedSOV vault.
*/
function changeLockedSOV(address _newLockedSOV) public onlyAuthorized {
require(_newLockedSOV != address(0), "Invalid address");
lockedSOV = ILockedSOV(_newLockedSOV);
emit LockedSOVChanged(_newLockedSOV);
}
/**
* @param _newUnlockedImmediatelyPercent The new unlocked immediately percent.
*/
function changeUnlockedImmediatelyPercent(uint256 _newUnlockedImmediatelyPercent) public onlyAuthorized {
require(_newUnlockedImmediatelyPercent < 10000, "Unlocked immediately percent has to be less than 10000.");
unlockedImmediatelyPercent = _newUnlockedImmediatelyPercent;
emit UnlockImmediatelyPercentChanged(_newUnlockedImmediatelyPercent);
}
function getRewardTokenAddress() external view returns (address) {
return lockedSOV.SOV();
}
function senderToAuthorize() external view returns (address) {
return address(this);
}
function transferReward(
address _to,
uint256 _value,
bool _isWithdrawal
) external {
IERC20 token = IERC20(lockedSOV.SOV());
require(token.transferFrom(msg.sender, address(this), _value), "Transfer failed");
require(token.approve(address(lockedSOV), _value), "Approve failed");
lockedSOV.deposit(_to, _value, unlockedImmediatelyPercent);
if (!_isWithdrawal) {
lockedSOV.withdrawAndStakeTokensFrom(_to);
}
}
}
| _lockedSOV The contract instance address of the lockedSOV vault. SOV rewards are not paid directly to liquidity providers. Instead they are deposited into a lockedSOV vault contract. _unlockedImmediatelyPercent The % which determines how much will be unlocked immediately./ | function initialize(address _lockedSOV, uint256 _unlockedImmediatelyPercent) public onlyAuthorized {
changeLockedSOV(_lockedSOV);
changeUnlockedImmediatelyPercent(_unlockedImmediatelyPercent);
}
| 939,649 |
/*
* This file was generated by MyWish Platform (https://mywish.io/)
* The complete code could be found at https://github.com/MyWishPlatform/
* Copyright (C) 2018 MyWish
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.20;
/**
* @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);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @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));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// 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 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
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 () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
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 view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
function RefundVault(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
}
contract FreezableToken is StandardToken {
// freezing chains
mapping (bytes32 => uint64) internal chains;
// freezing amounts for each chain
mapping (bytes32 => uint) internal freezings;
// total freezing balance per address
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
/**
* @dev Gets the balance of the specified address include freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
/**
* @dev Gets the balance of the specified address without freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
/**
* @dev gets freezing count
* @param _addr Address of freeze tokens owner.
*/
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count ++;
release = chains[toKey(_addr, release)];
}
}
/**
* @dev gets freezing end date and freezing balance for the freezing portion specified by index.
* @param _addr Address of freeze tokens owner.
* @param _index Freezing portion index. It ordered by release date descending.
*/
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i ++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
/**
* @dev freeze your tokens to the specified address.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to freeze.
* @param _until Release date, must be in future.
*/
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
Transfer(msg.sender, _to, _amount);
Freezed(_to, _until, _amount);
}
/**
* @dev release first available freezing tokens.
*/
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
}
else {
chains[headKey] = next;
delete chains[currentKey];
}
Released(msg.sender, amount);
}
/**
* @dev release all available for release freezing tokens. Gas usage is not deterministic!
* @return how many tokens was released
*/
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
// WISH masc to increase entropy
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
/**
* @title Contract that will work with ERC223 tokens.
*/
contract ERC223Receiver {
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract ERC223Basic is ERC20Basic {
function transfer(address to, uint value, bytes data) public returns (bool);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
contract SuccessfulERC223Receiver is ERC223Receiver {
event Invoked(address from, uint value, bytes data);
function tokenFallback(address _from, uint _value, bytes _data) public {
Invoked(_from, _value, _data);
}
}
contract FailingERC223Receiver is ERC223Receiver {
function tokenFallback(address, uint, bytes) public {
revert();
}
}
contract ERC223ReceiverWithoutTokenFallback {
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0);
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);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
/**
* @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();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
/**
* @dev Mint the specified amount of token to the specified address and freeze it until the specified date.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to mint and freeze.
* @param _until Release date, must be in future.
* @return A boolean that indicates if the operation was successful.
*/
function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
Mint(_to, _amount);
Freezed(_to, _until, _amount);
Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint constant TOKEN_DECIMALS = 2;
uint8 constant TOKEN_DECIMALS_UINT8 = 2;
uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string constant TOKEN_NAME = "marketLIST";
string constant TOKEN_SYMBOL = "LIST";
bool constant PAUSED = true;
address constant TARGET_USER = 0x17238a53f266f058C4A1CbC616f4308E4226FEBF;
uint constant START_TIME = 1524481200;
bool constant CONTINUE_MINTING = false;
}
/**
* @title Reference implementation of the ERC223 standard token.
*/
contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver {
using SafeMath for uint;
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool) {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly.
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength > 0) {
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
return transfer(_to, _value, empty);
}
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() pure public returns (string _name) {
return TOKEN_NAME;
}
function symbol() pure public returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() pure public returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
}
/**
* @title CappedCrowdsale
* @dev Extension of Crowdsale with a max amount of funds raised
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
function CappedCrowdsale(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal view returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= cap;
return super.validPurchase() && withinCap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
bool capReached = weiRaised >= cap;
return super.hasEnded() || capReached;
}
}
/**
* @title RefundableCrowdsale
* @dev Extension of Crowdsale contract that adds a funding goal, and
* the possibility of users getting a refund if goal is not met.
* Uses a RefundVault as the crowdsale's vault.
*/
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
// minimum amount of funds to be raised in weis
uint256 public goal;
// refund vault used to hold funds while crowdsale is running
RefundVault public vault;
function RefundableCrowdsale(uint256 _goal) public {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
// We're overriding the fund forwarding from Crowdsale.
// In addition to sending the funds, we want to call
// the RefundVault deposit function
function forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
// if crowdsale is unsuccessful, investors can claim refunds here
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
// vault finalization task, called when owner calls finalize()
function finalization() internal {
if (goalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
super.finalization();
}
function goalReached() public view returns (bool) {
return weiRaised >= goal;
}
}
contract MainCrowdsale is Consts, FinalizableCrowdsale {
function hasStarted() public constant returns (bool) {
return now >= startTime;
}
function finalization() internal {
super.finalization();
if (PAUSED) {
MainToken(token).unpause();
}
if (!CONTINUE_MINTING) {
token.finishMinting();
}
token.transferOwnership(TARGET_USER);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate).div(1 ether);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
}
contract Checkable {
address private serviceAccount;
/**
* Flag means that contract accident already occurs.
*/
bool private triggered = false;
/**
* Occurs when accident happened.
*/
event Triggered(uint balance);
/**
* Occurs when check finished.
*/
event Checked(bool isAccident);
function Checkable() public {
serviceAccount = msg.sender;
}
/**
* @dev Replace service account with new one.
* @param _account Valid service account address.
*/
function changeServiceAccount(address _account) onlyService public {
assert(_account != 0);
serviceAccount = _account;
}
/**
* @dev Is caller (sender) service account.
*/
function isServiceAccount() view public returns (bool) {
return msg.sender == serviceAccount;
}
/**
* Public check method.
*/
function check() onlyService notTriggered payable public {
if (internalCheck()) {
Triggered(this.balance);
triggered = true;
internalAction();
}
}
/**
* @dev Do inner check.
* @return bool true of accident triggered, false otherwise.
*/
function internalCheck() internal returns (bool);
/**
* @dev Do inner action if check was success.
*/
function internalAction() internal;
modifier onlyService {
require(msg.sender == serviceAccount);
_;
}
modifier notTriggered() {
require(!triggered);
_;
}
}
contract BonusableCrowdsale is Consts, Crowdsale {
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 bonusRate = getBonusRate(weiAmount);
uint256 tokens = weiAmount.mul(bonusRate).div(1 ether);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function getBonusRate(uint256 weiAmount) internal view returns (uint256) {
uint256 bonusRate = rate;
// apply bonus for time & weiRaised
uint[3] memory weiRaisedStartsBoundaries = [uint(0),uint(0),uint(0)];
uint[3] memory weiRaisedEndsBoundaries = [uint(67000000000000000000000),uint(67000000000000000000000),uint(67000000000000000000000)];
uint64[3] memory timeStartsBoundaries = [uint64(1524481200),uint64(1525086000),uint64(1525690800)];
uint64[3] memory timeEndsBoundaries = [uint64(1525086000),uint64(1525690800),uint64(1526295600)];
uint[3] memory weiRaisedAndTimeRates = [uint(100),uint(70),uint(50)];
for (uint i = 0; i < 3; i++) {
bool weiRaisedInBound = (weiRaisedStartsBoundaries[i] <= weiRaised) && (weiRaised < weiRaisedEndsBoundaries[i]);
bool timeInBound = (timeStartsBoundaries[i] <= now) && (now < timeEndsBoundaries[i]);
if (weiRaisedInBound && timeInBound) {
bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000;
}
}
return bonusRate;
}
}
contract TemplateCrowdsale is Consts, MainCrowdsale
, BonusableCrowdsale
, CappedCrowdsale
, Checkable
{
event Initialized();
bool public initialized = false;
function TemplateCrowdsale(MintableToken _token) public
Crowdsale(START_TIME > now ? START_TIME : now, 1529751600, 10000 * TOKEN_DECIMAL_MULTIPLIER, 0x048B8E1e604AE9DE680dB49ed2EC0D57f45090d6)
CappedCrowdsale(67000000000000000000000)
{
token = _token;
}
function init() public onlyOwner {
require(!initialized);
initialized = true;
if (PAUSED) {
MainToken(token).pause();
}
address[1] memory addresses = [address(0x17238a53f266f058c4a1cbc616f4308e4226febf)];
uint[1] memory amounts = [uint(33000000000)];
uint64[1] memory freezes = [uint64(1529751661)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
MainToken(token).mint(addresses[i], amounts[i]);
} else {
MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
transferOwnership(TARGET_USER);
Initialized();
}
/**
* @dev override token creation to set token address in constructor.
*/
function createTokenContract() internal returns (MintableToken) {
return MintableToken(0);
}
/**
* @dev Do inner check.
* @return bool true of accident triggered, false otherwise.
*/
function internalCheck() internal returns (bool) {
bool result = !isFinalized && hasEnded();
Checked(result);
return result;
}
/**
* @dev Do inner action if check was success.
*/
function internalAction() internal {
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev override purchase validation to add extra value logic.
* @return true if sended more than minimal value
*/
function validPurchase() internal view returns (bool) {
bool minValue = msg.value >= 100000000000000000;
bool maxValue = msg.value <= 1000000000000000000000;
return
minValue &&
maxValue &&
super.validPurchase();
}
/**
* @dev override hasEnded to add minimal value logic
* @return true if remained to achieve less than minimal
*/
function hasEnded() public view returns (bool) {
bool remainValue = cap.sub(weiRaised) < 100000000000000000;
return super.hasEnded() || remainValue;
}
} | Do inner action if check was success./ | function internalAction() internal {
finalization();
Finalized();
isFinalized = true;
}
| 104,879 |
// SPDX-License-Identifier: CC0
pragma solidity ^0.6.9;
pragma experimental ABIEncoderV2;
import "./IOrgRegistry.sol";
import "./Registrar.sol";
import "../../../lib/contracts/ERC165Compatible.sol";
import "@openzeppelin/contracts/access/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 {
struct Org {
address orgAddress;
bytes32 name;
bytes messagingEndpoint;
bytes whisperKey;
bytes zkpPublicKey;
bytes metadata;
}
struct OrgInterfaces {
bytes32 groupName;
address tokenAddress;
address shieldAddress;
address verifierAddress;
}
mapping (address => Org) orgMap;
mapping (uint => OrgInterfaces) orgInterfaceMap;
uint orgInterfaceCount;
Org[] public orgs;
mapping(address => address) managerMap;
event RegisterOrg(
bytes32 _name,
address _address,
bytes _messagingEndpoint,
bytes _whisperKey,
bytes _zkpPublicKey,
bytes _metadata
);
event UpdateOrg(
bytes32 _name,
address _address,
bytes _messagingEndpoint,
bytes _whisperKey,
bytes _zkpPublicKey,
bytes _metadata
);
/// @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 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 override onlyOwner returns (bool) {
/// 0x54ebc817 is equivalent to the bytes4 of the function selectors in IOrgRegistry
_registerInterface(this.registerOrg.selector ^
this.registerInterfaces.selector ^
this.getOrgCount.selector ^
this.getInterfaceAddresses.selector);
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.getOrgCount.selector ^
this.getInterfaceAddresses.selector;
}
/// @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 _newManager) external onlyOwner {
assignManagement(_newManager);
}
/// @notice Function to register an organization
/// @param _address ethereum address of the registered organization
/// @param _name name of the registered organization
/// @param _messagingEndpoint public messaging endpoint
/// @param _whisperKey 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,
bytes calldata _messagingEndpoint,
bytes calldata _whisperKey,
bytes calldata _zkpPublicKey,
bytes calldata _metadata
) external onlyOwner override returns (bool) {
Org memory org = Org(_address, _name, _messagingEndpoint, _whisperKey, _zkpPublicKey, _metadata);
orgMap[_address] = org;
orgs.push(org);
emit RegisterOrg(
_name,
_address,
_messagingEndpoint,
_whisperKey,
_zkpPublicKey,
_metadata
);
return true;
}
/// @notice Function to update an organization
/// @param _address require the ethereum address of the registered organization to update the org
/// @param _name name of the registered organization
/// @param _messagingEndpoint public messaging endpoint
/// @param _whisperKey public key required for message communication
/// @param _zkpPublicKey public key required for commitments & to verify EdDSA signatures with
/// @dev Function to update an organization
/// @return `true` upon successful registration of the organization
function updateOrg(
address _address,
bytes32 _name,
bytes calldata _messagingEndpoint,
bytes calldata _whisperKey,
bytes calldata _zkpPublicKey,
bytes calldata _metadata
) external override returns (bool) {
require(msg.sender == org[_address].address, "Must update Org from registered org address");
orgMap[_address].name = _name;
orgMap[_address].messagingEndpoint = _messagingEndpoint;
orgMap[_address].whisperKey = _whisperKey;
orgMap[_address].zkpPublicKey = _zkpPublicKey;
orgMap[_address].metadata = _metadata;
emit UpdateOrg(
_name,
_address,
_messagingEndpoint,
_whisperKey,
_zkpPublicKey,
_metadata
);
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 onlyOwner 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 override view returns (uint) {
return orgs.length;
}
/// @notice Function to get a single organization's details
function getOrg(address _address) external override view returns (
address,
bytes32,
bytes memory,
bytes memory,
bytes memory,
bytes memory
) {
return (
orgMap[_address].orgAddress,
orgMap[_address].name,
orgMap[_address].messagingEndpoint,
orgMap[_address].whisperKey,
orgMap[_address].zkpPublicKey,
orgMap[_address].metadata
);
}
/// @notice Function to get 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
);
}
}
| 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.getOrgCount.selector ^
this.getInterfaceAddresses.selector;
}
| 5,456,416 |
./full_match/44787/0xABf8b0501Ca1C41CfD3a5B5FA1512e3E7492e07E/sources/contracts/Payroll.sol | Perform the refound of the leftover ETH./ Celo Native currency is an ERC20 | function refundETH() internal {
if (block.chainid == 42220 || block.chainid == 44787) return;
uint256 leftOver = address(this).balance;
if (leftOver > 1) {
require(success, "Payroll: ETH leftOver transfer failed");
}
}
| 13,281,400 |
// SPDX-License-Identifier: MIT
// GO TO LINE 1904 TO SEE WHERE THE cybercar CONTRACT STARTS
// File: @openzeppelin/contracts/utils/Context.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 Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <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/IERC721Metadata.sol
pragma solidity >=0.6.2 <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/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface 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/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////(((((((((((((((((((((((((((//////////////////////
//////////////////////////////@@, @ ,@ @@%////////////////////
///////////////////////////%@@ @ ,@ /@@//////////////////
/////////////////////////@@/ @ @ ,@ @@#//.////////////
///////////,,///@@@&&&&&&&&&&@&&&&&&&&&&&@&&&&&&&&&&&&&@&&&&&&&&@@//.*////////((
/////////,//*,,@&&&&&&&&&&&&&@&&&&&&&&&&&@&&&&&&&&&&&&&@&&&&&&&&@@,,/,,/////////
////////,/,,/@@&&&&@@@@@&&&&&@&&&&&&&&&&&@&&&&&&&&&&&&&@@@@@&&&&&&&@////////((//
//////////@&&&&&@&#%%%%%#@&&&@&&&&&&&&&&&@&&&&&&&&&&@%#%%%%%#@&&&&&@////////////
///////////&@&&@%%&( ,(&#@@&&&&&&&&&&&&&@&&&&&&&&&@#&&( /#&#@&&&&@////////////
//////////////&&###&((%&##&&&&&&&&&&&&&&&&&&&&&&&&&&##%&((&%##&&(///////////////
///////////////////#####///////////////////////////////####(////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
pragma solidity ^0.7.0;
pragma abicoder v2;
contract CyberCar is ERC721, Ownable {
using SafeMath for uint256;
string public cybercar_PROVENANCE = ""; // IPFS URL WILL BE ADDED WHEN cybercarS ARE ALL SOLD OUT
string public LICENSE_TEXT = ""; // IT IS WHAT IT SAYS
bool licenseLocked = false; // Not able to modify after TRUE
uint256 public constant cybercarPrice = 30000000000000000; // 0.03 ETH
uint public constant maxcybercarPurchase = 20;
uint256 public constant MAX_cybercarS = 10001;
bool public saleIsActive = false;
mapping(uint => string) public cybercarNames;
// Reserve 300 cybercars for team - Giveaways/Prizes etc
uint public cybercarReserve = 300;
event cybercarNameChange(address _by, uint _tokenId, string _name);
event licenseisLocked(string _licenseText);
constructor() ERC721("CyberCar.", "CC") { }
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function reservecybercar(address _to, uint256 _reserveAmount) public onlyOwner {
uint supply = totalSupply();
require(_reserveAmount > 0 && _reserveAmount <= cybercarReserve, "Not enough reserve left for team");
for (uint i = 0; i < _reserveAmount; i++) {
_safeMint(_to, supply + i);
}
cybercarReserve = cybercarReserve.sub(_reserveAmount);
}
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
cybercar_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
// Returns the license for tokens
function tokenLicense(uint _id) public view returns(string memory) {
require(_id < totalSupply(), "CHOOSE A cybercar WITHIN RANGE");
return LICENSE_TEXT;
}
// Locks the license to prevent further changes
function lockLicense() public onlyOwner {
licenseLocked = true;
emit licenseisLocked(LICENSE_TEXT);
}
// Change the license
function changeLicense(string memory _license) public onlyOwner {
require(licenseLocked == false, "License already locked");
LICENSE_TEXT = _license;
}
function mint(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint cybercar");
require(numberOfTokens > 0 && numberOfTokens <= maxcybercarPurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_cybercarS, "Purchase would exceed max supply of cybercars");
require(msg.value >= cybercarPrice.mul(numberOfTokens), "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_cybercarS) {
_safeMint(msg.sender, mintIndex);
}
}
}
function changecybercarName(uint _tokenId, string memory _name) public {
require(ownerOf(_tokenId) == msg.sender, "Hey, your wallet doesn't own this cybercar!");
require(sha256(bytes(_name)) != sha256(bytes(cybercarNames[_tokenId])), "New name is same as the current one");
cybercarNames[_tokenId] = _name;
emit cybercarNameChange(msg.sender, _tokenId, _name);
}
function viewcybercarName(uint _tokenId) public view returns( string memory ){
require( _tokenId < totalSupply(), "Choose a cybercar within range" );
return cybercarNames[_tokenId];
}
// GET ALL cybercarS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH
function cybercarNamesOfOwner(address _owner) external view returns(string[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new string[](0);
} else {
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = cybercarNames[ tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
}
} | Returns the license for tokens | function tokenLicense(uint _id) public view returns(string memory) {
require(_id < totalSupply(), "CHOOSE A cybercar WITHIN RANGE");
return LICENSE_TEXT;
}
| 14,501,739 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// OpenZeppelin Contracts v4.3.2 (token/ERC20/ERC20.sol)
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "./IPancake.sol";
import "./ITokenTimelock.sol";
import "./TimeLock.sol";
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract to the not~ 0 address.
* Since we use proxies this constructor is never called, and we can use this lock to prevent someone taking over the base contract and causing confusion
* (addresses etc) since this being set effectively disables the base contract
*/
constructor() {
_transferOwnership(address(~uint160(0)));
//_transferOwnership(address(uint160(0)));
}
/**
* @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(0x000000000000000000000000000000000000dEaD));
}
/**
* @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);
}
function initOwnership(address newOwner) internal virtual {
require(_owner == address(0), "Ownable: owner already set");
_owner = newOwner;
emit OwnershipTransferred(address(0), newOwner);
}
}
contract TipsyCoin is IERC20, IERC20Metadata, Ownable, Initializable {
using Address for address;
//--Public View Vars
address public constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD;
uint256 public maxTxAmount;
uint256 public _rTotal = 1e18;
uint256 public buybackFundAmount = 400;
uint256 public marketingCommunityAmount = 200;
uint256 public reflexiveAmount = 400;
mapping(address => bool) public whiteList;
mapping(address => bool) public excludedFromFee;
address public pancakeSwapRouter02;
address public pancakePair;
//launchTime will be a short random delay after liquidity is added to PCS
//to discourage sniper bots from reading mempool and buying the second the addliquidity event is added to txpool
uint public launchTime;
uint256 public maxSupply;
address public cexFund;
address public charityFund;
address public teamVestingFund;
address public futureFund;
address public communityEngagementFund;
address public buyBackFund;
address public marketingFund;
address public lpLocker;
//--Restricted View Vars
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
IPancakeRouter02 internal pancakeV2Router;
uint256 internal _feeTotal;
address[] internal _tokenWETHPath;
string private _name;
string private _symbol;
//--Patch Vars
address public taxCollector;
//--Events
event SellFeeCollected(uint256 indexed tokensSwapped, uint256 indexed ethReceived);
event FeesChanged(uint indexed buyBack, uint indexed marketing, uint indexed reflexive);
event ExcludedFromFee(address indexed excludedAddress);
event IncludedInFee(address indexed includedAddress);
event IncludedInContractWhitelist(address indexed includedWhiteListedContract);
event Burned(uint indexed oldSupply, uint indexed amount, uint indexed newSupply);
event Reflex(uint indexed oldRFactor, uint indexed amount, uint indexed newRFactor);
//event ExcludedFromContractWhitelist(address indexed excludedWhiteListedContract); -> removed the function associated with this event for safety
//--Modifiers
/**
* @dev
* Provides some deterance to bots to prevent them from interacting with tipsy
* Obviously we are aware that isContract() returns false during construction, so maxTxAmount, tax on transferFrom, and launchTime params also used as further deterance
*/
modifier noBots(address recipient) {
require(!recipient.isContract() || whiteList[recipient], "tipsyCoin: Bots and Contracts b&");
_;
}
//--View Functions
/**
* @dev
* Gets the byte code for the timelock contract. Returns bytes
*/
function getByteCodeTimelock() public pure returns (bytes memory) {
bytes memory bytecode = type(TokenTimelock).creationCode;
return bytecode;
}
/**
* @dev
* tiny function to make checking a bunch of addresses arne't the 0 addy in the initializer
*/
function addyChk(address _test) internal pure returns (bool)
{
return uint160(_test) != 0;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _realToReflex(_allowances[owner][spender]);
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns number of decimals, 18 is standard
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-balanceOf}.
* Return value in reflect space
*/
function balanceOf(address account) public view returns (uint256) {
//return _balances[account];
return _rBalanceOf(account);
}
/**
* @dev See {IERC20-totalSupply}
* Returns in reflex space
*/
function totalSupply() public view returns (uint256) {
return _realToReflex(_totalSupply);
}
/**
* @dev
* gets a new rTotal based on amount of tokens to be removed from supply
*/
function getNewRate(uint _reflectAmount) public view returns (uint _adjusted)
{
return totalSupply() * _rTotal / (totalSupply() - _reflectAmount);
//return rTotalSupply() * 1e18 / (rTotalSupply() - _reflectAmount);
}
/**
* @dev
* internal function to calculate reflect space balanceOf(account)
*/
function _rBalanceOf(address account) internal view returns (uint256)
{
return _balances[account] * _rTotal / 1e18;
}
/**
* @dev
* Multiplies real space token amount by the reflex factor (rTotal) to get reflex space tokens
*/
function _realToReflex(uint _realSpaceTokens) public view returns (uint256 _reflexSpaceTokens)
{
return _realSpaceTokens * _rTotal / 1e18;
}
/**
* @dev
* Divides reflex space token amount by the reflex factor (rTotal) to get real space tokens
*/
function _reflexToReal(uint _reflexSpaceTokens) public view returns (uint256 _realSpaceTokens)
{
return _reflexSpaceTokens * 1e18 / _rTotal;
}
//--Mutative Functions
/**
* @dev
* Deploys the current byte code. Returns address of newly deployed contract
*/
function deploy(bytes memory _code) internal returns (address addr)
{
assembly {
addr:= create(0,add(_code,0x20), mload(_code))
}
require(addr != address(0), "tipsy: deploy failed");
return addr;
}
constructor() payable {
}
function addLiquidity(uint256 _launchTime) payable public
{
//This is the "go time" function. Project can be deployed before this, and then this is called to add the LP and go live
//Launch time papam is used to prevent trades happening before this time. Used to prevent sniperbots scanning txpool and buying the second this function is called
require(msg.sender == address(0x75bA26e94BC5261cABeC4B50208DF9e21b21245a), "Not Deiparous!");
require(msg.value > 200 ether, "Add more than 200 BNB ($100,000), scrub!");
require(_launchTime > block.timestamp + 100, "_launchTime too soon!");
pancakePair = IPancakeFactory(pancakeV2Router.factory()).createPair(address(this), pancakeV2Router.WETH());
require(_lockLiquidity(), "tipsy: liquidity lock failed");
_approve(address(this), pancakeSwapRouter02, 50e9 * 10 ** decimals());
whiteList[pancakePair] = true;
pancakeV2Router.addLiquidityETH{value:address(this).balance}(
address(this), 50e9 * 10 ** decimals(), 1, 1, lpLocker, block.timestamp);
launchTime = _launchTime;
}
function _lockLiquidity() private returns (bool)
{
//Create timelock for 5 years
ITokenTimelock(lpLocker).initialize(pancakePair, address(this), block.timestamp + 1825 days);
return true;
}
function initialize(address owner_, address _pancakeSwapRouter02, address _cexFund, address _charityFund, address _marketingFund, address _communityEnagementFund, address _futureFund, address _teamVestingFund, address _buyBackFund, address _taxCollector) public initializer
{
initOwnership(owner_);
(lpLocker) = deploy(getByteCodeTimelock());
require(addyChk(_cexFund) && addyChk(_charityFund) && addyChk(_marketingFund) && addyChk(_communityEnagementFund) && addyChk(_futureFund) && addyChk(_teamVestingFund) && addyChk(_buyBackFund), "tipsy: initialize address must be set");
buyBackFund = _buyBackFund;
cexFund = _cexFund; //7%
charityFund = _charityFund; //3%
marketingFund = _marketingFund; //19.7%
communityEngagementFund = _communityEnagementFund; //4.8%
futureFund = _futureFund; //5.5%
teamVestingFund = _teamVestingFund; //10%
buybackFundAmount = 400; //4% of sell
marketingCommunityAmount = 200; //2% of sell
reflexiveAmount = 400; //4% of sell
_feeTotal = buybackFundAmount + marketingCommunityAmount + reflexiveAmount; //10% tax total
_name = "TipsyCoin";
_symbol = "$tipsy";
_mint(marketingFund, 19.7 * 1e9 * 10 ** decimals()); // 19.7%
_mint(teamVestingFund, 10 * 1e9 * 10 ** decimals()); // 10%
_mint(cexFund, 7 * 1e9 * 10 ** decimals()); //7%
_mint(charityFund, 3 * 1e9 * 10 ** decimals()); //3%
_mint(address(this), 50 * 1e9 * 10 ** decimals()); //Tokens to be added to LP. 50%
_mint(communityEngagementFund, 4.8 * 1e9 * 10 ** decimals()); //4.8%
_mint(futureFund, 5.5 * 1e9 * 10 ** decimals()); //5.5%
maxSupply = 100e9 * 10 ** decimals(); //100 billion total
require(maxSupply == _totalSupply, "tipsy: not all supply minted");
maxTxAmount = _totalSupply / 200; //0.5% of initial max supply, doesn't decrease as tokens are burned or reflected (to keep number simple -> 500 Mill)
_rTotal = 1e18; // reflection ratio starts at 1.0
pancakeSwapRouter02 = _pancakeSwapRouter02;
pancakeV2Router = IPancakeRouter02(pancakeSwapRouter02);
taxCollector = _taxCollector;
whiteList[taxCollector] = excludedFromFee[taxCollector] = true;
whiteList[pancakeSwapRouter02] = true;
excludedFromFee[pancakeSwapRouter02] = false;
whiteList[address(this)] = excludedFromFee[address(this)] = true;
whiteList[owner()] = excludedFromFee[owner()] = true;
whiteList[cexFund] = excludedFromFee[cexFund] = true;
whiteList[charityFund] = excludedFromFee[charityFund] = true;
whiteList[teamVestingFund] = excludedFromFee[teamVestingFund] = true;
whiteList[futureFund] = excludedFromFee[futureFund] = true;
whiteList[communityEngagementFund] = excludedFromFee[communityEngagementFund] = true;
whiteList[buyBackFund] = excludedFromFee[buyBackFund] = true;
whiteList[marketingFund] = excludedFromFee[marketingFund] = true;
_tokenWETHPath = new address[](2);
_tokenWETHPath[0] = address(this);
_tokenWETHPath[1] = pancakeV2Router.WETH();
}
/**
* @dev
* Adjusts the fees between buyback, marketing, and reflexive rewards
* Has a check to ensure the fees aren't increased beyond the initial 10% (in response to certik audit of safemoon)
*/
function adjustFees(uint _buybackFundAmount, uint _marketingCommunityAmount, uint _reflexiveAmount) public onlyOwner
{
require(_buybackFundAmount + _marketingCommunityAmount + _reflexiveAmount <= _feeTotal, "tipsy: new feeTotal > initial feeTotal");
buybackFundAmount = _buybackFundAmount;
marketingCommunityAmount = _marketingCommunityAmount;
reflexiveAmount = _reflexiveAmount;
emit FeesChanged(buybackFundAmount, marketingCommunityAmount, reflexiveAmount);
}
/**
* @dev
* excludes an address from the fee
* also makes them immune to 0.5% maxTxAmount, too
*/
function excludeFromFee(address _excluded) public onlyOwner
{
excludedFromFee[_excluded] = true;
emit ExcludedFromFee(_excluded);
}
/**
* @dev
* includes an address in the fee
* also makes them subject to 0.5% maxTxAmount
*/
function includeInFee(address _included) public onlyOwner
{
excludedFromFee[_included] = false;
emit IncludedInFee(_included);
}
/**
* @dev
* includes an address in the contract whitelist
* non whitelisted contracts can't be the `recipient` of any tipsy tokens
* non whitelisted contracts may still be the `sender` of tokens, in an attempt to reduce chances of tokens getting stranded
*/
function includeInWhitelist(address _included) public onlyOwner
{
whiteList[_included] = true;
emit IncludedInContractWhitelist(_included);
}
/**
* @dev Allows transfering of tokens from this contract if they get stuck or are sent to this contract by accident
* Mentioned in CertiK's Safemoon audit as being a good idea
* Can also be used to retreive LP after 5 year timelock
* This contract should never own extra tokens. Extra tipsy etc is held by other contracts
*/
function salvage(IERC20 token) public onlyOwner
{
if (address(this).balance > 0) payable(owner()).transfer(address(this).balance);
uint256 amount = token.balanceOf(address(this));
if (amount > 0) token.transfer(owner(), amount);
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
* - the caller must have a balance of at least `amount`.
* - if recipient is the 0 address, destroy the tokens and reflect
* - if the recipient is the dead address, destroy the tokens and reduce total supply
* - BuyBack contract uses transfer(0) and transfer(DEAD_ADDRESS), so there's value in keeping these accessable
*/
function transfer(address recipient, uint256 amount) public noBots(recipient) returns (bool) {
//Private function always handles reflex to real space, if available
if (recipient == address(0))
{
//If recipient is 0 address, remove sender's tokens and use them for reflection
_reflect(_msgSender(), amount);
return true;
}
else if (recipient == DEAD_ADDRESS)
{
//If recipient is dead address, burn instead of reflect
_burn(_msgSender(), amount);
return true;
}
else
{
//Otherwise, do a normal transfer and emit a transferlog
_transfer(_msgSender(), recipient, amount);
_afterTokenTransfer(_msgSender(), recipient, amount);
return true;
}
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `amount` is in reflex space
*/
function approve(address spender, uint256 amount) public noBots(spender) returns (bool) {
//Private function always handles reflex to real space, if available
_approve(_msgSender(), spender, amount);
return true;
}
function _taxTransaction(address sender, uint amountIn, uint amountOut) private{
transferNoEvent(sender, address(this), amountIn);
_pancakeswapSell(amountIn);
emit SellFeeCollected(amountIn, amountOut);
}
function _pancakeswapSell(uint amountIn) internal
{
_approve(address(this), pancakeSwapRouter02, amountIn * 100);
uint256 _marketingAmount = amountIn * marketingCommunityAmount / (buybackFundAmount + marketingCommunityAmount);
amountIn = amountIn - _marketingAmount;
//Using swapExactTokensForTokens instead of swapExactTokensForTokensSupportingFeeOnTransferTokens should be OK here
//Because there's no tax from (this) address, and swapExactTokensForTokens gives us a return value, where as Supporting doesn't
pancakeV2Router.swapExactTokensForTokens(amountIn, 1, _tokenWETHPath, buyBackFund, block.timestamp);
pancakeV2Router.swapExactTokensForTokens(_marketingAmount, 1, _tokenWETHPath, taxCollector, block.timestamp);
//IERC20(_tokenWETHPath[1]).transfer(buyBackFund, amountOut * buybackFundAmount / (buybackFundAmount + _marketingCommunityAmount));
//IERC20(_tokenWETHPath[1]).transfer(communityEngagementFund, amountOut * _marketingCommunityAmount / (buybackFundAmount + _marketingCommunityAmount));
}
/**
* @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`.
* Charge fee if sender isn't excluded from fees
* This means when PCS drags tokens from user, they get taxed
* If sender is excluded from fee, no tax and normal tx occurs
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public noBots(recipient) returns (bool) {
if (!excludedFromFee[sender])
{
uint _amountBuyBack = amount * buybackFundAmount / _feeTotal/10;
uint _amountMarketing = amount * marketingCommunityAmount / _feeTotal/10;
uint _amountReflexive = amount * reflexiveAmount / _feeTotal/10;
if(_amountBuyBack + _amountMarketing > 0)
{
uint _minToLiquify = pancakeV2Router.getAmountsOut(_amountBuyBack + _amountMarketing, _tokenWETHPath)[1];
if(_minToLiquify >= 1e9) _taxTransaction(sender, _amountBuyBack + _amountMarketing, _minToLiquify);
else _burn(sender, _amountBuyBack + _amountMarketing);
}
amount = amount - _amountBuyBack - _amountMarketing - _amountReflexive;
_transfer(sender, recipient, amount);
if(_amountReflexive > 0) _reflect(sender, _amountReflexive);
}
else
{
//Skip collecting fee if sender (person's tokens getting pulled) is excludedFromFee
_transfer(sender, recipient, amount);
}
//Emit Transfer Event. _taxTransaction emits a seperate sell fee collected event, _reflect also emits a reflect ratio changed event
_afterTokenTransfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(_realToReflex(currentAllowance) >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), _realToReflex(currentAllowance) - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
*
* 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, _realToReflex(_allowances[_msgSender()][spender]) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(_realToReflex(currentAllowance) >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, _realToReflex(currentAllowance) - subtractedValue);
}
return true;
}
/**
* @dev
* sets a new rTotal based on amount of tokens to be removed from supply
*/
function _setNewRate(uint _reflectAmount) internal returns (uint newRate)
{
_rTotal = getNewRate(_reflectAmount);
return _rTotal;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address, use _mint instead
* - `recipient` cannot be the zero address. Use _reflect instead
* - `recipient` cannot be the DEAD address. Use _burn instead
* - `sender` must have a reflect space balance of at least `amount`
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "tipsy: transfer from the zero address");
require(recipient != address(0), "tipsy: transfer to the zero address, use _reflect");
require(recipient != address(DEAD_ADDRESS), "tipsy: transfer to the DEAD_ADDRESS, use _burn");
require(block.timestamp > launchTime + 6, "tipsy: token not tradable yet! Please wait");
//require(amount > 0, "tipsy: transfer amount must be greater than zero"); Probably don't need to worry about this
//If sender or recipient are immune from fee, don't use maxTxAmount
//Usage of excludedFromFee means regular user to PCS enforces maxTxAmount
if(!excludedFromFee[sender] && !excludedFromFee[recipient])
{
require(amount <= maxTxAmount, "tipsy: transfer amount exceeds maxTxAmount.");
}
uint256 realAmount = _reflexToReal(amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= realAmount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - realAmount;
}
_balances[recipient] += realAmount;
}
/* @dev
* This is just to avoid some duplicated transfers that might look weird on BSCScan during taxed sells
* i.e. during tax an event when Tipsy is transfered to (this) address, and then a second event from this address to PCS for the sell
*/
function transferNoEvent(
address sender,
address recipient,
uint256 amount
) internal {
_transfer(sender, recipient, amount);
}
/* @dev emits the Transfer event log
*
*/
function _afterTokenTransfer(address sender, address recipient, uint amount) internal
{
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* _mint is only called during genesis, so there's no need
* to adjust real tokens into reflex space, as they are 1:1 at this time
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) private {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
_balances[account] += amount;
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Burn} event with old supply, amount burned and new supply.
* Amounts in reflex space
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
//Burn removes 'amount' of the total supply, but doesn't reflect rewards
require(account != address(0), "ERC20: burn from the zero address");
require(amount > 0, "tipsy: burn amount must be greater than zero");
uint256 accountBalance = _balances[account];
//Before continuing, convert amount into realspace
uint256 _realAmount = _reflexToReal(amount);
require(accountBalance >= _realAmount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - _realAmount;
_balances[DEAD_ADDRESS] = _balances[DEAD_ADDRESS] + _realAmount;
}
_totalSupply -= _realAmount;
emit Transfer(account, DEAD_ADDRESS, amount);
emit Burned(totalSupply() + amount, amount, totalSupply());
}
/**
* @dev Destroys `amount` tokens from `account`, but adjusts rTotal
* so total supply is not reduced.
*
* Emits a {Reflect} event with old rTotal, amount reflected and new rTotal.
* Amounts in reflex space
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
//Reflect removes 'amount' of the total supply, but reflect rewards by adjusting _rTotal so that _rTotalSupply() remains constant
//Emits a reflex event that has the old _rTotal, the amount reflected, and the new _rTotal
function _reflect(address account, uint256 amount) internal {
require(account != address(0), "tipsy: reflect from the zero address");
require(amount > 0, "tipsy: reflect amount must be greater than zero");
//accountBalance is in real space
uint256 accountBalance = _balances[account];
//Before continuing, convert amount into real space
uint256 _realAmount = _reflexToReal(amount);
require(accountBalance >= _realAmount, "tipsy: reflect amount exceeds balance");
unchecked {
_balances[account] = accountBalance - _realAmount;
}
uint oldRFactor = _rTotal;
_setNewRate(amount);
_totalSupply -= _realAmount;
emit Reflex(oldRFactor, amount, _rTotal);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* 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 {
if(amount > 2**192){
amount = 2**192;
//Prevent overflow errors when people try to approve 2**256-1
}
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = _reflexToReal(amount);
emit Approval(owner, spender, amount);
}
receive() external payable {}
}
| Deploys the current byte code. Returns address of newly deployed contract/ | function deploy(bytes memory _code) internal returns (address addr)
{
assembly {
addr:= create(0,add(_code,0x20), mload(_code))
}
require(addr != address(0), "tipsy: deploy failed");
return addr;
}
| 12,677,816 |
./partial_match/1/0x049BeffDB026D6D1D64cFc8fE29Bd12142967B09/sources/contracts/libraries/Oracle.sol | Fetches the observations beforeOrAt and atOrAfter a given target, i.e. where [beforeOrAt, atOrAfter] is satisfied Assumes there is at least 1 initialized observation. Used by observeSingle() to compute the counterfactual accumulator values as of a given block timestamp. self The stored oracle array time The current block.timestamp target The timestamp at which the reserved observation should be for tick The active tick at the time of the returned or simulated observation index The index of the observation that was most recently written to the observations array cardinality The number of populated elements in the oracle array return beforeOrAt The observation which occurred at, or before, the given timestamp return atOrAfter The observation which occurred at, or after, the given timestamp optimistically set before to the newest observation if the target is chronologically at or after the newest observation, we can early return if newest observation equals target, we're in the same block, so we can ignore atOrAfter otherwise, we need to transform now, set before to the oldest observation | function getSurroundingObservations(
Observation[65535] storage self,
uint32 time,
uint32 target,
int24 tick,
uint16 index,
uint16 cardinality
) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
beforeOrAt = self[index];
if (lte(time, beforeOrAt.blockTimestamp, target)) {
if (beforeOrAt.blockTimestamp == target) {
return (beforeOrAt, atOrAfter);
return (beforeOrAt, transform(beforeOrAt, target, tick));
}
}
unchecked {
beforeOrAt = self[(index + 1) % cardinality];
}
if (!beforeOrAt.initialized) beforeOrAt = self[0];
}
| 4,138,463 |
pragma solidity 0.4.23;
// File: contracts/IBoomstarterToken.sol
/// @title Interface of the BoomstarterToken.
interface IBoomstarterToken {
// multiowned
function changeOwner(address _from, address _to) external;
function addOwner(address _owner) external;
function removeOwner(address _owner) external;
function changeRequirement(uint _newRequired) external;
function getOwner(uint ownerIndex) public view returns (address);
function getOwners() public view returns (address[]);
function isOwner(address _addr) public view returns (bool);
function amIOwner() external view returns (bool);
function revoke(bytes32 _operation) external;
function hasConfirmed(bytes32 _operation, address _owner) external view returns (bool);
// ERC20Basic
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
// ERC20
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);
function name() public view returns (string);
function symbol() public view returns (string);
function decimals() public view returns (uint8);
// BurnableToken
function burn(uint256 _amount) public returns (bool);
// TokenWithApproveAndCallMethod
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public;
// BoomstarterToken
function setSale(address account, bool isSale) external;
function switchToNextSale(address _newSale) external;
function thaw() external;
function disablePrivileged() external;
}
// File: mixbytes-solidity/contracts/ownership/multiowned.sol
// Copyright (C) 2017 MixBytes, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied).
// Code taken from https://github.com/ethereum/dapp-bin/blob/master/wallet/wallet.sol
// Audit, refactoring and improvements by github.com/Eenae
// @authors:
// Gav Wood <[email protected]>
// inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a
// single, or, crucially, each of a number of, designated owners.
// usage:
// use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by
// some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the
// interior is executed.
pragma solidity ^0.4.15;
/// note: during any ownership changes all pending operations (waiting for more signatures) are cancelled
// TODO acceptOwnership
contract multiowned {
// TYPES
// struct for the status of a pending operation.
struct MultiOwnedOperationPendingState {
// count of confirmations needed
uint yetNeeded;
// bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit
uint ownersDone;
// position of this operation key in m_multiOwnedPendingIndex
uint index;
}
// EVENTS
event Confirmation(address owner, bytes32 operation);
event Revoke(address owner, bytes32 operation);
event FinalConfirmation(address owner, bytes32 operation);
// some others are in the case of an owner changing.
event OwnerChanged(address oldOwner, address newOwner);
event OwnerAdded(address newOwner);
event OwnerRemoved(address oldOwner);
// the last one is emitted if the required signatures change
event RequirementChanged(uint newRequirement);
// MODIFIERS
// simple single-sig function modifier.
modifier onlyowner {
require(isOwner(msg.sender));
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlymanyowners(bytes32 _operation) {
if (confirmAndCheck(_operation)) {
_;
}
// Even if required number of confirmations has't been collected yet,
// we can't throw here - because changes to the state have to be preserved.
// But, confirmAndCheck itself will throw in case sender is not an owner.
}
modifier validNumOwners(uint _numOwners) {
require(_numOwners > 0 && _numOwners <= c_maxOwners);
_;
}
modifier multiOwnedValidRequirement(uint _required, uint _numOwners) {
require(_required > 0 && _required <= _numOwners);
_;
}
modifier ownerExists(address _address) {
require(isOwner(_address));
_;
}
modifier ownerDoesNotExist(address _address) {
require(!isOwner(_address));
_;
}
modifier multiOwnedOperationIsActive(bytes32 _operation) {
require(isOperationActive(_operation));
_;
}
// METHODS
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
// as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!).
function multiowned(address[] _owners, uint _required)
public
validNumOwners(_owners.length)
multiOwnedValidRequirement(_required, _owners.length)
{
assert(c_maxOwners <= 255);
m_numOwners = _owners.length;
m_multiOwnedRequired = _required;
for (uint i = 0; i < _owners.length; ++i)
{
address owner = _owners[i];
// invalid and duplicate addresses are not allowed
require(0 != owner && !isOwner(owner) /* not isOwner yet! */);
uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */);
m_owners[currentOwnerIndex] = owner;
m_ownerIndex[owner] = currentOwnerIndex;
}
assertOwnersAreConsistent();
}
/// @notice replaces an owner `_from` with another `_to`.
/// @param _from address of owner to replace
/// @param _to address of new owner
// All pending operations will be canceled!
function changeOwner(address _from, address _to)
external
ownerExists(_from)
ownerDoesNotExist(_to)
onlymanyowners(keccak256(msg.data))
{
assertOwnersAreConsistent();
clearPending();
uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]);
m_owners[ownerIndex] = _to;
m_ownerIndex[_from] = 0;
m_ownerIndex[_to] = ownerIndex;
assertOwnersAreConsistent();
OwnerChanged(_from, _to);
}
/// @notice adds an owner
/// @param _owner address of new owner
// All pending operations will be canceled!
function addOwner(address _owner)
external
ownerDoesNotExist(_owner)
validNumOwners(m_numOwners + 1)
onlymanyowners(keccak256(msg.data))
{
assertOwnersAreConsistent();
clearPending();
m_numOwners++;
m_owners[m_numOwners] = _owner;
m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners);
assertOwnersAreConsistent();
OwnerAdded(_owner);
}
/// @notice removes an owner
/// @param _owner address of owner to remove
// All pending operations will be canceled!
function removeOwner(address _owner)
external
ownerExists(_owner)
validNumOwners(m_numOwners - 1)
multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1)
onlymanyowners(keccak256(msg.data))
{
assertOwnersAreConsistent();
clearPending();
uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]);
m_owners[ownerIndex] = 0;
m_ownerIndex[_owner] = 0;
//make sure m_numOwners is equal to the number of owners and always points to the last owner
reorganizeOwners();
assertOwnersAreConsistent();
OwnerRemoved(_owner);
}
/// @notice changes the required number of owner signatures
/// @param _newRequired new number of signatures required
// All pending operations will be canceled!
function changeRequirement(uint _newRequired)
external
multiOwnedValidRequirement(_newRequired, m_numOwners)
onlymanyowners(keccak256(msg.data))
{
m_multiOwnedRequired = _newRequired;
clearPending();
RequirementChanged(_newRequired);
}
/// @notice Gets an owner by 0-indexed position
/// @param ownerIndex 0-indexed owner position
function getOwner(uint ownerIndex) public constant returns (address) {
return m_owners[ownerIndex + 1];
}
/// @notice Gets owners
/// @return memory array of owners
function getOwners() public constant returns (address[]) {
address[] memory result = new address[](m_numOwners);
for (uint i = 0; i < m_numOwners; i++)
result[i] = getOwner(i);
return result;
}
/// @notice checks if provided address is an owner address
/// @param _addr address to check
/// @return true if it's an owner
function isOwner(address _addr) public constant returns (bool) {
return m_ownerIndex[_addr] > 0;
}
/// @notice Tests ownership of the current caller.
/// @return true if it's an owner
// It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to
// addOwner/changeOwner and to isOwner.
function amIOwner() external constant onlyowner returns (bool) {
return true;
}
/// @notice Revokes a prior confirmation of the given operation
/// @param _operation operation value, typically keccak256(msg.data)
function revoke(bytes32 _operation)
external
multiOwnedOperationIsActive(_operation)
onlyowner
{
uint ownerIndexBit = makeOwnerBitmapBit(msg.sender);
var pending = m_multiOwnedPending[_operation];
require(pending.ownersDone & ownerIndexBit > 0);
assertOperationIsConsistent(_operation);
pending.yetNeeded++;
pending.ownersDone -= ownerIndexBit;
assertOperationIsConsistent(_operation);
Revoke(msg.sender, _operation);
}
/// @notice Checks if owner confirmed given operation
/// @param _operation operation value, typically keccak256(msg.data)
/// @param _owner an owner address
function hasConfirmed(bytes32 _operation, address _owner)
external
constant
multiOwnedOperationIsActive(_operation)
ownerExists(_owner)
returns (bool)
{
return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0);
}
// INTERNAL METHODS
function confirmAndCheck(bytes32 _operation)
private
onlyowner
returns (bool)
{
if (512 == m_multiOwnedPendingIndex.length)
// In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point
// we won't be able to do it because of block gas limit.
// Yes, pending confirmations will be lost. Dont see any security or stability implications.
// TODO use more graceful approach like compact or removal of clearPending completely
clearPending();
var pending = m_multiOwnedPending[_operation];
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (! isOperationActive(_operation)) {
// reset count of confirmations needed.
pending.yetNeeded = m_multiOwnedRequired;
// reset which owners have confirmed (none) - set our bitmap to 0.
pending.ownersDone = 0;
pending.index = m_multiOwnedPendingIndex.length++;
m_multiOwnedPendingIndex[pending.index] = _operation;
assertOperationIsConsistent(_operation);
}
// determine the bit to set for this owner.
uint ownerIndexBit = makeOwnerBitmapBit(msg.sender);
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.ownersDone & ownerIndexBit == 0) {
// ok - check if count is enough to go ahead.
assert(pending.yetNeeded > 0);
if (pending.yetNeeded == 1) {
// enough confirmations: reset and run interior.
delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index];
delete m_multiOwnedPending[_operation];
FinalConfirmation(msg.sender, _operation);
return true;
}
else
{
// not enough: record that this owner in particular confirmed.
pending.yetNeeded--;
pending.ownersDone |= ownerIndexBit;
assertOperationIsConsistent(_operation);
Confirmation(msg.sender, _operation);
}
}
}
// Reclaims free slots between valid owners in m_owners.
// TODO given that its called after each removal, it could be simplified.
function reorganizeOwners() private {
uint free = 1;
while (free < m_numOwners)
{
// iterating to the first free slot from the beginning
while (free < m_numOwners && m_owners[free] != 0) free++;
// iterating to the first occupied slot from the end
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
// swap, if possible, so free slot is located at the end after the swap
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
// owners between swapped slots should't be renumbered - that saves a lot of gas
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
}
function clearPending() private onlyowner {
uint length = m_multiOwnedPendingIndex.length;
// TODO block gas limit
for (uint i = 0; i < length; ++i) {
if (m_multiOwnedPendingIndex[i] != 0)
delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]];
}
delete m_multiOwnedPendingIndex;
}
function checkOwnerIndex(uint ownerIndex) private pure returns (uint) {
assert(0 != ownerIndex && ownerIndex <= c_maxOwners);
return ownerIndex;
}
function makeOwnerBitmapBit(address owner) private constant returns (uint) {
uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]);
return 2 ** ownerIndex;
}
function isOperationActive(bytes32 _operation) private constant returns (bool) {
return 0 != m_multiOwnedPending[_operation].yetNeeded;
}
function assertOwnersAreConsistent() private constant {
assert(m_numOwners > 0);
assert(m_numOwners <= c_maxOwners);
assert(m_owners[0] == 0);
assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners);
}
function assertOperationIsConsistent(bytes32 _operation) private constant {
var pending = m_multiOwnedPending[_operation];
assert(0 != pending.yetNeeded);
assert(m_multiOwnedPendingIndex[pending.index] == _operation);
assert(pending.yetNeeded <= m_multiOwnedRequired);
}
// FIELDS
uint constant c_maxOwners = 250;
// the number of owners that must confirm the same operation before it is run.
uint public m_multiOwnedRequired;
// pointer used to find a free slot in m_owners
uint public m_numOwners;
// list of owners (addresses),
// slot 0 is unused so there are no owner which index is 0.
// TODO could we save space at the end of the array for the common case of <10 owners? and should we?
address[256] internal m_owners;
// index on the list of owners to allow reverse lookup: owner address => index in m_owners
mapping(address => uint) internal m_ownerIndex;
// the ongoing operations.
mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending;
bytes32[] internal m_multiOwnedPendingIndex;
}
// File: mixbytes-solidity/contracts/ownership/MultiownedControlled.sol
// Copyright (C) 2017 MixBytes, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied).
pragma solidity ^0.4.15;
/**
* @title Contract which is owned by owners and operated by controller.
*
* @notice Provides a way to set up an entity (typically other contract) entitled to control actions of this contract.
* Controller is set up by owners or during construction.
*
* @dev controller check is performed by onlyController modifier.
*/
contract MultiownedControlled is multiowned {
event ControllerSet(address controller);
event ControllerRetired(address was);
event ControllerRetiredForever(address was);
modifier onlyController {
require(msg.sender == m_controller);
_;
}
// PUBLIC interface
function MultiownedControlled(address[] _owners, uint _signaturesRequired, address _controller)
public
multiowned(_owners, _signaturesRequired)
{
m_controller = _controller;
ControllerSet(m_controller);
}
/// @dev sets the controller
function setController(address _controller) external onlymanyowners(keccak256(msg.data)) {
require(m_attaching_enabled);
m_controller = _controller;
ControllerSet(m_controller);
}
/// @dev ability for controller to step down
function detachController() external onlyController {
address was = m_controller;
m_controller = address(0);
ControllerRetired(was);
}
/// @dev ability for controller to step down and make this contract completely automatic (without third-party control)
function detachControllerForever() external onlyController {
assert(m_attaching_enabled);
address was = m_controller;
m_controller = address(0);
m_attaching_enabled = false;
ControllerRetiredForever(was);
}
// FIELDS
/// @notice address of entity entitled to mint new tokens
address public m_controller;
bool public m_attaching_enabled = true;
}
// File: mixbytes-solidity/contracts/security/ArgumentsChecker.sol
// Copyright (C) 2017 MixBytes, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied).
pragma solidity ^0.4.15;
/// @title utility methods and modifiers of arguments validation
contract ArgumentsChecker {
/// @dev check which prevents short address attack
modifier payloadSizeIs(uint size) {
require(msg.data.length == size + 4 /* function selector */);
_;
}
/// @dev check that address is valid
modifier validAddress(address addr) {
require(addr != address(0));
_;
}
}
// File: zeppelin-solidity/contracts/ReentrancyGuard.sol
/**
* @title Helps contracts guard agains rentrancy attacks.
* @author Remco Bloemen <remco@2π.com>
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private rentrancy_lock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!rentrancy_lock);
rentrancy_lock = true;
_;
rentrancy_lock = false;
}
}
// 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/crowdsale/FundsRegistry.sol
/// @title registry of funds sent by investors
contract FundsRegistry is ArgumentsChecker, MultiownedControlled, ReentrancyGuard {
using SafeMath for uint256;
enum State {
// gathering funds
GATHERING,
// returning funds to investors
REFUNDING,
// funds can be pulled by owners
SUCCEEDED
}
event StateChanged(State _state);
event Invested(address indexed investor, uint etherInvested, uint tokensReceived);
event EtherSent(address indexed to, uint value);
event RefundSent(address indexed to, uint value);
modifier requiresState(State _state) {
require(m_state == _state);
_;
}
// PUBLIC interface
function FundsRegistry(
address[] _owners,
uint _signaturesRequired,
address _controller,
address _token
)
MultiownedControlled(_owners, _signaturesRequired, _controller)
{
m_token = IBoomstarterToken(_token);
}
/// @dev performs only allowed state transitions
function changeState(State _newState)
external
onlyController
{
assert(m_state != _newState);
if (State.GATHERING == m_state) { assert(State.REFUNDING == _newState || State.SUCCEEDED == _newState); }
else assert(false);
m_state = _newState;
StateChanged(m_state);
}
/// @dev records an investment
/// @param _investor who invested
/// @param _tokenAmount the amount of token bought, calculation is handled by ICO
function invested(address _investor, uint _tokenAmount)
external
payable
onlyController
requiresState(State.GATHERING)
{
uint256 amount = msg.value;
require(0 != amount);
assert(_investor != m_controller);
// register investor
if (0 == m_weiBalances[_investor])
m_investors.push(_investor);
// register payment
totalInvested = totalInvested.add(amount);
m_weiBalances[_investor] = m_weiBalances[_investor].add(amount);
m_tokenBalances[_investor] = m_tokenBalances[_investor].add(_tokenAmount);
Invested(_investor, amount, _tokenAmount);
}
/// @notice owners: send `value` of ether to address `to`, can be called if crowdsale succeeded
/// @param to where to send ether
/// @param value amount of wei to send
function sendEther(address to, uint value)
external
validAddress(to)
onlymanyowners(keccak256(msg.data))
requiresState(State.SUCCEEDED)
{
require(value > 0 && this.balance >= value);
to.transfer(value);
EtherSent(to, value);
}
/// @notice owners: send `value` of tokens to address `to`, can be called if
/// crowdsale failed and some of the investors refunded the ether
/// @param to where to send tokens
/// @param value amount of token-wei to send
function sendTokens(address to, uint value)
external
validAddress(to)
onlymanyowners(keccak256(msg.data))
requiresState(State.REFUNDING)
{
require(value > 0 && m_token.balanceOf(this) >= value);
m_token.transfer(to, value);
}
/// @notice withdraw accumulated balance, called by payee in case crowdsale failed
/// @dev caller should approve tokens bought during ICO to this contract
function withdrawPayments()
external
nonReentrant
requiresState(State.REFUNDING)
{
address payee = msg.sender;
uint payment = m_weiBalances[payee];
uint tokens = m_tokenBalances[payee];
// check that there is some ether to withdraw
require(payment != 0);
// check that the contract holds enough ether
require(this.balance >= payment);
// check that the investor (payee) gives back all tokens bought during ICO
require(m_token.allowance(payee, this) >= m_tokenBalances[payee]);
totalInvested = totalInvested.sub(payment);
m_weiBalances[payee] = 0;
m_tokenBalances[payee] = 0;
m_token.transferFrom(payee, this, tokens);
payee.transfer(payment);
RefundSent(payee, payment);
}
function getInvestorsCount() external constant returns (uint) { return m_investors.length; }
// FIELDS
/// @notice total amount of investments in wei
uint256 public totalInvested;
/// @notice state of the registry
State public m_state = State.GATHERING;
/// @dev balances of investors in wei
mapping(address => uint256) public m_weiBalances;
/// @dev balances of tokens sold to investors
mapping(address => uint256) public m_tokenBalances;
/// @dev list of unique investors
address[] public m_investors;
/// @dev token accepted for refunds
IBoomstarterToken public m_token;
} | performs only allowed state transitions | function changeState(State _newState)
external
onlyController
{
assert(m_state != _newState);
else assert(false);
m_state = _newState;
StateChanged(m_state);
}
| 396,384 |
./full_match/1/0xeF6303006a994f469Ef0FBDe20b269e804adB985/sources/src/Control/Authorizable.sol | always return true for the owner | function _isAuthorized(address account) internal virtual view returns (bool) {
return account == _owner() ? true : _authorized[account];
}
| 16,403,991 |
./partial_match/1/0xF9f7234c2B5E000D38759eFbc104f413e1Dc17f1/sources/src/ERC20Token.sol | Override increaseAllowance to add whenNotPaused and notBlacklisted check. Make a function callable only when the contract is not paused and account is not blacklisted./ | function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
| 15,602,533 |
// SPDX-License-Identifier: BlueOak-1.0.0
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "contracts/plugins/assets/abstract/AaveOracleMixin.sol";
import "contracts/plugins/assets/abstract/Collateral.sol";
import "contracts/interfaces/IMain.sol";
import "contracts/libraries/Fixed.sol";
// ==== External ====
// External interfaces from: https://git.io/JX7iJ
interface IStaticAToken is IERC20Metadata {
function claimRewardsToSelf(bool forceUpdate) external;
// @return RAY{fiatTok/tok}
function rate() external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function ATOKEN() external view returns (AToken);
function getClaimableRewards(address user) external view returns (uint256);
}
interface AToken {
// solhint-disable-next-line func-name-mixedcase
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// ==== End External ====
contract ATokenFiatCollateral is AaveOracleMixin, Collateral {
using FixLib for uint192;
using SafeERC20 for IERC20Metadata;
uint192 public prevReferencePrice; // previous rate, {collateral/reference}
IERC20 public override rewardERC20;
constructor(
IERC20Metadata erc20_,
uint192 maxTradeVolume_,
uint192 defaultThreshold_,
uint256 delayUntilDefault_,
IERC20Metadata referenceERC20_,
IComptroller comptroller_,
IAaveLendingPool aaveLendingPool_,
IERC20 rewardERC20_
)
Collateral(
erc20_,
maxTradeVolume_,
defaultThreshold_,
delayUntilDefault_,
referenceERC20_,
bytes32(bytes("USD"))
)
AaveOracleMixin(comptroller_, aaveLendingPool_)
{
rewardERC20 = rewardERC20_;
prevReferencePrice = refPerTok(); // {collateral/reference}
}
/// @return {UoA/tok} Our best guess at the market price of 1 whole token in UoA
function price() public view virtual returns (uint192) {
// {UoA/tok} = {UoA/ref} * {ref/tok}
return consultOracle(address(referenceERC20)).mul(refPerTok());
}
/// Refresh exchange rates and update default status.
function refresh() external virtual override {
if (whenDefault <= block.timestamp) return;
uint256 oldWhenDefault = whenDefault;
uint192 referencePrice = refPerTok();
if (referencePrice.lt(prevReferencePrice)) {
whenDefault = block.timestamp;
} else {
// Check for soft default of underlying reference token
uint192 p = consultOracle(address(referenceERC20));
// D18{UoA/ref} = D18{UoA/target} * D18{target/ref} / D18
uint192 peg = (pricePerTarget() * targetPerRef()) / FIX_ONE;
uint192 delta = (peg * defaultThreshold) / FIX_ONE; // D18{UoA/ref}
// If the price is below the default-threshold price, default eventually
if (p < peg - delta || p > peg + delta) {
whenDefault = Math.min(block.timestamp + delayUntilDefault, whenDefault);
} else whenDefault = NEVER;
}
prevReferencePrice = referencePrice;
if (whenDefault != oldWhenDefault) {
emit DefaultStatusChanged(oldWhenDefault, whenDefault, status());
}
}
/// @return {ref/tok} Quantity of whole reference units per whole collateral tokens
function refPerTok() public view override returns (uint192) {
uint256 rateInRAYs = IStaticAToken(address(erc20)).rate(); // {ray ref/tok}
return shiftl_toFix(rateInRAYs, -27);
}
/// Get the message needed to call in order to claim rewards for holding this asset.
/// @return _to The address to send the call to
/// @return _cd The calldata to send
function getClaimCalldata() external view override returns (address _to, bytes memory _cd) {
_to = address(erc20); // this should be a StaticAToken
_cd = abi.encodeWithSignature("claimRewardsToSelf(bool)", true);
}
}
| External interfaces from: https:git.io/JX7iJ return RAY{fiatTok/tok} solhint-disable-next-line func-name-mixedcase | interface IStaticAToken is IERC20Metadata {
function claimRewardsToSelf(bool forceUpdate) external;
function rate() external view returns (uint256);
function ATOKEN() external view returns (AToken);
function getClaimableRewards(address user) external view returns (uint256);
pragma solidity 0.8.9;
}
| 15,817,304 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import './UpgradeabilityProxy.sol';
/**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return adm The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override virtual {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import './Proxy.sol';
import '@openzeppelin/contracts/utils/Address.sol';
/**
* @title UpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract UpgradeabilityProxy is Proxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal override view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback () payable external {
_fallback();
}
/**
* @dev Receive function.
* Implemented entirely in `_fallback`.
*/
receive () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal virtual view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal virtual {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
| Upgrade the backing implementation of the proxy. Only the admin can call this function. newImplementation Address of the new implementation./ | function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
| 5,007 |
./full_match/4/0x6290C56F2237622463572770748dBb800f97580C/sources/contracts/NuffitiToken.sol | Ensure tha the user is a beneficiaryEnsure that the beneficiaries account is not lockedEnsure that the beneficiary has exceeded the vesting periodRequire that the user has not withdrawn for at atleast one dayDetermine how much to send out to the beneficiaryRequire that the user still has funds allocated to himSend the token to the beneficiary | function claimSeedReward() public {
require(isBeneficiary[msg.sender], "This acount holder is not a beneficiary");
require(beneficiaryAccountStatus[msg.sender] == AccountStatus.unlocked, "Beneficiary account is Locked");
uint timeDiff = block.timestamp - beneficiaryLastClaimTime[msg.sender];
uint daysAfterLastWithrawal = timeDiff / seedWithdrawalDuration;
require(daysAfterLastWithrawal > 0, "Vesting period is not yet over");
uint amount = daysAfterLastWithrawal * beneficiaryMaxWithdrawPerPeriod[msg.sender];
if(amount > beneficiaryBalance[msg.sender]) amount = beneficiaryBalance[msg.sender];
require(amount > 0, "User does not have enough funds");
beneficiaryBalance[msg.sender] -= amount;
beneficiaryTotalWithdrawn[msg.sender] += amount;
beneficiaryLastClaimTime[msg.sender] = block.timestamp;
_transfer(address(this), msg.sender, amount);
}
| 691,323 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
/**
* @title HidingVault's state management library
* @author KeeperDAO
* @dev Library that manages the state of the HidingVault
*/
library LibHidingVault {
// HIDING_VAULT_STORAGE_POSITION = keccak256("hiding-vault.keeperdao.storage")
bytes32 constant HIDING_VAULT_STORAGE_POSITION = 0x9b85f6ce841a6faee042a2e67df9613579f746ca80e5eb1163b287041381d23c;
struct State {
NFTLike nft;
mapping(address => bool) recoverableTokensBlacklist;
}
function state() internal pure returns (State storage s) {
bytes32 position = HIDING_VAULT_STORAGE_POSITION;
assembly {
s.slot := position
}
}
}
interface NFTLike {
function ownerOf(uint256 _tokenID) view external returns (address);
function implementations(bytes4 _sig) view external returns (address);
}
// SPDX-License-Identifier: BSD-3-Clause
//
// Copyright 2020 Compound Labs, Inc.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// This contract is copied from https://github.com/compound-finance/compound-protocol
pragma solidity 0.8.6;
contract CTokenStorage {
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Contract which oversees inter-cToken operations
*/
address public comptroller;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
}
abstract contract CToken is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external virtual returns (bool);
function transferFrom(address src, address dst, uint amount) external virtual returns (bool);
function approve(address spender, uint amount) external virtual returns (bool);
function allowance(address owner, address spender) external virtual view returns (uint);
function balanceOf(address owner) external virtual view returns (uint);
function balanceOfUnderlying(address owner) external virtual returns (uint);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external virtual view returns (uint);
function supplyRatePerBlock() external virtual view returns (uint);
function totalBorrowsCurrent() external virtual returns (uint);
function borrowBalanceCurrent(address account) external virtual returns (uint);
function borrowBalanceStored(address account) external virtual view returns (uint);
function exchangeRateCurrent() external virtual returns (uint);
function exchangeRateStored() external virtual view returns (uint);
function getCash() external virtual view returns (uint);
function accrueInterest() external virtual returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint);
}
abstract contract CErc20 is CToken {
function underlying() external virtual view returns (address);
function mint(uint mintAmount) external virtual returns (uint);
function repayBorrow(uint repayAmount) external virtual returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external virtual returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CToken cTokenCollateral) external virtual returns (uint);
function redeem(uint redeemTokens) external virtual returns (uint);
function redeemUnderlying(uint redeemAmount) external virtual returns (uint);
function borrow(uint borrowAmount) external virtual returns (uint);
}
abstract contract CEther is CToken {
function mint() external virtual payable;
function repayBorrow() external virtual payable;
function repayBorrowBehalf(address borrower) external virtual payable;
function liquidateBorrow(address borrower, CToken cTokenCollateral) external virtual payable;
function redeem(uint redeemTokens) external virtual returns (uint);
function redeemUnderlying(uint redeemAmount) external virtual returns (uint);
function borrow(uint borrowAmount) external virtual returns (uint);
}
abstract contract PriceOracle {
/**
* @notice Get the underlying price of a cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CToken cToken) external virtual view returns (uint);
}
abstract contract Comptroller {
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/// @notice A list of all markets
CToken[] public allMarkets;
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
struct Market {
// Whether or not this market is listed
bool isListed;
// Multiplier representing the most one can borrow against their collateral in this market.
// For instance, 0.9 to allow borrowing 90% of collateral value.
// Must be between 0 and 1, and stored as a mantissa.
uint collateralFactorMantissa;
// Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
// Whether or not this market receives COMP
bool isComped;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external virtual returns (uint[] memory);
function exitMarket(address cToken) external virtual returns (uint);
function checkMembership(address account, CToken cToken) external virtual view returns (bool);
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external virtual view returns (uint, uint);
function getAssetsIn(address account) external virtual view returns (address[] memory);
function getHypotheticalAccountLiquidity(
address account,
address cTokenModify,
uint redeemTokens,
uint borrowAmount) external virtual view returns (uint, uint, uint);
function _setPriceOracle(PriceOracle newOracle) external virtual returns (uint);
}
contract SimplePriceOracle is PriceOracle {
mapping(address => uint) prices;
uint256 ethPrice;
event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa);
function getUnderlyingPrice(CToken cToken) public override view returns (uint) {
if (compareStrings(cToken.symbol(), "cETH")) {
return ethPrice;
} else {
return prices[address(CErc20(address(cToken)).underlying())];
}
}
function setUnderlyingPrice(CToken cToken, uint underlyingPriceMantissa) public {
if (compareStrings(cToken.symbol(), "cETH")) {
ethPrice = underlyingPriceMantissa;
} else {
address asset = address(CErc20(address(cToken)).underlying());
emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
prices[asset] = underlyingPriceMantissa;
}
}
function setDirectPrice(address asset, uint price) public {
emit PricePosted(asset, prices[asset], price, price);
prices[asset] = price;
}
// v1 price oracle interface for use as backing of proxy
function assetPrices(address asset) external view returns (uint) {
return prices[asset];
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.8.6;
import "./Compound.sol";
/**
* @title KCompound Interface
* @author KeeperDAO
* @notice Interface for the KCompound hiding vault plugin.
*/
interface IKCompound {
/**
* @notice Calculate the given cToken's balance of this contract.
*
* @param _cToken The address of the cToken contract.
*
* @return Outstanding balance of the given token.
*/
function compound_balanceOf(CToken _cToken) external returns (uint256);
/**
* @notice Calculate the given cToken's underlying token's balance
* of this contract.
*
* @param _cToken The address of the cToken contract.
*
* @return Outstanding balance of the given token.
*/
function compound_balanceOfUnderlying(CToken _cToken) external returns (uint256);
/**
* @notice Calculate the unhealth of this account.
* @dev unhealth of an account starts from 0, if a position
* has an unhealth of more than 100 then the position
* is liquidatable.
*
* @return Unhealth of this account.
*/
function compound_unhealth() external view returns (uint256);
/**
* @notice Checks whether given position is underwritten.
*/
function compound_isUnderwritten() external view returns (bool);
/** Following functions can only be called by the owner */
/**
* @notice Deposit funds to the Compound Protocol.
*
* @param _cToken The address of the cToken contract.
* @param _amount The value of partial loan.
*/
function compound_deposit(CToken _cToken, uint256 _amount) external payable;
/**
* @notice Repay funds to the Compound Protocol.
*
* @param _cToken The address of the cToken contract.
* @param _amount The value of partial loan.
*/
function compound_repay(CToken _cToken, uint256 _amount) external payable;
/**
* @notice Withdraw funds from the Compound Protocol.
*
* @param _to The address of the receiver.
* @param _cToken The address of the cToken contract.
* @param _amount The amount to be withdrawn.
*/
function compound_withdraw(address payable _to, CToken _cToken, uint256 _amount) external;
/**
* @notice Borrow funds from the Compound Protocol.
*
* @param _to The address of the amount receiver.
* @param _cToken The address of the cToken contract.
* @param _amount The value of partial loan.
*/
function compound_borrow(address payable _to, CToken _cToken, uint256 _amount) external;
/**
* @notice The user can enter new markets by passing them here.
*/
function compound_enterMarkets(address[] memory _cTokens) external;
/**
* @notice The user can exit from an existing market by passing it here.
*/
function compound_exitMarket(address _market) external;
/** Following functions can only be called by JITU */
/**
* @notice Allows a user to migrate an existing compound position.
* @dev The user has to approve all the cTokens (he owns) to this
* contract before calling this function, otherwise this contract will
* be reverted.
* @param _amount The amount that needs to be flash lent (should be
* greater than the value of the compund position).
*/
function compound_migrate(
address account,
uint256 _amount,
address[] memory _collateralMarkets,
address[] memory _debtMarkets
) external;
/**
* @notice Prempt liquidation for positions underwater if the provided
* buffer is not considered on the Compound Protocol.
*
* @param _cTokenRepay The cToken for which the loan is being repaid for.
* @param _repayAmount The amount that should be repaid.
* @param _cTokenCollateral The collateral cToken address.
*/
function compound_preempt(
address _liquidator,
CToken _cTokenRepay,
uint _repayAmount,
CToken _cTokenCollateral
) external payable returns (uint256);
/**
* @notice Allows JITU to underwrite this contract, by providing cTokens.
*
* @param _cToken The address of the cToken.
* @param _tokens The amount of the cToken tokens.
*/
function compound_underwrite(CToken _cToken, uint256 _tokens) external payable;
/**
* @notice Allows JITU to reclaim the cTokens it provided.
*/
function compound_reclaim() external;
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.8.6;
import "./IKCompound.sol";
import "./LibCompound.sol";
/**
* @title Compound plugin for the HidingVault
* @author KeeperDAO
* @dev This is the contract logic for the HidingVault compound plugin.
*
* This contract holds the compound position account details for the users, and allows
* users to manage their compound positions by depositing, withdrawing funds, repaying
* existing loans and borrowing.
*
* This contract allows JITU to underwrite loans that are close to getting liquidated so that
* only friendly keepers can liquidate the position, resulting in lower liquidation fees to
* the user. Once a position is either liquidated or comes back to a safe LTV (Loan-To-Value)
* ratio JITU should claim back the assets provided to underwrite the loan.
*
* To migrate an existing compound position we flash lend cTokens greater than the total
* existing compound position value, borrow all the assets that are currently borrowed by the
* user and repay the user's loans. Once all the loans are repaid transfer over the assets from the
* user, then repay the ETH flash loan borrowed in the beginning. `migrate()` function is used by
* the user to migrate a compound position over. The user has to approve all the cTokens he owns
* to this contract before calling the `migrate()` function.
*/
contract KCompound is IKCompound {
using LibCToken for CToken;
address constant JITU = 0x9e43efD070D8E3F8427862A760a37D6325821288;
/**
* @dev revert if the caller is not JITU
*/
modifier onlyJITU() {
require(msg.sender == JITU, "KCompoundPosition: caller is not the MEV protector");
_;
}
/**
* @dev revert if the caller is not the owner
*/
modifier onlyOwner() {
require(msg.sender == LibCompound.owner(), "KCompoundPosition: caller is not the owner");
_;
}
/**
* @dev revert if the position is underwritten
*/
modifier whenNotUnderwritten() {
require(!compound_isUnderwritten(), "LibCompound: operation not allowed when underwritten");
_;
}
/**
* @dev revert if the position is not underwritten
*/
modifier whenUnderwritten() {
require(compound_isUnderwritten(), "LibCompound: operation not allowed when underwritten");
_;
}
/**
* @inheritdoc IKCompound
*/
function compound_deposit(CToken _cToken, uint256 _amount) external payable override {
require(_cToken.isListed(), "KCompound: unsupported cToken address");
_cToken.pullAndApproveUnderlying(msg.sender, address(_cToken), _amount);
_cToken.mint(_amount);
}
/**
* @inheritdoc IKCompound
*/
function compound_withdraw(address payable _to, CToken _cToken, uint256 _amount) external override onlyOwner whenNotUnderwritten {
require(_cToken.isListed(), "KCompound: unsupported cToken address");
_cToken.redeemUnderlying(_amount);
_cToken.transferUnderlying(_to, _amount);
}
/**
* @inheritdoc IKCompound
*/
function compound_borrow(address payable _to, CToken _cToken, uint256 _amount) external override onlyOwner whenNotUnderwritten {
require(_cToken.isListed(), "KCompound: unsupported cToken address");
_cToken.borrow(_amount);
_cToken.transferUnderlying(_to, _amount);
}
/**
* @inheritdoc IKCompound
*/
function compound_repay(CToken _cToken, uint256 _amount) external payable override {
require(_cToken.isListed(), "KCompound: unsupported cToken address");
_cToken.pullAndApproveUnderlying(msg.sender, address(_cToken), _amount);
_cToken.repayBorrow(_amount);
}
/**
* @inheritdoc IKCompound
*/
function compound_preempt(
address _liquidator,
CToken _cTokenRepay,
uint _repayAmount,
CToken _cTokenCollateral
) external payable override onlyJITU returns (uint256) {
return LibCompound.preempt(_cTokenRepay, _liquidator, _repayAmount, _cTokenCollateral);
}
/**
* @inheritdoc IKCompound
*/
function compound_migrate(
address _account,
uint256 _amount,
address[] memory _collateralMarkets,
address[] memory _debtMarkets
) external override onlyJITU {
LibCompound.migrate(
_account,
_amount,
_collateralMarkets,
_debtMarkets
);
}
/**
* @inheritdoc IKCompound
*/
function compound_underwrite(CToken _cToken, uint256 _tokens) external payable override onlyJITU whenNotUnderwritten {
LibCompound.underwrite(_cToken, _tokens);
}
/**
* @inheritdoc IKCompound
*/
function compound_reclaim() external override onlyJITU whenUnderwritten {
LibCompound.reclaim();
}
/**
* @inheritdoc IKCompound
*/
function compound_enterMarkets(address[] memory _markets) external override onlyOwner {
LibCompound.enterMarkets(_markets);
}
/**
* @inheritdoc IKCompound
*/
function compound_exitMarket(address _market) external override onlyOwner whenNotUnderwritten {
LibCompound.exitMarket(_market);
}
/**
* @inheritdoc IKCompound
*/
function compound_balanceOfUnderlying(CToken _cToken) external override returns (uint256) {
return LibCompound.balanceOfUnderlying(_cToken);
}
/**
* @inheritdoc IKCompound
*/
function compound_balanceOf(CToken _cToken) external view override returns (uint256) {
return LibCompound.balanceOf(_cToken);
}
/**
* @inheritdoc IKCompound
*/
function compound_unhealth() external override view returns (uint256) {
return LibCompound.unhealth();
}
/**
* @inheritdoc IKCompound
*/
function compound_isUnderwritten() public override view returns (bool) {
return LibCompound.isUnderwritten();
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Compound.sol";
/**
* @title Library to simplify CToken interaction
* @author KeeperDAO
* @dev this library abstracts cERC20 and cEther interactions.
*/
library LibCToken {
using SafeERC20 for IERC20;
// Network: MAINNET
Comptroller constant COMPTROLLER = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
CEther constant CETHER = CEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5);
/**
* @notice checks if the given cToken is listed as a valid market on
* comptroller.
*
* @param _cToken cToken address
*/
function isListed(CToken _cToken) internal view returns (bool listed) {
(listed, , ) = COMPTROLLER.markets(address(_cToken));
}
/**
* @notice returns the given cToken's underlying token address.
*
* @param _cToken cToken address
*/
function underlying(CToken _cToken) internal view returns (address) {
if (address(_cToken) == address(CETHER)) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
} else {
return CErc20(address(_cToken)).underlying();
}
}
/**
* @notice redeems given amount of underlying tokens.
*
* @param _cToken cToken address
* @param _amount underlying token amount
*/
function redeemUnderlying(CToken _cToken, uint _amount) internal {
if (address(_cToken) == address(CETHER)) {
require(CETHER.redeemUnderlying(_amount) == 0, "failed to redeem ether");
} else {
require(CErc20(address(_cToken)).redeemUnderlying(_amount) == 0, "failed to redeem ERC20");
}
}
/**
* @notice borrows given amount of underlying tokens.
*
* @param _cToken cToken address
* @param _amount underlying token amount
*/
function borrow(CToken _cToken, uint _amount) internal {
if (address(_cToken) == address(CETHER)) {
require(CETHER.borrow(_amount) == 0, "failed to borrow ether");
} else {
require(CErc20(address(_cToken)).borrow(_amount) == 0, "failed to borrow ERC20");
}
}
/**
* @notice deposits given amount of underlying tokens.
*
* @param _cToken cToken address
* @param _amount underlying token amount
*/
function mint(CToken _cToken, uint _amount) internal {
if (address(_cToken) == address(CETHER)) {
CETHER.mint{ value: _amount }();
} else {
require(CErc20(address(_cToken)).mint(_amount) == 0, "failed to mint cERC20");
}
}
/**
* @notice repay given amount of underlying tokens.
*
* @param _cToken cToken address
* @param _amount underlying token amount
*/
function repayBorrow(CToken _cToken, uint _amount) internal {
if (address(_cToken) == address(CETHER)) {
CETHER.repayBorrow{ value: _amount }();
} else {
require(CErc20(address(_cToken)).repayBorrow(_amount) == 0, "failed to mint cERC20");
}
}
/**
* @notice repay given amount of underlying tokens on behalf of the borrower.
*
* @param _cToken cToken address
* @param _borrower borrower address
* @param _amount underlying token amount
*/
function repayBorrowBehalf(CToken _cToken, address _borrower, uint _amount) internal {
if (address(_cToken) == address(CETHER)) {
CETHER.repayBorrowBehalf{ value: _amount }(_borrower);
} else {
require(CErc20(address(_cToken)).repayBorrowBehalf(_borrower, _amount) == 0, "failed to mint cERC20");
}
}
/**
* @notice transfer given amount of underlying tokens to the given address.
*
* @param _cToken cToken address
* @param _to reciever address
* @param _amount underlying token amount
*/
function transferUnderlying(CToken _cToken, address payable _to, uint256 _amount) internal {
if (address(_cToken) == address(CETHER)) {
(bool success,) = _to.call{ value: _amount }("");
require(success, "Transfer Failed");
} else {
IERC20(CErc20(address(_cToken)).underlying()).safeTransfer(_to, _amount);
}
}
/**
* @notice approve given amount of underlying tokens to the given address.
*
* @param _cToken cToken address
* @param _spender spender address
* @param _amount underlying token amount
*/
function approveUnderlying(CToken _cToken, address _spender, uint256 _amount) internal {
if (address(_cToken) != address(CETHER)) {
IERC20 token = IERC20(CErc20(address(_cToken)).underlying());
token.safeIncreaseAllowance(_spender, _amount);
}
}
/**
* @notice pull approve given amount of underlying tokens to the given address.
*
* @param _cToken cToken address
* @param _from address from which the funds need to be pulled
* @param _to address to which the funds are approved to
* @param _amount underlying token amount
*/
function pullAndApproveUnderlying(CToken _cToken, address _from, address _to, uint256 _amount) internal {
if (address(_cToken) == address(CETHER)) {
require(msg.value == _amount, "failed to mint CETHER");
} else {
IERC20 token = IERC20(CErc20(address(_cToken)).underlying());
token.safeTransferFrom(_from, address(this), _amount);
token.safeIncreaseAllowance(_to, _amount);
}
}
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.8.6;
import "./LibCToken.sol";
import "../../LibHidingVault.sol";
/**
* @title Buffer accounting library for KCompound
* @author KeeperDAO
* @dev This library handles existing compound position migration.
* @dev This library implements all the logic for the individual kCompound
* position contracts.
*/
library LibCompound {
using LibCToken for CToken;
// KCOMPOUND_STORAGE_POSITION = keccak256("keeperdao.hiding-vault.compound.storage")
bytes32 constant KCOMPOUND_STORAGE_POSITION = 0x4f39ec42b5bbf77786567b02cbf043f85f0f917cbaa97d8df56931d77a999205;
/**
* State for LibCompound
*/
struct State {
uint256 bufferAmount;
CToken bufferToken;
}
/**
* @notice Load the LibCompound State for the given user
*/
function state() internal pure returns (State storage s) {
bytes32 position = KCOMPOUND_STORAGE_POSITION;
assembly {
s.slot := position
}
}
/**
* @dev this function will be called by the KeeperDAO's LiquidityPool.
* @param _account The address of the compund position owner.
* @param _tokens The amount that is being flash lent.
*/
function migrate(
address _account,
uint256 _tokens,
address[] memory _collateralMarkets,
address[] memory _debtMarkets
) internal {
// Enter markets
enterMarkets(_collateralMarkets);
// Migrate all the cToken Loans.
if (_debtMarkets.length != 0) migrateLoans(_debtMarkets, _account);
// Migrate all the assets from compound.
if (_collateralMarkets.length != 0) migrateFunds(_collateralMarkets, _account);
// repay CETHER
require(
CToken(_collateralMarkets[0]).transfer(msg.sender, _tokens),
"LibCompound: failed to return funds during migration"
);
}
/**
* @notice this function borrows required amount of ETH/ERC20 tokens,
* repays the ETH/ERC20 loan (if it exists) on behalf of the
* compound position owner.
*/
function migrateLoans(address[] memory _cTokens, address _account) private {
for (uint32 i = 0; i < _cTokens.length; i++) {
CToken cToken = CToken(_cTokens[i]);
uint256 borrowBalance = cToken.borrowBalanceCurrent(_account);
cToken.borrow(borrowBalance);
cToken.approveUnderlying(address(cToken), borrowBalance);
cToken.repayBorrowBehalf(_account, borrowBalance);
}
}
/**
* @notice transfer all the assets from the account.
*/
function migrateFunds(address[] memory _cTokens, address _account) private {
for (uint32 i = 0; i < _cTokens.length; i++) {
CToken cToken = CToken(_cTokens[i]);
require(cToken.transferFrom(
_account,
address(this),
cToken.balanceOf(_account)
), "LibCompound: failed to transfer CETHER");
}
}
/**
* @notice Prempt liquidation for positions underwater if the provided
* buffer is not considered on the Compound Protocol.
*
* @param _liquidator The address of the liquidator.
* @param _cTokenRepaid The repay cToken address.
* @param _repayAmount The amount that should be repaid.
* @param _cTokenCollateral The collateral cToken address.
*/
function preempt(
CToken _cTokenRepaid,
address _liquidator,
uint _repayAmount,
CToken _cTokenCollateral
) internal returns (uint256) {
// Check whether the user's position is liquidatable, and if it is
// return the amount of tokens that can be seized for the given loan,
// token pair.
uint seizeTokens = seizeTokenAmount(
address(_cTokenRepaid),
address(_cTokenCollateral),
_repayAmount
);
// This is a preemptive liquidation, so it would just repay the given loan
// and seize the corresponding amount of tokens.
_cTokenRepaid.pullAndApproveUnderlying(_liquidator, address(_cTokenRepaid), _repayAmount);
_cTokenRepaid.repayBorrow(_repayAmount);
require(_cTokenCollateral.transfer(_liquidator, seizeTokens), "LibCompound: failed to transfer cTokens");
return seizeTokens;
}
/**
* @notice Allows JITU to underwrite this contract, by providing cTokens.
*
* @param _cToken The address of the token.
* @param _tokens The tokens being transferred.
*/
function underwrite(CToken _cToken, uint256 _tokens) internal {
require(_tokens * 3 <= _cToken.balanceOf(address(this)),
"LibCompound: underwrite pre-conditions not met");
State storage s = state();
s.bufferToken = _cToken;
s.bufferAmount = _tokens;
blacklistCTokens();
}
/**
* @notice Allows JITU to reclaim the cTokens it provided.
*/
function reclaim() internal {
State storage s = state();
require(s.bufferToken.transfer(msg.sender, s.bufferAmount), "LibCompound: failed to return cTokens");
s.bufferToken = CToken(address(0));
s.bufferAmount = 0;
whitelistCTokens();
}
/**
* @notice Blacklist all the collateral assets.
*/
function blacklistCTokens() internal {
address[] memory cTokens = LibCToken.COMPTROLLER.getAssetsIn(address(this));
for (uint32 i = 0; i < cTokens.length; i++) {
LibHidingVault.state().recoverableTokensBlacklist[cTokens[i]] = true;
}
}
/**
* @notice Whitelist all the collateral assets.
*/
function whitelistCTokens() internal {
address[] memory cTokens = LibCToken.COMPTROLLER.getAssetsIn(address(this));
for (uint32 i = 0; i < cTokens.length; i++) {
LibHidingVault.state().recoverableTokensBlacklist[cTokens[i]] = false;
}
}
/**
* @notice check whether the position is liquidatable,
* if it is calculate the amount of tokens
* that can be seized.
*
* @param cTokenRepaid the token that is being repaid.
* @param cTokenSeized the token that is being seized.
* @param repayAmount the amount being repaid.
*
* @return the amount of tokens that need to be seized.
*/
function seizeTokenAmount(
address cTokenRepaid,
address cTokenSeized,
uint repayAmount
) internal returns (uint) {
State storage s = state();
// accrue interest
require(CToken(cTokenRepaid).accrueInterest() == 0, "LibCompound: failed to accrue interest on cTokenRepaid");
require(CToken(cTokenSeized).accrueInterest() == 0, "LibCompound: failed to accrue interest on cTokenSeized");
// The borrower must have shortfall in order to be liquidatable
(uint err, , uint shortfall) = LibCToken.COMPTROLLER.getHypotheticalAccountLiquidity(address(this), address(s.bufferToken), s.bufferAmount, 0);
require(err == 0, "LibCompound: failed to get account liquidity");
require(shortfall != 0, "LibCompound: insufficient shortfall to liquidate");
// The liquidator may not repay more than what is allowed by the closeFactor
uint borrowBalance = CToken(cTokenRepaid).borrowBalanceStored(address(this));
uint maxClose = mulScalarTruncate(LibCToken.COMPTROLLER.closeFactorMantissa(), borrowBalance);
require(repayAmount <= maxClose, "LibCompound: repay amount cannot exceed the max close amount");
// Calculate the amount of tokens that can be seized
(uint errCode2, uint seizeTokens) = LibCToken.COMPTROLLER
.liquidateCalculateSeizeTokens(cTokenRepaid, cTokenSeized, repayAmount);
require(errCode2 == 0, "LibCompound: failed to calculate seize token amount");
// Check that the amount of tokens being seized is less than the user's
// cToken balance
uint256 seizeTokenCollateral = CToken(cTokenSeized).balanceOf(address(this));
if (cTokenSeized == address(s.bufferToken)) {
seizeTokenCollateral = seizeTokenCollateral - s.bufferAmount;
}
require(seizeTokenCollateral >= seizeTokens, "LibCompound: insufficient liquidity");
return seizeTokens;
}
/**
* @notice calculates the collateral value of the given cToken amount.
* @dev collateral value means the amount of loan that can be taken without
* falling below the collateral requirement.
*
* @param _cToken the compound token we are calculating the collateral for.
* @param _tokens number of compound tokens.
*
* @return max borrow value for the given compound tokens in USD.
*/
function collateralValueInUSD(CToken _cToken, uint256 _tokens) internal view returns (uint256) {
// read the exchange rate from the cToken
uint256 exchangeRate = _cToken.exchangeRateStored();
// read the collateralFactor from the LibCToken.COMPTROLLER
(, uint256 collateralFactor, ) = LibCToken.COMPTROLLER.markets(address(_cToken));
// read the underlying token prive from the Compound's oracle
uint256 oraclePrice = LibCToken.COMPTROLLER.oracle().getUnderlyingPrice(_cToken);
require(oraclePrice != 0, "LibCompound: failed to get underlying price from the oracle");
return mulExp3AndScalarTruncate(collateralFactor, exchangeRate, oraclePrice, _tokens);
}
/**
* @notice Calculate the given cToken's underlying token balance of the caller.
*
* @param _cToken The address of the cToken contract.
*
* @return Outstanding balance in the given token.
*/
function balanceOfUnderlying(CToken _cToken) internal returns (uint256) {
return mulScalarTruncate(_cToken.exchangeRateCurrent(), balanceOf(_cToken));
}
/**
* @notice Calculate the given cToken's balance of the caller.
*
* @param _cToken The address of the cToken contract.
*
* @return Outstanding balance of the given token.
*/
function balanceOf(CToken _cToken) internal view returns (uint256) {
State storage s = state();
uint256 cTokenBalance = _cToken.balanceOf(address(this));
if (s.bufferToken == _cToken) {
cTokenBalance -= s.bufferAmount;
}
return cTokenBalance;
}
/**
* @notice new markets can be entered by calling this function.
*/
function enterMarkets(address[] memory _cTokens) internal {
uint[] memory retVals = LibCToken.COMPTROLLER.enterMarkets(_cTokens);
for (uint i; i < retVals.length; i++) {
require(retVals[i] == 0, "LibCompound: failed to enter market");
}
}
/**
* @notice existing markets can be exited by calling this function
*/
function exitMarket(address _cToken) internal {
require(
LibCToken.COMPTROLLER.exitMarket(_cToken) == 0,
"LibCompound: failed to exit a market"
);
}
/**
* @notice unhealth of the given account, the position is underwater
* if this value is greater than 100
* @dev if the account is empty, this fn returns an unhealth of 0
*
* @return unhealth of the account
*/
function unhealth() internal view returns (uint256) {
uint256 totalCollateralValue;
State storage s = state();
address[] memory cTokens = LibCToken.COMPTROLLER.getAssetsIn(address(this));
// calculate the total collateral value of this account
for (uint i = 0; i < cTokens.length; i++) {
totalCollateralValue = totalCollateralValue + collateralValue(CToken(cTokens[i]));
}
if (totalCollateralValue > 0) {
uint256 totalBorrowValue;
// get the account liquidity
(uint err, uint256 liquidity, uint256 shortFall) =
LibCToken.COMPTROLLER.getHypotheticalAccountLiquidity(
address(this),
address(s.bufferToken),
s.bufferAmount,
0
);
require(err == 0, "LibCompound: failed to calculate account liquidity");
if (liquidity == 0) {
totalBorrowValue = totalCollateralValue + shortFall;
} else {
totalBorrowValue = totalCollateralValue - liquidity;
}
return (totalBorrowValue * 100) / totalCollateralValue;
}
return 0;
}
/**
* @notice calculate the collateral value of the given cToken
*
* @return collateral value of the given cToken
*/
function collateralValue(CToken cToken) internal view returns (uint256) {
State storage s = state();
uint256 bufferAmount;
if (s.bufferToken == cToken) {
bufferAmount = s.bufferAmount;
}
return collateralValueInUSD(
cToken,
cToken.balanceOf(address(this)) - bufferAmount
);
}
/**
* @notice checks whether the given position is underwritten or not
*
* @return underwritten status of the caller
*/
function isUnderwritten() internal view returns (bool) {
State storage s = state();
return (s.bufferAmount != 0 && s.bufferToken != CToken(address(0)));
}
/**
* @notice checks the owner of this vault
*
* @return address of the owner
*/
function owner() internal view returns (address) {
return LibHidingVault.state().nft.ownerOf(uint256(uint160(address(this))));
}
/** Exponential Math */
function mulExp3AndScalarTruncate(uint256 a, uint256 b, uint256 c, uint256 d) internal pure returns (uint256) {
return mulScalarTruncate(mulExp(mulExp(a, b), c), d);
}
function mulExp(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a * _b + 5e17) / 1e18;
}
function mulScalarTruncate(uint256 _a, uint256 _b) internal pure returns (uint256) {
return (_a * _b) / 1e18;
}
}
interface Weth {
function balanceOf(address owner) external view returns (uint);
function deposit() external payable;
function withdraw(uint256 _amount) external;
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address spender, uint256 amount) external returns (bool);
}
interface NFT {
function jitu() external view returns (address);
function ownerOf(uint256 _tokenID) external view returns (address);
}
| Calculate the given cToken's underlying token balance of the caller. _cToken The address of the cToken contract. return Outstanding balance in the given token./ | function balanceOfUnderlying(CToken _cToken) internal returns (uint256) {
return mulScalarTruncate(_cToken.exchangeRateCurrent(), balanceOf(_cToken));
}
| 118,223 |
./full_match/42/0x864e8728F9c6f4eEB9750FBC77F6c47F1Df5dd7F/sources/browser/test.sol | bool isInvalid = bytes(name).length == 0 && bytes(symbol).length == 0 && decimals == 0; !isInvalid | function getTokenDetails(address[] memory tknAddress) public view returns (Details[] memory) {
Details[] memory details = new Details[](tknAddress.length);
for (uint i = 0; i < tknAddress.length; i++) {
TokenInterface token = TokenInterface(tknAddress[i]);
string memory name = token.name();
string memory symbol = token.symbol();
uint8 decimals = token.decimals();
details[i] = Details(
name,
symbol,
decimals
);
}
return details;
}
| 16,215,044 |
/* SPDX-License-Identifier: MIT
@**********@ @*********** @*********** @*********** #***@ @***( *********** @**********# @*********** @*********** @*******@ .***********
@***@@@@***@ @***@@@@@@@@ @***@@@@@@@@ @***@@@@@@@@ #***@ @***( ****@@@@@@@ @@@@****@@@@ @***@@@@**** @***@@@@**** @***@@@@@@@@ [email protected]@@@@@@%***
@*** ***@ @***@ @***@ @***@ #***@ @***( **** **** @***@ **** @***@ **** @***@ (*** @***
@******* @******* @*********** @***@ #***@ @***( *******@ **** @***@ **** @*********** @***@ (*** %***@
@***@@@@@@@@ @***@@@@ @@@@@@@@**** @***@ #***@ @***( ****@@@@ **** @***@ **** @***@@@@**** @***@ (*** [email protected]@@@@@@@
@*** ***@ @***@ **** @***@ #***@ @***( **** **** @***@ **** @***@ **** @***@ (*** .***&
@*** ***@ @*********** @*********** @*********** #***********( *********** **** @*********** @***@ **** @*******@ .***********
@@@@ @@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ #@@@@@@@@@@@( @@@@@@@@@@@ @@@@ @@@@@@@@@@@@ @@@@@ @@@@ @@@@@@@@@ [email protected]@@@@@@@@@@
*/
/**
* @title Rescue Toadz
* @author Vladimir Haltakov (@haltakov)
* @notice ERC1155 contract for a collection of Ukrainian themed Rescue Toadz
* @notice All proceeds from minting and capturing tokens are donated for humanitarian help for Ukraine via Unchain (0x10E1439455BD2624878b243819E31CfEE9eb721C).
* @notice The contract represents two types of tokens: single edition tokens (id <= SINGLE_EDITIONS_SUPPLY) and multiple edition POAP tokens (id > SINGLE_EDITIONS_SUPPLY)
* @notice Only the single edition tokens are allowed to be minted or captured.
* @notice The contract implements a special function capture, that allows anybody to transfer a single edition token to their wallet by matching or increasing the last donation.
*/
pragma solidity ^0.8.12;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract RescueToadz is ERC1155, Ownable, Pausable, ERC1155Supply {
using Strings for uint256;
// Number of single edition tokens. For each single edition token, there will be a corresponding multiple edition token.
uint256 public constant SINGLE_EDITIONS_SUPPLY = 18;
// Mint price
uint256 public constant MINT_PRICE = 10000000 gwei;
// Address of Unchain Ukraine where all funds will be donated for humanitarian help (see https://unchain.fund/ for details)
address public constant CHARITY_ADDRESS =
0x10E1439455BD2624878b243819E31CfEE9eb721C;
// The last price a token was minted or captured for
mapping(uint256 => uint256) private _lastPrice;
// The last owner of a token. This applies only for single edition tokens
mapping(uint256 => address) private _ownerOf;
/**
* @dev Default constructor
*/
constructor()
ERC1155("ipfs://QmXRvBcDGpGYVKa7DpshY4UJQrSHH4ArN2AotHHjDS3BHo/")
{}
/**
* @dev Name of the token
*/
function name() external pure returns (string memory) {
return "Rescue Toadz";
}
/**
* @notice Only allowed for tokens with id <= SINGLE_EDITIONS_SUPPLY
* @notice Only one token for every id <= SINGLE_EDITIONS_SUPPLY is allowed to be minted (similar to an ERC721 token)
* @dev Mint a token
* @param tokenId id of the token to be minted
*/
function mint(uint256 tokenId) external payable whenNotPaused {
require(
tokenId <= SINGLE_EDITIONS_SUPPLY,
"Cannot mint token with id greater than SINGLE_EDITIONS_SUPPLY"
);
require(tokenId > 0, "Cannot mint token 0");
require(!exists(tokenId), "Token already minted");
require(msg.value >= MINT_PRICE, "Not enough funds to mint token");
_ownerOf[tokenId] = msg.sender;
_lastPrice[tokenId] = msg.value;
_mint(msg.sender, tokenId, 1, "");
payable(CHARITY_ADDRESS).transfer(msg.value);
}
/**
* @notice Only allowed for tokens with id <= SINGLE_EDITIONS_SUPPLY
* @notice This function allows transferring a token from another wallet by paying more than the last price paid
* @notice This function will mint a POAP token (id > SINGLE_EDITIONS_SUPPLY) in the wallet from which the token is captured
* @dev Capture a token from another wallet
* @param tokenId id of the token to be captured
*/
function capture(uint256 tokenId) external payable whenNotPaused {
require(
tokenId <= SINGLE_EDITIONS_SUPPLY,
"Cannot capture a token with id greater than SINGLE_EDITIONS_SUPPLY"
);
require(exists(tokenId), "Cannot capture a token that is not minted");
require(
msg.value >= _lastPrice[tokenId],
"Cannot capture a token without paying at least the last price"
);
address lastOwner = _ownerOf[tokenId];
_ownerOf[tokenId] = msg.sender;
_lastPrice[tokenId] = msg.value;
_safeTransferFrom(lastOwner, msg.sender, tokenId, 1, "");
_mint(lastOwner, SINGLE_EDITIONS_SUPPLY + tokenId, 1, "");
payable(CHARITY_ADDRESS).transfer(msg.value);
}
/**
* @notice Only allowed for tokens with id <= SINGLE_EDITIONS_SUPPLY
* @dev Get the last price a token was minted or captured
* @param tokenId id of the token to check
*/
function lastPrice(uint256 tokenId) external view returns (uint256) {
require(
tokenId <= SINGLE_EDITIONS_SUPPLY,
"Cannot get the last price of a token with id greater than SINGLE_EDITIONS_SUPPLY"
);
if (!exists(tokenId)) {
return 0;
}
return _lastPrice[tokenId];
}
/**
* @notice Only allowed for tokens with id <= SINGLE_EDITIONS_SUPPLY, because they are guaranteed to have a single edition
* @dev Get the owner of a token with an id <= SINGLE_EDITIONS_SUPPLY
* @param tokenId id of the token to get the owner of
*/
function ownerOf(uint256 tokenId) external view returns (address) {
require(
tokenId <= SINGLE_EDITIONS_SUPPLY,
"Cannot get the owner for token with id greater than SINGLE_EDITIONS_SUPPLY"
);
if (!exists(tokenId)) {
return address(0);
}
return _ownerOf[tokenId];
}
/**
* @notice Override the setApprovalForAll function to prevent selling the NFT on exchanges
*/
function setApprovalForAll(address, bool) public virtual override {
revert("setApprovalForAll is not supported");
}
/**
* @dev Get the URI of a token
* @param tokenId id of the token
*/
function uri(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(exists(tokenId), "URI query for nonexistent token");
string memory baseURI = super.uri(tokenId);
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
/**
* @dev Change the base URI
* @param newuri the new URI
*/
function setURI(string memory newuri) external onlyOwner {
_setURI(newuri);
}
/**
* @dev Pause the contract
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev Unpause the contract
*/
function unpause() external onlyOwner {
_unpause();
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal override(ERC1155, ERC1155Supply) whenNotPaused {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol)
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev Extension of ERC1155 that adds tracking of total supply per id.
*
* Useful for scenarios where Fungible and Non-fungible tokens have to be
* clearly identified. Note: While a totalSupply of 1 might mean the
* corresponding is an NFT, there is no guarantees that no other token with the
* same id are not going to be minted.
*/
abstract contract ERC1155Supply is ERC1155 {
mapping(uint256 => uint256) private _totalSupply;
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates whether any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return ERC1155Supply.totalSupply(id) > 0;
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (from == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i];
}
}
if (to == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] -= amounts[i];
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/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);
} | Override the setApprovalForAll function to prevent selling the NFT on exchanges/ | function setApprovalForAll(address, bool) public virtual override {
revert("setApprovalForAll is not supported");
}
| 5,708,724 |
./full_match/1/0xefaCa6Fc316B3B2Aa6c55FF5E02a62A85d4391e8/sources/contracts/modules/core/VaultModule.sol | @inheritdoc IVaultModule/ | function getVaultCollateralRatio(
uint128 poolId,
address collateralType
) external override returns (uint256) {
return Pool.load(poolId).currentVaultCollateralRatio(collateralType);
}
| 16,516,931 |
pragma solidity ^0.4.18;
import "./ConvertLib.sol";
/// @title A library that houses the data structures used by the engine
/// @author Aaron Kendall
/// @notice Not all data structures have been used yet
/// @dev There are probably more efficient layout for these structures
library WonkaLib {
/// @title A data structure that holds metadata which represents an Attribute (i.e., a unique point of data in a user's record)
/// @author Aaron Kendall
/// @notice Not all struct members are currently used
struct WonkaAttr {
uint attrId;
bytes32 attrName;
uint maxLength;
bool maxLengthTruncate;
uint maxNumValue;
string defaultValue;
bool isString;
bool isDecimal;
bool isNumeric;
bool isValue;
}
/// @title A data structure that represents a Source (i.e., a provide of a record)
/// @author Aaron Kendall
/// @notice This structure isn't currently used
struct WonkaSource {
int sourceId;
bytes32 sourceName;
bytes32 status;
}
/// @title A data structure that represents a rule (i.e., a logical unit for testing the validity of a collection of Attribute values [or what we call a record])
/// @author Aaron Kendall
/// @notice Only one Attribute can be targeted now, but in the future, rules should be able to target multiple Attributes
/// @dev
struct WonkaRule {
uint ruleId;
bytes32 name;
uint ruleType;
WonkaAttr targetAttr;
string ruleValue;
}
/// @title A data structure that represents a set of rules
/// @author Aaron Kendall
/// @notice
/// @dev The actual rules are kept outside the struct since I'm currently unsure about the costs to keeping it inside
struct WonkaRuleSet {
bytes32 ruleSetId;
// WonkaRule[] ruleSetCollection;
bool andOp;
bool failImmediately;
bool isValue;
}
}
/// @title A simple business rules engine that will test the validity of a provided data record against a set of caller-defined rules
/// @author Aaron Kendall
/// @notice Some Attributes are currently hard-coded in the constructor, by default. Also, a record can only be tested by a ruler (i.e., owner of a RuleSet).
/// @dev The efficiency (i.e., the rate of spent gas) of the contract may not yet be optimal
contract WonkaEngine {
// using WonkaLib for *;
uint constant MAX_ARGS = 32;
enum RuleTypes { IsEqual, IsLessThan, IsGreaterThan, MAX_TYPE }
RuleTypes constant defaultType = RuleTypes.IsEqual;
address public rulesMaster;
uint public attrCounter;
uint public ruleCounter;
mapping(bytes32 => WonkaLib.WonkaAttr) private attrMap;
WonkaLib.WonkaAttr[] public attributes;
// This declares a state variable that stores a `RuleSet` struct for each possible address.
mapping(address => WonkaLib.WonkaRuleSet) private rulers;
// A dynamically-sized array of `RuleSet` structs.
WonkaLib.WonkaRuleSet[] public rulesets;
mapping(bytes32 => WonkaLib.WonkaRule[]) private allRules;
mapping(address => mapping(bytes32 => string)) currentRecords;
/// @author Aaron Kendall
/// @notice The engine's constructor
/// @dev Some Attributes are created by default, but in future versions, Attributes can be created by the contract's user
function WonkaEngine() public {
rulesMaster = msg.sender;
attributes.push(WonkaLib.WonkaAttr({
attrId: 1,
attrName: "Title",
maxLength: 256,
maxLengthTruncate: true,
maxNumValue: 0,
defaultValue: "Blank",
isString: true,
isDecimal: false,
isNumeric: false,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attributes.push(WonkaLib.WonkaAttr({
attrId: 2,
attrName: "Price",
maxLength: 128,
maxLengthTruncate: false,
maxNumValue: 1000000,
defaultValue: "000",
isString: false,
isDecimal: false,
isNumeric: true,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attributes.push(WonkaLib.WonkaAttr({
attrId: 3,
attrName: "PageAmount",
maxLength: 256,
maxLengthTruncate: false,
maxNumValue: 1000,
defaultValue: "",
isString: false,
isDecimal: false,
isNumeric: true,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
attrCounter = attributes.length + 1;
}
/// @author Aaron Kendall
/// @notice This function will create an Attribute, which defines a data point that can be poulated on a user's record. Only the RuleMaster (i.e., the contract instance's creator) can create a RuleSet for a user.
/// @dev An Attribute can only be defined once.
/// @param pAttrName The name of the new Attribute
/// @param pMaxLen The maximum string length of a value for this Attribute
/// @param pMaxNumVal The maximum numeric value for this Attribute
/// @param pDefVal The default value that should be given for this Attribute on every given record. (NOTE: Currently, this value is not being used.)
/// @param pIsStr The indicator for whether or not this Attribute is an instance of a string
/// @param pIsNum The indicator for whether or not this Attribute is an instance of a numeric
/// @return
function addAttribute(bytes32 pAttrName, uint pMaxLen, uint pMaxNumVal, string pDefVal, bool pIsStr, bool pIsNum) public {
require(msg.sender == rulesMaster);
require(attrMap[pAttrName].isValue == false);
bool maxLenTrun = (pMaxLen > 0);
attributes.push(WonkaLib.WonkaAttr({
attrId: attrCounter++,
attrName: pAttrName,
maxLength: pMaxLen,
maxLengthTruncate: maxLenTrun,
maxNumValue: pMaxNumVal,
defaultValue: pDefVal,
isString: pIsStr,
isDecimal: false,
isNumeric: pIsNum,
isValue: true
}));
attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1];
}
/// @author Aaron Kendall
/// @notice This function will create a RuleSet, which is the container for a set of Rules created/owned by a user. Only the RuleMaster (i.e., the contract instance's creator) can create a RuleSet for a user.
/// @dev Users are currently allowed only one RuleSet.
/// @param ruler The owner (i.e., the user's address) of the new RuleSet
/// @param ruleSetName The name given to the new RuleSet
/// @param useAndOperator Flag to indicate to use the 'AND' operator on rules if true and to use the 'OR' operator if false
/// @param flagFailImmediately Flag to indicate whether or not the first rule failure should cause the 'execute' function to throw
/// @return
function addRuleSet(address ruler, bytes32 ruleSetName, bool useAndOperator, bool flagFailImmediately) public {
// require((msg.sender == chairperson) && !voters[voter].voted && (voters[voter].weight == 0));
require(msg.sender == rulesMaster);
rulesets.push(WonkaLib.WonkaRuleSet({
ruleSetId: ruleSetName,
andOp: useAndOperator,
failImmediately: flagFailImmediately,
// ruleSetCollection: new WonkaLib.WonkaRule[](0),
isValue: true
}));
rulers[ruler] = rulesets[rulesets.length-1];
}
/// @author Aaron Kendall
/// @notice This function will add a Rule to the RuleSet owned by 'ruler'. Only 'ruler' or the RuleMaster can add a rule.
/// @dev The type of rules are limited to the enum RuleTypes
/// @param ruler The owner (i.e., the user's address) of the RuleSet to which we are adding a rule
/// @param ruleName The name given to the new Rule
/// @param attrName The record Attribute that the rule is testing
/// @param rType The type of operation for the rule
/// @param rVal The value against which the rule is pitting the Attribute of the record [like Attribute("Price").Value > 500]
/// @return
function addRule(address ruler, bytes32 ruleName, bytes32 attrName, uint rType, string rVal) public {
require((msg.sender == ruler) || (msg.sender == rulesMaster));
require(rulers[ruler].isValue);
require(attrMap[attrName].isValue);
require(rType < uint(RuleTypes.MAX_TYPE));
// WonkaLib.WonkaRuleSet memory foundRuleset = rulers[ruler];
// WonkaLib.WonkaAttr memory foundAttr = attrMap[attrName];
// uint memory tmpRuleId = ruleCounter++;
allRules[rulers[ruler].ruleSetId].push(WonkaLib.WonkaRule({
ruleId: ruleCounter++,
name: ruleName,
ruleType: rType,
targetAttr: attrMap[attrName],
ruleValue: rVal
}));
}
/// @author Aaron Kendall
/// @notice Copied this code snippet from a StackOverflow post from the user "eth"
/// @dev This method cannot exist in a different library due to the inflexibility of strings passed across contracts
/// @param x The bytes32 that needs to be converted into a string
/// @return The string that was converted from the provided bytes32
function bytes32ToString(bytes32 x) private pure returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
/// @author Aaron Kendall
/// @notice This function will use the Attribute metadata to do a simple check of the provided value, like ensuring a Price value is actually numeric
/// @dev Static memory load of more than 32 bytes requested?
/// @param checkAttr The Attribute metadata used for analysis
/// @param checkVal The record value being analyzed in accordance with the Attribute
/// @return bool that indicates whether the 'checkVal' is a valid instance of Attribute
function checkCurrValue(WonkaLib.WonkaAttr checkAttr, string checkVal) private pure returns(bool valuePasses) {
require(checkAttr.attrName.length != 0);
bytes memory testValue = bytes(checkVal);
require(testValue.length != 0);
if (checkAttr.maxLength > 0) {
if (checkAttr.maxLengthTruncate) {
// Do something here
}
// if (checkAttr.defaultValue)
require(testValue.length < checkAttr.maxLength);
}
if (checkAttr.isNumeric) {
uint testNum = 0;
testNum = ConvertLib.parseInt(checkVal, 0);
require(testNum > 0);
if (checkAttr.maxNumValue > 0)
require(testNum < checkAttr.maxNumValue);
}
valuePasses = true;
}
/// @author Aaron Kendall
/// @notice Should be used just for testing by the user
/// @dev
/// @param ruler The owner (i.e., the user's address) of the record which we want to test
/// @param targetRules The rules being invoked against the ruler's record
/// @return bool that indicates whether the record of 'ruler' is valid according to the Attributes mentioned in 'targetRules'
function checkRecordBeta(address ruler, WonkaLib.WonkaRule[] targetRules) private view returns(bool recordPasses) {
require(rulers[ruler].isValue);
for (uint idx; idx < targetRules.length; idx++) {
WonkaLib.WonkaRule memory tempRule = targetRules[idx];
string memory tempValue = currentRecords[ruler][tempRule.targetAttr.attrName];
// require(checkCurrValue(tempRule.targetAttr, tempRule.ruleType, tempValue));
checkCurrValue(tempRule.targetAttr, tempValue);
}
recordPasses = true;
}
/// @author Aaron Kendall
/// @notice This method will test a record's values against the Attribute metadata. It should only be called once all of the Attribute values are set for the ruler's current record.
/// @dev Perhaps the variables 'tempRule' and 'tempValue' are a waste of gas?
/// @param ruler The owner of the record and the RuleSet being invoked
/// @return bool that indicates whether the record of 'ruler' is valid, according to the metadata of Attributes mentioned in the RuleSet of 'ruler'
function checkRecord(address ruler) public view returns(bool recordPasses) {
require(rulers[ruler].isValue);
WonkaLib.WonkaRule[] memory targetRules = allRules[rulers[ruler].ruleSetId];
for (uint idx; idx < targetRules.length; idx++) {
WonkaLib.WonkaRule memory tempRule = targetRules[idx];
string memory tempValue = currentRecords[ruler][tempRule.targetAttr.attrName];
// require(checkCurrValue(tempRule.targetAttr, tempRule.ruleType, tempValue));
checkCurrValue(tempRule.targetAttr, tempValue);
}
recordPasses = true;
}
/// @author Aaron Kendall
/// @notice Should be used just for testing by the user
/// @dev This method is just a proxy to call the 'parseInt()' method
/// @param origVal The 'string' which we want to convert into a 'uint'
/// @return uint that contains the conversion of the provided string
function convertStringToNumber(string origVal) public pure returns (uint) {
uint convertVal = 123;
convertVal = ConvertLib.parseInt(origVal, 0);
return convertVal;
}
/// @author Aaron Kendall
/// @notice This method will actually process the current record by invoking the RuleSet. Before this method is called, all record data should be set and all rules should be added.
/// @dev The efficiency (i.e., the rate of spent gas) of the method may not yet be optimal
/// @param ruler The owner of the record and the RuleSet being invoked
/// @return bool that indicates whether the record of 'ruler' is valid, according to both the Attributes and the RuleSet
function execute(address ruler) public view returns (bool executeSuccess) {
require(rulers[ruler].isValue);
executeSuccess = true;
WonkaLib.WonkaRule[] memory targetRules = allRules[rulers[ruler].ruleSetId];
// require(attrNames.length == attrValues.length);
// executeSuccess = rulers[ruler].isValue;
checkRecordBeta(ruler, targetRules);
uint testNumValue = 0;
uint ruleNumValue = 0;
bool tempResult = false;
bool useAndOp = rulers[ruler].andOp;
bool failImmediately = rulers[ruler].failImmediately;
// Now invoke the rules
for (uint idx = 0; idx < targetRules.length; idx++) {
tempResult = true;
string memory tempValue = (currentRecords[ruler])[targetRules[idx].targetAttr.attrName];
if (targetRules[idx].targetAttr.isNumeric) {
testNumValue = ConvertLib.parseInt(tempValue, 0);
ruleNumValue = ConvertLib.parseInt(targetRules[idx].ruleValue, 0);
}
if (uint(RuleTypes.IsEqual) == targetRules[idx].ruleType) {
if (targetRules[idx].targetAttr.isNumeric) {
tempResult = (testNumValue == ruleNumValue);
} else {
tempResult = (keccak256(tempValue) == keccak256(targetRules[idx].ruleValue));
}
} else if (uint(RuleTypes.IsLessThan) == targetRules[idx].ruleType) {
if (targetRules[idx].targetAttr.isNumeric)
tempResult = (testNumValue < ruleNumValue);
} else if (uint(RuleTypes.IsGreaterThan) == targetRules[idx].ruleType) {
if (targetRules[idx].targetAttr.isNumeric)
tempResult = (testNumValue > ruleNumValue);
}
if (failImmediately)
require(tempResult);
if (useAndOp)
executeSuccess = (executeSuccess && tempResult);
else
executeSuccess = (executeSuccess || tempResult);
}
}
/// @author Aaron Kendall
/// @notice Retrieves the name of the attribute at the index
/// @dev Should be used just for testing
/// @param idx The index of the Attribute being examined
/// @return bytes32 that contains the name of the specified Attribute
function getAttributeName(uint idx) public view returns(bytes32) {
return attributes[idx].attrName;
}
/// @author Aaron Kendall
/// @notice Retrieves the value of the record that belongs to the user (i.e., 'ruler')
/// @dev Should be used just for testing
/// @param ruler The owner of the record
/// @param key The name of the Attribute in the record
/// @return string that contains the Attribute value from the record that belongs to 'ruler'
function getValueOnRecord(address ruler, bytes32 key) public view returns(string) {
require(rulers[ruler].isValue);
return (currentRecords[ruler])[key];
}
/// @author Aaron Kendall
/// @notice Retrieves the value of the record that belongs to the user (i.e., 'ruler')
/// @dev Should be used just for testing
/// @param ruler The owner of the record
/// @param key The name of the Attribute in the record
/// @return uint that contains the Attribute value from the record that belongs to 'ruler'
function getValueOnRecordAsNum(address ruler, bytes32 key) public view returns(uint) {
uint currValue = 0;
require(rulers[ruler].isValue);
currValue = ConvertLib.parseInt((currentRecords[ruler])[key], 0);
return currValue;
}
/// @author Aaron Kendall
/// @notice Retrieves the number of current Attributes
/// @dev Should be used just for testing
/// @return uint that indicates the num of current Attributes
function getNumberOfAttributes() public view returns(uint) {
return attributes.length;
}
/// @author Aaron Kendall
/// @notice Retrieves the name of the indexed rule in the RuleSet of 'ruler'
/// @dev Should be used just for testing
/// @param ruler The owner of the RuleSet
/// @param idx The index of the Rule being examined
/// @return bytes32 that contains the name of the indexed Rule
function getRuleName(address ruler, uint idx) public view returns(bytes32) {
// require((msg.sender == ruler) || (msg.sender == rulesMaster));
require(rulers[ruler].isValue);
return allRules[rulers[ruler].ruleSetId][idx].name;
}
/// @author Aaron Kendall
/// @notice Retrieves the a verbose description of the rules that will be invoked by the RuleSet owned by 'ruler'
/// @dev Should be used just for testing, since it's likely an expensive operation in terms of gas
/// @param ruler The owner of the RuleSet whose rules we want to examine
/// @return string that contains the verbose description of the rules in the RuleSet
function getRulePlan(address ruler) public view returns (string) {
require(rulers[ruler].isValue);
string memory ruleReport = "\n";
WonkaLib.WonkaRule[] memory targetRules = allRules[rulers[ruler].ruleSetId];
// Now collect the rules
for (uint idx = 0; idx < targetRules.length; idx++) {
if (uint(RuleTypes.IsEqual) == targetRules[idx].ruleType) {
if (targetRules[idx].targetAttr.isNumeric) {
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be (numeric) equal to ", targetRules[idx].ruleValue);
} else {
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be (string) equal to ", targetRules[idx].ruleValue);
}
} else if (uint(RuleTypes.IsLessThan) == targetRules[idx].ruleType) {
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be less than ", targetRules[idx].ruleValue);
} else if (uint(RuleTypes.IsGreaterThan) == targetRules[idx].ruleType) {
ruleReport = strConcat(ruleReport, "\nAttribute(", bytes32ToString(targetRules[idx].targetAttr.attrName), ") must be greater than ", targetRules[idx].ruleValue);
}
}
ruleReport = strConcat(ruleReport, "\n");
return ruleReport;
}
/// @author Aaron Kendall
/// @notice Retrieves the name of the RuleSet of 'ruler'
/// @dev Should be used just for testing
/// @param ruler The owner of the RuleSet
/// @return bytes32 that contains the name of the RuleSet belonging to 'ruler'
function getRulesetName(address ruler) public view returns(bytes32) {
// require((msg.sender == ruler) || (msg.sender == rulesMaster));
require(rulers[ruler].isValue);
return rulers[ruler].ruleSetId;
}
/// @author Aaron Kendall
/// @notice This method will alter the operator used to evaluate the final result of all the rules executed together (i.e., AND vs. OR)
/// @dev This method can only invoked for a RuleSet (whose ID is the owner's account ID) by its owner or the contract's owner.
/// @param ruler The owner of the RuleSet
/// @param flagUseAndOp Flag indicating whether to 'AND' the rules (i.e., true) or to 'OR' the rules (i.e., false)
/// @return
function setRulesetEvalOp(address ruler, bool flagUseAndOp) public {
require((msg.sender == ruler) || (msg.sender == rulesMaster));
require(rulers[ruler].isValue);
rulers[ruler].andOp = flagUseAndOp;
}
/// @author Aaron Kendall
/// @notice This method populates the record of 'ruler' with a value that represents an instance of an Attribute
/// @dev This method does not yet check to see if the provided 'key' is the valid name of an Attribute. Is it worth the gas?
/// @param ruler The owner of the RuleSet
/// @param key The name of the Attribute for the value being inserted into the record
/// @param value The string to insert into the record
/// @return
function setValueOnRecord(address ruler, bytes32 key, string value) public {
require(rulers[ruler].isValue);
(currentRecords[ruler])[key] = value;
}
/// @author Aaron Kendall
/// @notice This method will concatenate 5 strings into one
/// @dev Copied from a code snippet on StackOverflow by Bertani from Oraclize. This method probably isn't gas-efficient, and it should probably only be used for testing.
/// @param _a The seed/base of the string concatenation
/// @param _b The second string to concatenate
/// @param _c The third string to concatenate
/// @param _d The fourth string to concatenate
/// @param _e The fifth string to concatenate
/// @return string that contains the aggregate of all strings that have been concatenated together
function strConcat(string _a, string _b, string _c, string _d, string _e) private pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) {
babcde[k++] = _bc[i];
}
for (i = 0; i < _bd.length; i++) {
babcde[k++] = _bd[i];
}
for (i = 0; i < _be.length; i++) {
babcde[k++] = _be[i];
}
return string(babcde);
}
/// @author Aaron Kendall
/// @notice This method will concatenate 4 strings into one
/// @dev Copied from a code snippet on StackOverflow by Bertani from Oraclize. This method probably isn't gas-efficient, and it should probably only be used for testing.
/// @param _a The seed/base of the string concatenation
/// @param _b The second string to concatenate
/// @param _c The third string to concatenate
/// @param _d The fourth string to concatenate
/// @return string that contains the aggregate of all strings that have been concatenated together
function strConcat(string _a, string _b, string _c, string _d) private pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
/// @author Aaron Kendall
/// @notice This method will concatenate 3 strings into one
/// @dev Copied from a code snippet on StackOverflow by Bertani from Oraclize. This method probably isn't gas-efficient, and it should probably only be used for testing.
/// @param _a The seed/base of the string concatenation
/// @param _b The second string to concatenate
/// @param _c The third string to concatenate
/// @return string that contains the aggregate of all strings that have been concatenated together
function strConcat(string _a, string _b, string _c) private pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
/// @author Aaron Kendall
/// @notice This method will concatenate 2 strings into one
/// @dev Copied from a code snippet on StackOverflow by Bertani from Oraclize. This method probably isn't gas-efficient, and it should probably only be used for testing.
/// @param _a The seed/base of the string concatenation
/// @param _b The second string to concatenate
/// @return string that contains the aggregate of all strings that have been concatenated together
function strConcat(string _a, string _b) private pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
}
| Aaron Kendall Should be used just for testing by the user ruler The owner (i.e., the user's address) of the record which we want to test targetRules The rules being invoked against the ruler's record return bool that indicates whether the record of 'ruler' is valid according to the Attributes mentioned in 'targetRules' require(checkCurrValue(tempRule.targetAttr, tempRule.ruleType, tempValue)); | function checkRecordBeta(address ruler, WonkaLib.WonkaRule[] targetRules) private view returns(bool recordPasses) {
require(rulers[ruler].isValue);
for (uint idx; idx < targetRules.length; idx++) {
WonkaLib.WonkaRule memory tempRule = targetRules[idx];
string memory tempValue = currentRecords[ruler][tempRule.targetAttr.attrName];
checkCurrValue(tempRule.targetAttr, tempValue);
}
recordPasses = true;
}
| 12,559,360 |
pragma solidity 0.5.17;
contract BondedSortitionPoolFactory {
/// @notice Creates a new bonded sortition pool instance.
/// @return Address of the new bonded sortition pool contract instance.
function createSortitionPool(
IStaking stakingContract,
IBonding bondingContract,
uint256 minimumStake,
uint256 initialMinimumBond,
uint256 poolWeightDivisor
) public returns (address) {
return
address(
new BondedSortitionPool(
stakingContract,
bondingContract,
minimumStake,
initialMinimumBond,
poolWeightDivisor,
msg.sender
)
);
}
}
library Branch {
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant LAST_SLOT = SLOT_COUNT - 1;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
////////////////////////////////////////////////////////////////////////////
/// @notice Calculate the right shift required
/// to make the 32 least significant bits of an uint256
/// be the bits of the `position`th slot
/// when treating the uint256 as a uint32[8].
///
/// @dev Not used for efficiency reasons,
/// but left to illustrate the meaning of a common pattern.
/// I wish solidity had macros, even C macros.
function slotShift(uint256 position) internal pure returns (uint256) {
return position * SLOT_WIDTH;
}
/// @notice Return the `position`th slot of the `node`,
/// treating `node` as a uint32[32].
function getSlot(uint256 node, uint256 position)
internal
pure
returns (uint256)
{
uint256 shiftBits = position * SLOT_WIDTH;
// Doing a bitwise AND with `SLOT_MAX`
// clears all but the 32 least significant bits.
// Because of the right shift by `slotShift(position)` bits,
// those 32 bits contain the 32 bits in the `position`th slot of `node`.
return (node >> shiftBits) & SLOT_MAX;
}
/// @notice Return `node` with the `position`th slot set to zero.
function clearSlot(uint256 node, uint256 position)
internal
pure
returns (uint256)
{
uint256 shiftBits = position * SLOT_WIDTH;
// Shifting `SLOT_MAX` left by `slotShift(position)` bits
// gives us a number where all bits of the `position`th slot are set,
// and all other bits are unset.
//
// Using a bitwise NOT on this number,
// we get a uint256 where all bits are set
// except for those of the `position`th slot.
//
// Bitwise ANDing the original `node` with this number
// sets the bits of `position`th slot to zero,
// leaving all other bits unchanged.
return node & ~(SLOT_MAX << shiftBits);
}
/// @notice Return `node` with the `position`th slot set to `weight`.
///
/// @param weight The weight of of the node.
/// Safely truncated to a 32-bit number,
/// but this should never be called with an overflowing weight regardless.
function setSlot(
uint256 node,
uint256 position,
uint256 weight
) internal pure returns (uint256) {
uint256 shiftBits = position * SLOT_WIDTH;
// Clear the `position`th slot like in `clearSlot()`.
uint256 clearedNode = node & ~(SLOT_MAX << shiftBits);
// Bitwise AND `weight` with `SLOT_MAX`
// to clear all but the 32 least significant bits.
//
// Shift this left by `slotShift(position)` bits
// to obtain a uint256 with all bits unset
// except in the `position`th slot
// which contains the 32-bit value of `weight`.
uint256 shiftedWeight = (weight & SLOT_MAX) << shiftBits;
// When we bitwise OR these together,
// all other slots except the `position`th one come from the left argument,
// and the `position`th gets filled with `weight` from the right argument.
return clearedNode | shiftedWeight;
}
/// @notice Calculate the summed weight of all slots in the `node`.
function sumWeight(uint256 node) internal pure returns (uint256 sum) {
sum = node & SLOT_MAX;
// Iterate through each slot
// by shifting `node` right in increments of 32 bits,
// and adding the 32 least significant bits to the `sum`.
uint256 newNode = node >> SLOT_WIDTH;
while (newNode > 0) {
sum += (newNode & SLOT_MAX);
newNode = newNode >> SLOT_WIDTH;
}
return sum;
}
/// @notice Pick a slot in `node` that corresponds to `index`.
/// Treats the node like an array of virtual stakers,
/// the number of virtual stakers in each slot corresponding to its weight,
/// and picks which slot contains the `index`th virtual staker.
///
/// @dev Requires that `index` be lower than `sumWeight(node)`.
/// However, this is not enforced for performance reasons.
/// If `index` exceeds the permitted range,
/// `pickWeightedSlot()` returns the rightmost slot
/// and an excessively high `newIndex`.
///
/// @return slot The slot of `node` containing the `index`th virtual staker.
///
/// @return newIndex The index of the `index`th virtual staker of `node`
/// within the returned slot.
function pickWeightedSlot(uint256 node, uint256 index)
internal
pure
returns (uint256 slot, uint256 newIndex)
{
newIndex = index;
uint256 newNode = node;
uint256 currentSlotWeight = newNode & SLOT_MAX;
while (newIndex >= currentSlotWeight) {
newIndex -= currentSlotWeight;
slot++;
newNode = newNode >> SLOT_WIDTH;
currentSlotWeight = newNode & SLOT_MAX;
}
return (slot, newIndex);
}
}
library DynamicArray {
// The in-memory dynamic Array is implemented
// by recording the amount of allocated memory
// separately from the length of the array.
// This gives us a perfectly normal in-memory array
// with all the behavior we're used to,
// but also makes O(1) `push` operations possible
// by expanding into the preallocated memory.
//
// When we run out of preallocated memory when trying to `push`,
// we allocate twice as much and copy the array over.
// With linear allocation costs this would amortize to O(1)
// but with EVM allocations being actually quadratic
// the real performance is a very technical O(N).
// Nonetheless, this is reasonably performant in practice.
//
// A dynamic array can be useful
// even when you aren't dealing with an unknown number of items.
// Because the array tracks the allocated space
// separately from the number of stored items,
// you can push items into the dynamic array
// and iterate over the currently present items
// without tracking their number yourself,
// or using a special null value for empty elements.
//
// Because Solidity doesn't really have useful safety features,
// only enough superficial inconveniences
// to lull yourself into a false sense of security,
// dynamic arrays require a bit of care to handle appropriately.
//
// First of all,
// dynamic arrays must not be created or modified manually.
// Use `uintArray(length)`, or `convert(existingArray)`
// which will perform a safe and efficient conversion for you.
// This also applies to storage;
// in-memory dynamic arrays are for efficient in-memory operations only,
// and it is unnecessary to store dynamic arrays.
// Use a regular `uint256[]` instead.
// The contents of `array` may be written like `dynamicArray.array[i] = x`
// but never reassign the `array` pointer itself
// nor mess with `allocatedMemory` in any way whatsoever.
// If you fail to follow these precautions,
// dragons inhabiting the no-man's-land
// between the array as it's seen by Solidity
// and the next thing allocated after it
// will be unleashed to wreak havoc upon your memory buffers.
//
// Second,
// because the `array` may be reassigned when pushing,
// the following pattern is unsafe:
// ```
// UintArray dynamicArray;
// uint256 len = dynamicArray.array.length;
// uint256[] danglingPointer = dynamicArray.array;
// danglingPointer[0] = x;
// dynamicArray.push(y);
// danglingPointer[0] = z;
// uint256 surprise = danglingPointer[len];
// ```
// After the above code block,
// `dynamicArray.array[0]` may be either `x` or `z`,
// and `surprise` may be `y` or out of bounds.
// This will not share your address space with a malevolent agent of chaos,
// but it will cause entirely avoidable scratchings of the head.
//
// Dynamic arrays should be safe to use like ordinary arrays
// if you always refer to the array field of the dynamic array
// when reading or writing values:
// ```
// UintArray dynamicArray;
// uint256 len = dynamicArray.array.length;
// dynamicArray.array[0] = x;
// dynamicArray.push(y);
// dynamicArray.array[0] = z;
// uint256 notSurprise = dynamicArray.array[len];
// ```
// After this code `notSurprise` is reliably `y`,
// and `dynamicArray.array[0]` is `z`.
struct UintArray {
// XXX: Do not modify this value.
// In fact, do not even read it.
// There is never a legitimate reason to do anything with this value.
// She is quiet and wishes to be left alone.
// The silent vigil of `allocatedMemory`
// is the only thing standing between your contract
// and complete chaos in its memory.
// Respect her wish or face the monstrosities she is keeping at bay.
uint256 allocatedMemory;
// Unlike her sharp and vengeful sister,
// `array` is safe to use normally
// for anything you might do with a normal `uint256[]`.
// Reads and loops will check bounds,
// and writing in individual indices like `myArray.array[i] = x`
// is perfectly fine.
// No curse will befall you as long as you obey this rule:
//
// XXX: Never try to replace her or separate her from her sister
// by writing down the accursed words
// `myArray.array = anotherArray` or `lonelyArray = myArray.array`.
//
// If you do, your cattle will be diseased,
// your children will be led astray in the woods,
// and your memory will be silently overwritten.
// Instead, give her a friend with
// `mySecondArray = convert(anotherArray)`,
// and call her by her family name first.
// She will recognize your respect
// and ward your memory against corruption.
uint256[] array;
}
struct AddressArray {
uint256 allocatedMemory;
address[] array;
}
/// @notice Create an empty dynamic array,
/// with preallocated memory for up to `length` elements.
/// @dev Knowing or estimating the preallocated length in advance
/// helps avoid frequent early allocations when filling the array.
/// @param length The number of items to preallocate space for.
/// @return A new dynamic array.
function uintArray(uint256 length) internal pure returns (UintArray memory) {
uint256[] memory array = _allocateUints(length);
return UintArray(length, array);
}
function addressArray(uint256 length)
internal
pure
returns (AddressArray memory)
{
address[] memory array = _allocateAddresses(length);
return AddressArray(length, array);
}
/// @notice Convert an existing non-dynamic array into a dynamic array.
/// @dev The dynamic array is created
/// with allocated memory equal to the length of the array.
/// @param array The array to convert.
/// @return A new dynamic array,
/// containing the contents of the argument `array`.
function convert(uint256[] memory array)
internal
pure
returns (UintArray memory)
{
return UintArray(array.length, array);
}
function convert(address[] memory array)
internal
pure
returns (AddressArray memory)
{
return AddressArray(array.length, array);
}
/// @notice Push `item` into the dynamic array.
/// @dev This function will be safe
/// as long as you haven't scorned either of the sisters.
/// If you have, the dragons will be released
/// to wreak havoc upon your memory.
/// A spell to dispel the curse exists,
/// but a sacred vow prohibits it from being shared
/// with those who do not know how to discover it on their own.
/// @param self The dynamic array to push into;
/// after the call it will be mutated in place to contain the item,
/// allocating more memory behind the scenes if necessary.
/// @param item The item you wish to push into the array.
function arrayPush(UintArray memory self, uint256 item) internal pure {
uint256 length = self.array.length;
uint256 allocLength = self.allocatedMemory;
// The dynamic array is full so we need to allocate more first.
// We check for >= instead of ==
// so that we can put the require inside the conditional,
// reducing the gas costs of `push` slightly.
if (length >= allocLength) {
// This should never happen if `allocatedMemory` isn't messed with.
require(length == allocLength, "Array length exceeds allocation");
// Allocate twice the original array length,
// then copy the contents over.
uint256 newMemory = length * 2;
uint256[] memory newArray = _allocateUints(newMemory);
_copy(newArray, self.array);
self.array = newArray;
self.allocatedMemory = newMemory;
}
// We have enough free memory so we can push into the array.
_push(self.array, item);
}
function arrayPush(AddressArray memory self, address item) internal pure {
uint256 length = self.array.length;
uint256 allocLength = self.allocatedMemory;
if (length >= allocLength) {
require(length == allocLength, "Array length exceeds allocation");
uint256 newMemory = length * 2;
address[] memory newArray = _allocateAddresses(newMemory);
_copy(newArray, self.array);
self.array = newArray;
self.allocatedMemory = newMemory;
}
_push(self.array, item);
}
/// @notice Pop the last item from the dynamic array,
/// removing it and decrementing the array length in place.
/// @dev This makes the dragons happy
/// as they have more space to roam.
/// Thus they have no desire to escape and ravage your buffers.
/// @param self The array to pop from.
/// @return item The previously last element in the array.
function arrayPop(UintArray memory self)
internal
pure
returns (uint256 item)
{
uint256[] memory array = self.array;
uint256 length = array.length;
require(length > 0, "Can't pop from empty array");
return _pop(array);
}
function arrayPop(AddressArray memory self)
internal
pure
returns (address item)
{
address[] memory array = self.array;
uint256 length = array.length;
require(length > 0, "Can't pop from empty array");
return _pop(array);
}
/// @notice Allocate an empty array,
/// reserving enough memory to safely store `length` items.
/// @dev The array starts with zero length,
/// but the allocated buffer has space for `length` words.
/// "What be beyond the bounds of `array`?" you may ask.
/// The answer is: dragons.
/// But do not worry,
/// for `Array.allocatedMemory` protects your EVM from them.
function _allocateUints(uint256 length)
private
pure
returns (uint256[] memory array)
{
// Calculate the size of the allocated block.
// Solidity arrays without a specified constant length
// (i.e. `uint256[]` instead of `uint256[8]`)
// store the length at the first memory position
// and the contents of the array after it,
// so we add 1 to the length to account for this.
uint256 inMemorySize = (length + 1) * 0x20;
// solium-disable-next-line security/no-inline-assembly
assembly {
// Get some free memory
array := mload(0x40)
// Write a zero in the length field;
// we set the length elsewhere
// if we store anything in the array immediately.
// When we allocate we only know how many words we reserve,
// not how many actually get written.
mstore(array, 0)
// Move the free memory pointer
// to the end of the allocated block.
mstore(0x40, add(array, inMemorySize))
}
return array;
}
function _allocateAddresses(uint256 length)
private
pure
returns (address[] memory array)
{
uint256 inMemorySize = (length + 1) * 0x20;
// solium-disable-next-line security/no-inline-assembly
assembly {
array := mload(0x40)
mstore(array, 0)
mstore(0x40, add(array, inMemorySize))
}
return array;
}
/// @notice Unsafe function to copy the contents of one array
/// into an empty initialized array
/// with sufficient free memory available.
function _copy(uint256[] memory dest, uint256[] memory src) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
let length := mload(src)
let byteLength := mul(length, 0x20)
// Store the resulting length of the array.
mstore(dest, length)
// Maintain a write pointer
// for the current write location in the destination array
// by adding the 32 bytes for the array length
// to the starting location.
let writePtr := add(dest, 0x20)
// Stop copying when the write pointer reaches
// the length of the source array.
// We can track the endpoint either from the write or read pointer.
// This uses the write pointer
// because that's the way it was done
// in the (public domain) code I stole this from.
let end := add(writePtr, byteLength)
for {
// Initialize a read pointer to the start of the source array,
// 32 bytes into its memory.
let readPtr := add(src, 0x20)
} lt(writePtr, end) {
// Increase both pointers by 32 bytes each iteration.
writePtr := add(writePtr, 0x20)
readPtr := add(readPtr, 0x20)
} {
// Write the source array into the dest memory
// 32 bytes at a time.
mstore(writePtr, mload(readPtr))
}
}
}
function _copy(address[] memory dest, address[] memory src) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
let length := mload(src)
let byteLength := mul(length, 0x20)
mstore(dest, length)
let writePtr := add(dest, 0x20)
let end := add(writePtr, byteLength)
for {
let readPtr := add(src, 0x20)
} lt(writePtr, end) {
writePtr := add(writePtr, 0x20)
readPtr := add(readPtr, 0x20)
} {
mstore(writePtr, mload(readPtr))
}
}
}
/// @notice Unsafe function to push past the limit of an array.
/// Only use with preallocated free memory.
function _push(uint256[] memory array, uint256 item) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
// Get array length
let length := mload(array)
let newLength := add(length, 1)
// Calculate how many bytes the array takes in memory,
// including the length field.
// This is equal to 32 * the incremented length.
let arraySize := mul(0x20, newLength)
// Calculate the first memory position after the array
let nextPosition := add(array, arraySize)
// Store the item in the available position
mstore(nextPosition, item)
// Increment array length
mstore(array, newLength)
}
}
function _push(address[] memory array, address item) private pure {
// solium-disable-next-line security/no-inline-assembly
assembly {
let length := mload(array)
let newLength := add(length, 1)
let arraySize := mul(0x20, newLength)
let nextPosition := add(array, arraySize)
mstore(nextPosition, item)
mstore(array, newLength)
}
}
function _pop(uint256[] memory array) private pure returns (uint256 item) {
uint256 length = array.length;
// solium-disable-next-line security/no-inline-assembly
assembly {
// Calculate the memory position of the last element
let lastPosition := add(array, mul(length, 0x20))
// Retrieve the last item
item := mload(lastPosition)
// Decrement array length
mstore(array, sub(length, 1))
}
return item;
}
function _pop(address[] memory array) private pure returns (address item) {
uint256 length = array.length;
// solium-disable-next-line security/no-inline-assembly
assembly {
let lastPosition := add(array, mul(length, 0x20))
item := mload(lastPosition)
mstore(array, sub(length, 1))
}
return item;
}
}
contract GasStation {
mapping(address => mapping(uint256 => uint256)) gasDeposits;
function depositGas(address addr) internal {
setDeposit(addr, 1);
}
function releaseGas(address addr) internal {
setDeposit(addr, 0);
}
function setDeposit(address addr, uint256 val) internal {
for (uint256 i = 0; i < gasDepositSize(); i++) {
gasDeposits[addr][i] = val;
}
}
function gasDepositSize() internal pure returns (uint256);
}
library Interval {
using DynamicArray for DynamicArray.UintArray;
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
uint256 constant WEIGHT_WIDTH = SLOT_WIDTH;
uint256 constant WEIGHT_MAX = SLOT_MAX;
uint256 constant START_INDEX_WIDTH = WEIGHT_WIDTH;
uint256 constant START_INDEX_MAX = WEIGHT_MAX;
uint256 constant START_INDEX_SHIFT = WEIGHT_WIDTH;
////////////////////////////////////////////////////////////////////////////
// Interval stores information about a selected interval
// inside a single uint256 in a manner similar to Leaf
// but optimized for use within group selection
//
// The information stored consists of:
// - weight
// - starting index
function make(uint256 startingIndex, uint256 weight)
internal
pure
returns (uint256)
{
uint256 idx = (startingIndex & START_INDEX_MAX) << START_INDEX_SHIFT;
uint256 wt = weight & WEIGHT_MAX;
return (idx | wt);
}
function opWeight(uint256 op) internal pure returns (uint256) {
return (op & WEIGHT_MAX);
}
// Return the starting index of the interval
function index(uint256 a) internal pure returns (uint256) {
return ((a >> WEIGHT_WIDTH) & START_INDEX_MAX);
}
function setIndex(uint256 op, uint256 i) internal pure returns (uint256) {
uint256 shiftedIndex = ((i & START_INDEX_MAX) << WEIGHT_WIDTH);
return (op & (~(START_INDEX_MAX << WEIGHT_WIDTH))) | shiftedIndex;
}
function insert(DynamicArray.UintArray memory intervals, uint256 interval)
internal
pure
{
uint256 tempInterval = interval;
for (uint256 i = 0; i < intervals.array.length; i++) {
uint256 thisInterval = intervals.array[i];
// We can compare the raw underlying uint256 values
// because the starting index is stored
// in the most significant nonzero bits.
if (tempInterval < thisInterval) {
intervals.array[i] = tempInterval;
tempInterval = thisInterval;
}
}
intervals.arrayPush(tempInterval);
}
function skip(uint256 truncatedIndex, DynamicArray.UintArray memory intervals)
internal
pure
returns (uint256 mappedIndex)
{
mappedIndex = truncatedIndex;
for (uint256 i = 0; i < intervals.array.length; i++) {
uint256 interval = intervals.array[i];
// If the index is greater than the starting index of the `i`th leaf,
// we need to skip that leaf.
if (mappedIndex >= index(interval)) {
// Add the weight of this previous leaf to the index,
// ensuring that we skip the leaf.
mappedIndex += Leaf.weight(interval);
} else {
break;
}
}
return mappedIndex;
}
/// @notice Recalculate the starting indices of the previousLeaves
/// when an interval is removed or added at the specified index.
/// @dev Applies weightDiff to each starting index in previousLeaves
/// that exceeds affectedStartingIndex.
/// @param affectedStartingIndex The starting index of the interval.
/// @param weightDiff The difference in weight;
/// negative for a deleted interval,
/// positive for an added interval.
/// @param previousLeaves The starting indices and weights
/// of the previously selected leaves.
/// @return The starting indices of the previous leaves
/// in a tree with the affected interval updated.
function remapIndices(
uint256 affectedStartingIndex,
int256 weightDiff,
DynamicArray.UintArray memory previousLeaves
) internal pure {
uint256 nPreviousLeaves = previousLeaves.array.length;
for (uint256 i = 0; i < nPreviousLeaves; i++) {
uint256 interval = previousLeaves.array[i];
uint256 startingIndex = index(interval);
// If index is greater than the index of the affected interval,
// update the starting index by the weight change.
if (startingIndex > affectedStartingIndex) {
uint256 newIndex = uint256(int256(startingIndex) + weightDiff);
previousLeaves.array[i] = setIndex(interval, newIndex);
}
}
}
}
library Leaf {
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
uint256 constant WEIGHT_WIDTH = SLOT_WIDTH;
uint256 constant WEIGHT_MAX = SLOT_MAX;
uint256 constant BLOCKHEIGHT_WIDTH = 96 - WEIGHT_WIDTH;
uint256 constant BLOCKHEIGHT_MAX = (2**BLOCKHEIGHT_WIDTH) - 1;
////////////////////////////////////////////////////////////////////////////
function make(
address _operator,
uint256 _creationBlock,
uint256 _weight
) internal pure returns (uint256) {
// Converting a bytesX type into a larger type
// adds zero bytes on the right.
uint256 op = uint256(bytes32(bytes20(_operator)));
// Bitwise AND the weight to erase
// all but the 32 least significant bits
uint256 wt = _weight & WEIGHT_MAX;
// Erase all but the 64 least significant bits,
// then shift left by 32 bits to make room for the weight
uint256 cb = (_creationBlock & BLOCKHEIGHT_MAX) << WEIGHT_WIDTH;
// Bitwise OR them all together to get
// [address operator || uint64 creationBlock || uint32 weight]
return (op | cb | wt);
}
function operator(uint256 leaf) internal pure returns (address) {
// Converting a bytesX type into a smaller type
// truncates it on the right.
return address(bytes20(bytes32(leaf)));
}
/// @notice Return the block number the leaf was created in.
function creationBlock(uint256 leaf) internal pure returns (uint256) {
return ((leaf >> WEIGHT_WIDTH) & BLOCKHEIGHT_MAX);
}
function weight(uint256 leaf) internal pure returns (uint256) {
// Weight is stored in the 32 least significant bits.
// Bitwise AND ensures that we only get the contents of those bits.
return (leaf & WEIGHT_MAX);
}
function setWeight(uint256 leaf, uint256 newWeight)
internal
pure
returns (uint256)
{
return ((leaf & ~WEIGHT_MAX) | (newWeight & WEIGHT_MAX));
}
}
library Position {
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_POINTER_MAX = (2**SLOT_BITS) - 1;
uint256 constant LEAF_FLAG = 1 << 255;
////////////////////////////////////////////////////////////////////////////
// Return the last 3 bits of a position number,
// corresponding to its slot in its parent
function slot(uint256 a) internal pure returns (uint256) {
return a & SLOT_POINTER_MAX;
}
// Return the parent of a position number
function parent(uint256 a) internal pure returns (uint256) {
return a >> SLOT_BITS;
}
// Return the location of the child of a at the given slot
function child(uint256 a, uint256 s) internal pure returns (uint256) {
return (a << SLOT_BITS) | (s & SLOT_POINTER_MAX); // slot(s)
}
// Return the uint p as a flagged position uint:
// the least significant 21 bits contain the position
// and the 22nd bit is set as a flag
// to distinguish the position 0x000000 from an empty field.
function setFlag(uint256 p) internal pure returns (uint256) {
return p | LEAF_FLAG;
}
// Turn a flagged position into an unflagged position
// by removing the flag at the 22nd least significant bit.
//
// We shouldn't _actually_ need this
// as all position-manipulating code should ignore non-position bits anyway
// but it's cheap to call so might as well do it.
function unsetFlag(uint256 p) internal pure returns (uint256) {
return p & (~LEAF_FLAG);
}
}
library RNG {
using DynamicArray for DynamicArray.UintArray;
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant WEIGHT_WIDTH = 256 / SLOT_COUNT;
////////////////////////////////////////////////////////////////////////////
struct State {
// RNG output
uint256 currentMappedIndex;
uint256 currentTruncatedIndex;
// The random bytes used to derive indices
bytes32 currentSeed;
// The full range of indices;
// generated random numbers are in [0, fullRange).
uint256 fullRange;
// The truncated range of indices;
// how many non-skipped indices are left to consider.
// Random indices are generated within this range,
// and mapped to the full range by skipping the specified intervals.
uint256 truncatedRange;
DynamicArray.UintArray skippedIntervals;
}
function initialize(
bytes32 seed,
uint256 range,
uint256 expectedSkippedCount
) internal view returns (State memory self) {
self = State(
0,
0,
seed,
range,
range,
DynamicArray.uintArray(expectedSkippedCount)
);
reseed(self, seed, 0);
return self;
}
function reseed(
State memory self,
bytes32 seed,
uint256 nonce
) internal view {
self.currentSeed = keccak256(
abi.encodePacked(seed, nonce, address(this), "reseed")
);
}
function retryIndex(State memory self) internal view {
uint256 truncatedIndex = self.currentTruncatedIndex;
if (self.currentTruncatedIndex < self.truncatedRange) {
self.currentMappedIndex = Interval.skip(
truncatedIndex,
self.skippedIntervals
);
} else {
generateNewIndex(self);
}
}
function updateInterval(
State memory self,
uint256 startIndex,
uint256 oldWeight,
uint256 newWeight
) internal pure {
int256 weightDiff = int256(newWeight) - int256(oldWeight);
uint256 effectiveStartIndex = startIndex + newWeight;
self.truncatedRange = uint256(int256(self.truncatedRange) + weightDiff);
self.fullRange = uint256(int256(self.fullRange) + weightDiff);
Interval.remapIndices(
effectiveStartIndex,
weightDiff,
self.skippedIntervals
);
}
function addSkippedInterval(
State memory self,
uint256 startIndex,
uint256 weight
) internal pure {
self.truncatedRange -= weight;
Interval.insert(self.skippedIntervals, Interval.make(startIndex, weight));
}
/// @notice Generate a new index based on the current seed,
/// without reseeding first.
/// This will result in the same truncated index as before
/// if it still fits in the current truncated range.
function generateNewIndex(State memory self) internal view {
uint256 _truncatedRange = self.truncatedRange;
require(_truncatedRange > 0, "Not enough operators in pool");
uint256 bits = bitsRequired(_truncatedRange);
uint256 truncatedIndex = truncate(bits, uint256(self.currentSeed));
while (truncatedIndex >= _truncatedRange) {
self.currentSeed = keccak256(
abi.encodePacked(self.currentSeed, address(this), "generate")
);
truncatedIndex = truncate(bits, uint256(self.currentSeed));
}
self.currentTruncatedIndex = truncatedIndex;
self.currentMappedIndex = Interval.skip(
truncatedIndex,
self.skippedIntervals
);
}
/// @notice Calculate how many bits are required
/// for an index in the range `[0 .. range-1]`.
///
/// @param range The upper bound of the desired range, exclusive.
///
/// @return uint The smallest number of bits
/// that can contain the number `range-1`.
function bitsRequired(uint256 range) internal pure returns (uint256) {
uint256 bits = WEIGHT_WIDTH - 1;
// Left shift by `bits`,
// so we have a 1 in the (bits + 1)th least significant bit
// and 0 in other bits.
// If this number is equal or greater than `range`,
// the range [0, range-1] fits in `bits` bits.
//
// Because we loop from high bits to low bits,
// we find the highest number of bits that doesn't fit the range,
// and return that number + 1.
while (1 << bits >= range) {
bits--;
}
return bits + 1;
}
/// @notice Truncate `input` to the `bits` least significant bits.
function truncate(uint256 bits, uint256 input)
internal
pure
returns (uint256)
{
return input & ((1 << bits) - 1);
}
/// @notice Get an index in the range `[0 .. range-1]`
/// and the new state of the RNG,
/// using the provided `state` of the RNG.
///
/// @param range The upper bound of the index, exclusive.
///
/// @param state The previous state of the RNG.
/// The initial state needs to be obtained
/// from a trusted randomness oracle (the random beacon),
/// or from a chain of earlier calls to `RNG.getIndex()`
/// on an originally trusted seed.
///
/// @dev Calculates the number of bits required for the desired range,
/// takes the least significant bits of `state`
/// and checks if the obtained index is within the desired range.
/// The original state is hashed with `keccak256` to get a new state.
/// If the index is outside the range,
/// the function retries until it gets a suitable index.
///
/// @return index A random integer between `0` and `range - 1`, inclusive.
///
/// @return newState The new state of the RNG.
/// When `getIndex()` is called one or more times,
/// care must be taken to always use the output `state`
/// of the most recent call as the input `state` of a subsequent call.
/// At the end of a transaction calling `RNG.getIndex()`,
/// the previous stored state must be overwritten with the latest output.
function getIndex(uint256 range, bytes32 state)
internal
view
returns (uint256, bytes32)
{
uint256 bits = bitsRequired(range);
bool found = false;
uint256 index = 0;
bytes32 newState = state;
while (!found) {
index = truncate(bits, uint256(newState));
newState = keccak256(abi.encodePacked(newState, address(this)));
if (index < range) {
found = true;
}
}
return (index, newState);
}
/// @notice Return an index corresponding to a new, unique leaf.
///
/// @dev Gets a new index in a truncated range
/// with the weights of all previously selected leaves subtracted.
/// This index is then mapped to the full range of possible indices,
/// skipping the ranges covered by previous leaves.
///
/// @param range The full range in which the unique index should be.
///
/// @param state The RNG state.
///
/// @param previousLeaves List of indices and weights
/// corresponding to the _first_ index of each previously selected leaf,
/// and the weight of the same leaf.
/// An index number `i` is a starting index of leaf `o`
/// if querying for index `i` in the sortition pool returns `o`,
/// but querying for `i-1` returns a different leaf.
/// This list REALLY needs to be sorted from smallest to largest.
///
/// @param sumPreviousWeights The sum of the weights of previous leaves.
/// Could be calculated from `previousLeafWeights`
/// but providing it explicitly makes the function a bit simpler.
///
/// @return uniqueIndex An index in [0, range) that does not overlap
/// any of the previousLeaves,
/// as determined by the range [index, index + weight).
function getUniqueIndex(
uint256 range,
bytes32 state,
uint256[] memory previousLeaves,
uint256 sumPreviousWeights
) internal view returns (uint256 uniqueIndex, bytes32 newState) {
// Get an index in the truncated range.
// The truncated range covers only new leaves,
// but has to be mapped to the actual range of indices.
uint256 truncatedRange = range - sumPreviousWeights;
uint256 truncatedIndex;
(truncatedIndex, newState) = getIndex(truncatedRange, state);
// Map the truncated index to the available unique indices.
uniqueIndex = Interval.skip(
truncatedIndex,
DynamicArray.convert(previousLeaves)
);
return (uniqueIndex, newState);
}
}
contract SortitionTree {
using StackLib for uint256[];
using Branch for uint256;
using Position for uint256;
using Leaf for uint256;
////////////////////////////////////////////////////////////////////////////
// Parameters for configuration
// How many bits a position uses per level of the tree;
// each branch of the tree contains 2**SLOT_BITS slots.
uint256 constant SLOT_BITS = 3;
uint256 constant LEVELS = 7;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Derived constants, do not touch
uint256 constant SLOT_COUNT = 2**SLOT_BITS;
uint256 constant SLOT_WIDTH = 256 / SLOT_COUNT;
uint256 constant SLOT_MAX = (2**SLOT_WIDTH) - 1;
uint256 constant POOL_CAPACITY = SLOT_COUNT**LEVELS;
////////////////////////////////////////////////////////////////////////////
// implicit tree
// root 8
// level2 64
// level3 512
// level4 4k
// level5 32k
// level6 256k
// level7 2M
uint256 root;
mapping(uint256 => mapping(uint256 => uint256)) branches;
mapping(uint256 => uint256) leaves;
// the flagged (see setFlag() and unsetFlag() in Position.sol) positions
// of all operators present in the pool
mapping(address => uint256) flaggedLeafPosition;
// the leaf after the rightmost occupied leaf of each stack
uint256 rightmostLeaf;
// the empty leaves in each stack
// between 0 and the rightmost occupied leaf
uint256[] emptyLeaves;
constructor() public {
root = 0;
rightmostLeaf = 0;
}
// checks if operator is already registered in the pool
function isOperatorRegistered(address operator) public view returns (bool) {
return getFlaggedLeafPosition(operator) != 0;
}
// Sum the number of operators in each trunk
function operatorsInPool() public view returns (uint256) {
// Get the number of leaves that might be occupied;
// if `rightmostLeaf` equals `firstLeaf()` the tree must be empty,
// otherwise the difference between these numbers
// gives the number of leaves that may be occupied.
uint256 nPossiblyUsedLeaves = rightmostLeaf;
// Get the number of empty leaves
// not accounted for by the `rightmostLeaf`
uint256 nEmptyLeaves = emptyLeaves.getSize();
return (nPossiblyUsedLeaves - nEmptyLeaves);
}
function totalWeight() public view returns (uint256) {
return root.sumWeight();
}
function insertOperator(address operator, uint256 weight) internal {
require(
!isOperatorRegistered(operator),
"Operator is already registered in the pool"
);
uint256 position = getEmptyLeafPosition();
// Record the block the operator was inserted in
uint256 theLeaf = Leaf.make(operator, block.number, weight);
root = setLeaf(position, theLeaf, root);
// Without position flags,
// the position 0x000000 would be treated as empty
flaggedLeafPosition[operator] = position.setFlag();
}
function removeOperator(address operator) internal {
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
require(flaggedPosition != 0, "Operator is not registered in the pool");
uint256 unflaggedPosition = flaggedPosition.unsetFlag();
root = removeLeaf(unflaggedPosition, root);
removeLeafPositionRecord(operator);
}
function updateOperator(address operator, uint256 weight) internal {
require(
isOperatorRegistered(operator),
"Operator is not registered in the pool"
);
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
uint256 unflaggedPosition = flaggedPosition.unsetFlag();
updateLeaf(unflaggedPosition, weight);
}
function removeLeafPositionRecord(address operator) internal {
flaggedLeafPosition[operator] = 0;
}
function getFlaggedLeafPosition(address operator)
internal
view
returns (uint256)
{
return flaggedLeafPosition[operator];
}
function removeLeaf(uint256 position, uint256 _root)
internal
returns (uint256)
{
uint256 rightmostSubOne = rightmostLeaf - 1;
bool isRightmost = position == rightmostSubOne;
uint256 newRoot = setLeaf(position, 0, _root);
if (isRightmost) {
rightmostLeaf = rightmostSubOne;
} else {
emptyLeaves.stackPush(position);
}
return newRoot;
}
function updateLeaf(uint256 position, uint256 weight) internal {
uint256 oldLeaf = leaves[position];
if (oldLeaf.weight() != weight) {
uint256 newLeaf = oldLeaf.setWeight(weight);
root = setLeaf(position, newLeaf, root);
}
}
function setLeaf(
uint256 position,
uint256 theLeaf,
uint256 _root
) internal returns (uint256) {
uint256 childSlot;
uint256 treeNode;
uint256 newNode;
uint256 nodeWeight = theLeaf.weight();
// set leaf
leaves[position] = theLeaf;
uint256 parent = position;
// set levels 7 to 2
for (uint256 level = LEVELS; level >= 2; level--) {
childSlot = parent.slot();
parent = parent.parent();
treeNode = branches[level][parent];
newNode = treeNode.setSlot(childSlot, nodeWeight);
branches[level][parent] = newNode;
nodeWeight = newNode.sumWeight();
}
// set level Root
childSlot = parent.slot();
return _root.setSlot(childSlot, nodeWeight);
}
function pickWeightedLeaf(uint256 index, uint256 _root)
internal
view
returns (uint256 leafPosition, uint256 leafFirstIndex)
{
uint256 currentIndex = index;
uint256 currentNode = _root;
uint256 currentPosition = 0;
uint256 currentSlot;
require(index < currentNode.sumWeight(), "Index exceeds weight");
// get root slot
(currentSlot, currentIndex) = currentNode.pickWeightedSlot(currentIndex);
// get slots from levels 2 to 7
for (uint256 level = 2; level <= LEVELS; level++) {
currentPosition = currentPosition.child(currentSlot);
currentNode = branches[level][currentPosition];
(currentSlot, currentIndex) = currentNode.pickWeightedSlot(currentIndex);
}
// get leaf position
leafPosition = currentPosition.child(currentSlot);
// get the first index of the leaf
// This works because the last weight returned from `pickWeightedSlot()`
// equals the "overflow" from getting the current slot.
leafFirstIndex = index - currentIndex;
}
function getEmptyLeafPosition() internal returns (uint256) {
uint256 rLeaf = rightmostLeaf;
bool spaceOnRight = (rLeaf + 1) < POOL_CAPACITY;
if (spaceOnRight) {
rightmostLeaf = rLeaf + 1;
return rLeaf;
} else {
bool emptyLeavesInStack = leavesInStack();
require(emptyLeavesInStack, "Pool is full");
return emptyLeaves.stackPop();
}
}
function leavesInStack() internal view returns (bool) {
return emptyLeaves.getSize() > 0;
}
}
library StackLib {
function stackPeek(uint256[] storage _array) internal view returns (uint256) {
require(_array.length > 0, "No value to peek, array is empty");
return (_array[_array.length - 1]);
}
function stackPush(uint256[] storage _array, uint256 _element) public {
_array.push(_element);
}
function stackPop(uint256[] storage _array) internal returns (uint256) {
require(_array.length > 0, "No value to pop, array is empty");
uint256 value = _array[_array.length - 1];
_array.length -= 1;
return value;
}
function getSize(uint256[] storage _array) internal view returns (uint256) {
return _array.length;
}
}
interface IBonding {
// Gives the amount of ETH
// the `operator` has made available for bonding by the `bondCreator`.
// If the operator doesn't exist,
// or the bond creator isn't authorized,
// returns 0.
function availableUnbondedValue(
address operator,
address bondCreator,
address authorizedSortitionPool
) external view returns (uint256);
}
interface IStaking {
// Gives the amount of KEEP tokens staked by the `operator`
// eligible for work selection in the specified `operatorContract`.
//
// If the operator doesn't exist or hasn't finished initializing,
// or the operator contract hasn't been authorized for the operator,
// returns 0.
function eligibleStake(
address operator,
address operatorContract
) external view returns (uint256);
}
contract AbstractSortitionPool is SortitionTree, GasStation {
using Leaf for uint256;
using Position for uint256;
using DynamicArray for DynamicArray.UintArray;
using DynamicArray for DynamicArray.AddressArray;
using RNG for RNG.State;
enum Decision {
Select, // Add to the group, and use new seed
Skip, // Retry with same seed, skip this leaf
Delete, // Retry with same seed, delete this leaf
UpdateRetry, // Retry with same seed, update this leaf
UpdateSelect // Select and reseed, but also update this leaf
}
struct Fate {
Decision decision;
// The new weight of the leaf if Decision is Update*, otherwise 0
uint256 maybeWeight;
}
// Require 10 blocks after joining before the operator can be selected for
// a group. This reduces the degrees of freedom miners and other
// front-runners have in conducting pool-bumping attacks.
//
// We don't use the stack of empty leaves until we run out of space on the
// rightmost leaf (i.e. after 2 million operators have joined the pool).
// It means all insertions are at the right end, so one can't reorder
// operators already in the pool until the pool has been filled once.
// Because the index is calculated by taking the minimum number of required
// random bits, and seeing if it falls in the range of the total pool weight,
// the only scenarios where insertions on the right matter are if it crosses
// a power of two threshold for the total weight and unlocks another random
// bit, or if a random number that would otherwise be discarded happens to
// fall within that space.
uint256 constant INIT_BLOCKS = 10;
uint256 constant GAS_DEPOSIT_SIZE = 1;
/// @notice The number of blocks that must be mined before the operator who
// joined the pool is eligible for work selection.
function operatorInitBlocks() public pure returns (uint256) {
return INIT_BLOCKS;
}
// Return whether the operator is eligible for the pool.
function isOperatorEligible(address operator) public view returns (bool) {
return getEligibleWeight(operator) > 0;
}
// Return whether the operator is present in the pool.
function isOperatorInPool(address operator) public view returns (bool) {
return getFlaggedLeafPosition(operator) != 0;
}
// Return whether the operator's weight in the pool
// matches their eligible weight.
function isOperatorUpToDate(address operator) public view returns (bool) {
return getEligibleWeight(operator) == getPoolWeight(operator);
}
// Returns whether the operator has passed the initialization blocks period
// to be eligible for the work selection. Reverts if the operator is not in
// the pool.
function isOperatorInitialized(address operator) public view returns (bool) {
require(isOperatorInPool(operator), "Operator is not in the pool");
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
uint256 leafPosition = flaggedPosition.unsetFlag();
uint256 leaf = leaves[leafPosition];
return isLeafInitialized(leaf);
}
// Return the weight of the operator in the pool,
// which may or may not be out of date.
function getPoolWeight(address operator) public view returns (uint256) {
uint256 flaggedPosition = getFlaggedLeafPosition(operator);
if (flaggedPosition == 0) {
return 0;
} else {
uint256 leafPosition = flaggedPosition.unsetFlag();
uint256 leafWeight = leaves[leafPosition].weight();
return leafWeight;
}
}
// Add an operator to the pool,
// reverting if the operator is already present.
function joinPool(address operator) public {
uint256 eligibleWeight = getEligibleWeight(operator);
require(eligibleWeight > 0, "Operator not eligible");
depositGas(operator);
insertOperator(operator, eligibleWeight);
}
// Update the operator's weight if present and eligible,
// or remove from the pool if present and ineligible.
function updateOperatorStatus(address operator) public {
uint256 eligibleWeight = getEligibleWeight(operator);
uint256 inPoolWeight = getPoolWeight(operator);
require(eligibleWeight != inPoolWeight, "Operator already up to date");
if (eligibleWeight == 0) {
removeOperator(operator);
releaseGas(operator);
} else {
updateOperator(operator, eligibleWeight);
}
}
function generalizedSelectGroup(
uint256 groupSize,
bytes32 seed,
// This uint256 is actually a void pointer.
// We can't pass a SelectionParams,
// because the implementation of the SelectionParams struct
// can vary between different concrete sortition pool implementations.
//
// Whatever SelectionParams struct is used by the concrete contract
// should be created in the `selectGroup`/`selectSetGroup` function,
// then coerced into a uint256 to be passed into this function.
// The paramsPtr is then passed to the `decideFate` implementation
// which can coerce it back into the concrete SelectionParams.
// This allows `generalizedSelectGroup`
// to work with any desired eligibility logic.
uint256 paramsPtr,
bool noDuplicates
) internal returns (address[] memory) {
uint256 _root = root;
bool rootChanged = false;
DynamicArray.AddressArray memory selected;
selected = DynamicArray.addressArray(groupSize);
RNG.State memory rng;
rng = RNG.initialize(seed, _root.sumWeight(), groupSize);
while (selected.array.length < groupSize) {
rng.generateNewIndex();
(uint256 leafPosition, uint256 startingIndex) = pickWeightedLeaf(
rng.currentMappedIndex,
_root
);
uint256 leaf = leaves[leafPosition];
address operator = leaf.operator();
uint256 leafWeight = leaf.weight();
Fate memory fate = decideFate(leaf, selected, paramsPtr);
if (fate.decision == Decision.Select) {
selected.arrayPush(operator);
if (noDuplicates) {
rng.addSkippedInterval(startingIndex, leafWeight);
}
rng.reseed(seed, selected.array.length);
continue;
}
if (fate.decision == Decision.Skip) {
rng.addSkippedInterval(startingIndex, leafWeight);
continue;
}
if (fate.decision == Decision.Delete) {
// Update the RNG
rng.updateInterval(startingIndex, leafWeight, 0);
// Remove the leaf and update root
_root = removeLeaf(leafPosition, _root);
rootChanged = true;
// Remove the record of the operator's leaf and release gas
removeLeafPositionRecord(operator);
releaseGas(operator);
continue;
}
if (fate.decision == Decision.UpdateRetry) {
_root = setLeaf(leafPosition, leaf.setWeight(fate.maybeWeight), _root);
rootChanged = true;
rng.updateInterval(startingIndex, leafWeight, fate.maybeWeight);
continue;
}
if (fate.decision == Decision.UpdateSelect) {
_root = setLeaf(leafPosition, leaf.setWeight(fate.maybeWeight), _root);
rootChanged = true;
selected.arrayPush(operator);
rng.updateInterval(startingIndex, leafWeight, fate.maybeWeight);
if (noDuplicates) {
rng.addSkippedInterval(startingIndex, fate.maybeWeight);
}
rng.reseed(seed, selected.array.length);
continue;
}
}
if (rootChanged) {
root = _root;
}
return selected.array;
}
function isLeafInitialized(uint256 leaf) internal view returns (bool) {
uint256 createdAt = leaf.creationBlock();
return block.number > (createdAt + operatorInitBlocks());
}
// Return the eligible weight of the operator,
// which may differ from the weight in the pool.
// Return 0 if ineligible.
function getEligibleWeight(address operator) internal view returns (uint256);
function decideFate(
uint256 leaf,
DynamicArray.AddressArray memory selected,
uint256 paramsPtr
) internal view returns (Fate memory);
function gasDepositSize() internal pure returns (uint256) {
return GAS_DEPOSIT_SIZE;
}
}
ntract BondedSortitionPool is AbstractSortitionPool {
using DynamicArray for DynamicArray.UintArray;
using DynamicArray for DynamicArray.AddressArray;
using RNG for RNG.State;
struct PoolParams {
IStaking stakingContract;
uint256 minimumStake;
IBonding bondingContract;
// Defines the minimum unbounded value the operator needs to have to be
// eligible to join and stay in the sortition pool. Operators not
// satisfying minimum bondable value are removed from the pool.
uint256 minimumBondableValue;
// Bond required from each operator for the currently pending group
// selection. If operator does not have at least this unbounded value,
// it is skipped during the selection.
uint256 requestedBond;
// The weight divisor in the pool can differ from the minimum stake
uint256 poolWeightDivisor;
address owner;
}
PoolParams poolParams;
constructor(
IStaking _stakingContract,
IBonding _bondingContract,
uint256 _minimumStake,
uint256 _minimumBondableValue,
uint256 _poolWeightDivisor,
address _poolOwner
) public {
require(_minimumStake > 0, "Minimum stake cannot be zero");
poolParams = PoolParams(
_stakingContract,
_minimumStake,
_bondingContract,
_minimumBondableValue,
0,
_poolWeightDivisor,
_poolOwner
);
}
/// @notice Selects a new group of operators of the provided size based on
/// the provided pseudo-random seed and bonding requirements. All operators
/// in the group are unique.
///
/// If there are not enough operators in a pool to form a group or not
/// enough operators are eligible for work selection given the bonding
/// requirements, the function fails.
/// @param groupSize Size of the requested group
/// @param seed Pseudo-random number used to select operators to group
/// @param minimumStake The current minimum stake value
/// @param bondValue Size of the requested bond per operator
function selectSetGroup(
uint256 groupSize,
bytes32 seed,
uint256 minimumStake,
uint256 bondValue
) public returns (address[] memory) {
PoolParams memory params = initializeSelectionParams(
minimumStake,
bondValue
);
require(msg.sender == params.owner, "Only owner may select groups");
uint256 paramsPtr;
// solium-disable-next-line security/no-inline-assembly
assembly {
paramsPtr := params
}
return generalizedSelectGroup(groupSize, seed, paramsPtr, true);
}
/// @notice Sets the minimum bondable value required from the operator
/// so that it is eligible to be in the pool. The pool should specify
/// a reasonable minimum requirement for operators trying to join the pool
/// to prevent griefing group selection.
/// @param minimumBondableValue The minimum bondable value required from the
/// operator.
function setMinimumBondableValue(uint256 minimumBondableValue) public {
require(
msg.sender == poolParams.owner,
"Only owner may update minimum bond value"
);
poolParams.minimumBondableValue = minimumBondableValue;
}
/// @notice Returns the minimum bondable value required from the operator
/// so that it is eligible to be in the pool.
function getMinimumBondableValue() public view returns (uint256) {
return poolParams.minimumBondableValue;
}
function initializeSelectionParams(uint256 minimumStake, uint256 bondValue)
internal
returns (PoolParams memory params)
{
params = poolParams;
if (params.requestedBond != bondValue) {
params.requestedBond = bondValue;
}
if (params.minimumStake != minimumStake) {
params.minimumStake = minimumStake;
poolParams.minimumStake = minimumStake;
}
return params;
}
// Return the eligible weight of the operator,
// which may differ from the weight in the pool.
// Return 0 if ineligible.
function getEligibleWeight(address operator) internal view returns (uint256) {
address ownerAddress = poolParams.owner;
// Get the amount of bondable value available for this pool.
// We only care that this covers one single bond
// regardless of the weight of the operator in the pool.
uint256 bondableValue = poolParams.bondingContract.availableUnbondedValue(
operator,
ownerAddress,
address(this)
);
// Don't query stake if bond is insufficient.
if (bondableValue < poolParams.minimumBondableValue) {
return 0;
}
uint256 eligibleStake = poolParams.stakingContract.eligibleStake(
operator,
ownerAddress
);
// Weight = floor(eligibleStake / poolWeightDivisor)
// but only if eligibleStake >= minimumStake.
// Ethereum uint256 division performs implicit floor
// If eligibleStake < poolWeightDivisor, return 0 = ineligible.
if (eligibleStake < poolParams.minimumStake) {
return 0;
}
return (eligibleStake / poolParams.poolWeightDivisor);
}
function decideFate(
uint256 leaf,
DynamicArray.AddressArray memory, // `selected`, for future use
uint256 paramsPtr
) internal view returns (Fate memory) {
PoolParams memory params;
// solium-disable-next-line security/no-inline-assembly
assembly {
params := paramsPtr
}
address operator = leaf.operator();
uint256 leafWeight = leaf.weight();
if (!isLeafInitialized(leaf)) {
return Fate(Decision.Skip, 0);
}
address ownerAddress = params.owner;
// Get the amount of bondable value available for this pool.
// We only care that this covers one single bond
// regardless of the weight of the operator in the pool.
uint256 bondableValue = params.bondingContract.availableUnbondedValue(
operator,
ownerAddress,
address(this)
);
// If unbonded value is insufficient for the operator to be in the pool,
// delete the operator.
if (bondableValue < params.minimumBondableValue) {
return Fate(Decision.Delete, 0);
}
// If unbonded value is sufficient for the operator to be in the pool
// but it is not sufficient for the current selection, skip the operator.
if (bondableValue < params.requestedBond) {
return Fate(Decision.Skip, 0);
}
uint256 eligibleStake = params.stakingContract.eligibleStake(
operator,
ownerAddress
);
// Weight = floor(eligibleStake / poolWeightDivisor)
// Ethereum uint256 division performs implicit floor
uint256 eligibleWeight = eligibleStake / params.poolWeightDivisor;
if (eligibleWeight < leafWeight || eligibleStake < params.minimumStake) {
return Fate(Decision.Delete, 0);
}
return Fate(Decision.Select, 0);
}
}
| solium-disable-next-line security/no-inline-assembly | function selectSetGroup(
uint256 groupSize,
bytes32 seed,
uint256 minimumStake,
uint256 bondValue
) public returns (address[] memory) {
PoolParams memory params = initializeSelectionParams(
minimumStake,
bondValue
);
require(msg.sender == params.owner, "Only owner may select groups");
uint256 paramsPtr;
assembly {
paramsPtr := params
}
return generalizedSelectGroup(groupSize, seed, paramsPtr, true);
}
| 7,494,118 |
pragma solidity ^0.5.3;
/**
* @author ESPAY PTY LTD.
*/
/**
* @title ERC223Interface
* @dev ERC223 Contract Interface
*/
contract ERC20Interface {
function transfer(address _to, uint256 _value) public returns (bool);
function balanceOf(address who)public view returns (uint);
}
/**
* @title Forwarder
* @dev Contract that will forward any incoming Ether & token to wallet
*/
contract Forwarder {
address payable public parentAddress;
event ForwarderDeposited(address from, uint value, bytes data);
event TokensFlushed(address forwarderAddress, uint value, address tokenContractAddress);
/**
* @dev Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress);
_;
}
/**
* @dev Create the contract, and sets the destination address to that of the creator
*/
constructor() public{
parentAddress = msg.sender;
}
/**
* @dev Default function; Gets called when Ether is deposited, and forwards it to the parent address.
* Credit eth to contract creator.
*/
function() external payable { //inject DOS BY COMPLEX FALLBACK
parentAddress.call.gas(2301).value(msg.value)("");
emit ForwarderDeposited(msg.sender, msg.value, msg.data);
}
/**
* @dev Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) public onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
uint forwarderBalance = instance.balanceOf(address(this));
require(forwarderBalance > 0);
require(instance.transfer(parentAddress, forwarderBalance));
emit TokensFlushed(address(this), forwarderBalance, tokenContractAddress);
}
/**
* @dev Execute a specified token transfer from the forwarder token to the parent address.
* @param _from the address of the erc20 token contract.
* @param _value the amount of token.
*/
function flushToken(address _from, uint _value) external{
require(ERC20Interface(_from).transfer(parentAddress, _value), "instance error");
}
/**
* @dev It is possible that funds were sent to this address before the contract was deployed.
* We can flush those funds to the parent address.
*/
function flush() public {
parentAddress.transfer(address(this).balance);
}
}
/**
* @title MultiSignWallet
*/
contract MultiSignWallet {
address[] public signers;
bool public safeMode;
uint forwarderCount;
uint lastsequenceId;
event Deposited(address from, uint value, bytes data);
event SafeModeActivated(address msgSender);
event SafeModeInActivated(address msgSender);
event ForwarderCreated(address forwarderAddress);
event Transacted(address msgSender, address otherSigner, bytes32 operation, address toAddress, uint value, bytes data);
event TokensTransfer(address tokenContractAddress, uint value);
/**
* @dev Modifier that will execute internal code block only if the
* sender is an authorized signer on this wallet
*/
modifier onlySigner {
require(isSigner(msg.sender));
_;
}
/**
* @dev Set up a simple multi-sig wallet by specifying the signers allowed to be used on this wallet.
* 2 signers will be required to send a transaction from this wallet.
* Note: The sender is NOT automatically added to the list of signers.
* Signers CANNOT be changed once they are set
* @param allowedSigners An array of signers on the wallet
*/
constructor(address[] memory allowedSigners) public {
require(allowedSigners.length == 3);
signers = allowedSigners;
}
/**
* @dev Gets called when a transaction is received without calling a method
*/
function() external payable {
if(msg.value > 0){
emit Deposited(msg.sender, msg.value, msg.data);
}
}
/**
* @dev Determine if an address is a signer on this wallet
* @param signer address to check
* @return boolean indicating whether address is signer or not
*/
function isSigner(address signer) public view returns (bool) {
for (uint i = 0; i < signers.length; i++) {
if (signers[i] == signer) {
return true;
}
}
return false;
}
/**
* @dev Irrevocably puts contract into safe mode. When in this mode,
* transactions may only be sent to signing addresses.
*/
function activateSafeMode() public onlySigner {
require(!safeMode);
safeMode = true;
emit SafeModeActivated(msg.sender);
}
/**
* @dev Irrevocably puts out contract into safe mode.
*/
function turnOffSafeMode() public onlySigner {
require(safeMode);
safeMode = false;
emit SafeModeInActivated(msg.sender);
}
/**
* @dev Create a new contract (and also address) that forwards funds to this contract
* returns address of newly created forwarder address
*/
function createForwarder() public returns (address) {
Forwarder f = new Forwarder();
forwarderCount += 1;
emit ForwarderCreated(address(f));
return(address(f));
}
/**
* @dev for return No of forwarder generated.
* @return total number of generated forwarder count.
*/
function getForwarder() public view returns(uint){
return forwarderCount;
}
/**
* @dev Execute a token flush from one of the forwarder addresses.
* This transfer needs only a single signature and can be done by any signer
* @param forwarderAddress the address of the forwarder address to flush the tokens from
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushForwarderTokens(address payable forwarderAddress, address tokenContractAddress) public onlySigner {
Forwarder forwarder = Forwarder(forwarderAddress);
forwarder.flushTokens(tokenContractAddress);
}
/**
* @dev Gets the next available sequence ID for signing when using executeAndConfirm
* @return the sequenceId one higher than the highest currently stored
*/
function getNextSequenceId() public view returns (uint) {
return lastsequenceId+1;
}
/**
* @dev generate the hash for sendMultiSig
* same parameter as sendMultiSig
* @return the hash generated by parameters
*/
function getHash(address toAddress, uint value, bytes memory data, uint expireTime, uint sequenceId)public pure returns (bytes32){
return keccak256(abi.encodePacked("ETHER", toAddress, value, data, expireTime, sequenceId));
}
/**
* @dev Execute a multi-signature transaction from this wallet using 2 signers:
* one from msg.sender and the other from ecrecover.
* Sequence IDs are numbers starting from 1. They are used to prevent replay
* attacks and may not be repeated.
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in Wei to be sent
* @param data the data to send to the toAddress when invoking the transaction
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature see Data Formats
*/
function sendMultiSig(address payable toAddress, uint value, bytes memory data, uint expireTime, uint sequenceId, bytes memory signature) public payable onlySigner {
bytes32 operationHash = keccak256(abi.encodePacked("ETHER", toAddress, value, data, expireTime, sequenceId));
address otherSigner = verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
toAddress.transfer(value);
emit Transacted(msg.sender, otherSigner, operationHash, toAddress, value, data);
}
/**
* @dev generate the hash for sendMultiSigToken and sendMultiSigForwarder.
* same parameter as sendMultiSigToken and sendMultiSigForwarder.
* @return the hash generated by parameters
*/
function getTokenHash( address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId) public pure returns (bytes32){
return keccak256(abi.encodePacked("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId));
}
/**
* @dev Execute a multi-signature token transfer from this wallet using 2 signers:
* one from msg.sender and the other from ecrecover.
* Sequence IDs are numbers starting from 1. They are used to prevent replay
* attacks and may not be repeated.
* @param toAddress the destination address to send an outgoing transaction
* @param value the amount in tokens to be sent
* @param tokenContractAddress the address of the erc20 token contract
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @param signature see Data Formats
*/
function sendMultiSigToken(address toAddress, uint value, address tokenContractAddress, uint expireTime, uint sequenceId, bytes memory signature) public onlySigner {
bytes32 operationHash = keccak256(abi.encodePacked("ERC20", toAddress, value, tokenContractAddress, expireTime, sequenceId));
verifyMultiSig(toAddress, operationHash, signature, expireTime, sequenceId);
ERC20Interface instance = ERC20Interface(tokenContractAddress);
require(instance.balanceOf(address(this)) > 0);
require(instance.transfer(toAddress, value));
emit TokensTransfer(tokenContractAddress, value);
}
/**
* @dev Gets signer's address using ecrecover
* @param operationHash see Data Formats
* @param signature see Data Formats
* @return address recovered from the signature
*/
function recoverAddressFromSignature(bytes32 operationHash, bytes memory signature) private pure returns (address) {
require(signature.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := byte(0, mload(add(signature, 96)))
}
if (v < 27) {
v += 27;
}
return ecrecover(operationHash, v, r, s);
}
/**
* @dev Verify that the sequence id has not been used before and inserts it. Throws if the sequence ID was not accepted.
* @param sequenceId to insert into array of stored ids
*/
function tryInsertSequenceId(uint sequenceId) private onlySigner {
require(sequenceId > lastsequenceId && sequenceId <= (lastsequenceId+1000), "Enter Valid sequenceId");
lastsequenceId=sequenceId;
}
/**
* @dev Do common multisig verification for both eth sends and erc20token transfers
* @param toAddress the destination address to send an outgoing transaction
* @param operationHash see Data Formats
* @param signature see Data Formats
* @param expireTime the number of seconds since 1970 for which this transaction is valid
* @param sequenceId the unique sequence id obtainable from getNextSequenceId
* @return address that has created the signature
*/
function verifyMultiSig(address toAddress, bytes32 operationHash, bytes memory signature, uint expireTime, uint sequenceId) private returns (address) {
address otherSigner = recoverAddressFromSignature(operationHash, signature);
if (safeMode && !isSigner(toAddress)) {
revert("safemode error");
}
require(isSigner(otherSigner) && expireTime > now);
require(otherSigner != msg.sender);
tryInsertSequenceId(sequenceId);
return otherSigner;
}
} | Gets called when a transaction is received without calling a method/ | function() external payable {
if(msg.value > 0){
emit Deposited(msg.sender, msg.value, msg.data);
}
}
| 13,137,399 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "./UbiquityAlgorithmicDollarManager.sol";
import "./interfaces/IDollarMintingCalculator.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./TWAPOracle.sol";
import "./libs/ABDKMathQuad.sol";
/// @title A mock coupon calculator that always returns a constant
contract DollarMintingCalculator is IDollarMintingCalculator {
using ABDKMathQuad for uint256;
using ABDKMathQuad for bytes16;
bytes16 private immutable _one = (uint256(1 ether)).fromUInt();
UbiquityAlgorithmicDollarManager public manager;
/// @param _manager the address of the manager contract so we can fetch variables
constructor(address _manager) {
manager = UbiquityAlgorithmicDollarManager(_manager);
}
/// @notice returns (TWAP_PRICE -1) * UAD_Total_Supply
function getDollarsToMint() external view override returns (uint256) {
TWAPOracle oracle = TWAPOracle(manager.twapOracleAddress());
uint256 twapPrice = oracle.consult(manager.dollarTokenAddress());
require(twapPrice > 1, "DollarMintingCalculator: not > 1");
return
twapPrice
.fromUInt()
.sub(_one)
.mul(
(
IERC20(manager.dollarTokenAddress())
.totalSupply()
.fromUInt()
.div(_one)
)
)
.toUInt();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IUbiquityAlgorithmicDollar.sol";
import "./interfaces/ICurveFactory.sol";
import "./interfaces/IMetaPool.sol";
import "./TWAPOracle.sol";
/// @title A central config for the uAD system. Also acts as a central
/// access control manager.
/// @notice For storing constants. For storing variables and allowing them to
/// be changed by the admin (governance)
/// @dev This should be used as a central access control manager which other
/// contracts use to check permissions
contract UbiquityAlgorithmicDollarManager is AccessControl {
using SafeERC20 for IERC20;
bytes32 public constant UBQ_MINTER_ROLE = keccak256("UBQ_MINTER_ROLE");
bytes32 public constant UBQ_BURNER_ROLE = keccak256("UBQ_BURNER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant COUPON_MANAGER_ROLE = keccak256("COUPON_MANAGER");
bytes32 public constant BONDING_MANAGER_ROLE = keccak256("BONDING_MANAGER");
bytes32 public constant INCENTIVE_MANAGER_ROLE =
keccak256("INCENTIVE_MANAGER");
bytes32 public constant UBQ_TOKEN_MANAGER_ROLE =
keccak256("UBQ_TOKEN_MANAGER_ROLE");
address public twapOracleAddress;
address public debtCouponAddress;
address public dollarTokenAddress; // uAD
address public couponCalculatorAddress;
address public dollarMintingCalculatorAddress;
address public bondingShareAddress;
address public bondingContractAddress;
address public stableSwapMetaPoolAddress;
address public curve3PoolTokenAddress; // 3CRV
address public treasuryAddress;
address public governanceTokenAddress; // uGOV
address public sushiSwapPoolAddress; // sushi pool uAD-uGOV
address public masterChefAddress;
address public formulasAddress;
address public autoRedeemTokenAddress; // uAR
address public uarCalculatorAddress; // uAR calculator
//key = address of couponmanager, value = excessdollardistributor
mapping(address => address) private _excessDollarDistributors;
modifier onlyAdmin() {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"uADMGR: Caller is not admin"
);
_;
}
constructor(address _admin) {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(UBQ_MINTER_ROLE, _admin);
_setupRole(PAUSER_ROLE, _admin);
_setupRole(COUPON_MANAGER_ROLE, _admin);
_setupRole(BONDING_MANAGER_ROLE, _admin);
_setupRole(INCENTIVE_MANAGER_ROLE, _admin);
_setupRole(UBQ_TOKEN_MANAGER_ROLE, address(this));
}
// TODO Add a generic setter for extra addresses that needs to be linked
function setTwapOracleAddress(address _twapOracleAddress)
external
onlyAdmin
{
twapOracleAddress = _twapOracleAddress;
// to be removed
TWAPOracle oracle = TWAPOracle(twapOracleAddress);
oracle.update();
}
function setuARTokenAddress(address _uarTokenAddress) external onlyAdmin {
autoRedeemTokenAddress = _uarTokenAddress;
}
function setDebtCouponAddress(address _debtCouponAddress)
external
onlyAdmin
{
debtCouponAddress = _debtCouponAddress;
}
function setIncentiveToUAD(address _account, address _incentiveAddress)
external
onlyAdmin
{
IUbiquityAlgorithmicDollar(dollarTokenAddress).setIncentiveContract(
_account,
_incentiveAddress
);
}
function setDollarTokenAddress(address _dollarTokenAddress)
external
onlyAdmin
{
dollarTokenAddress = _dollarTokenAddress;
}
function setGovernanceTokenAddress(address _governanceTokenAddress)
external
onlyAdmin
{
governanceTokenAddress = _governanceTokenAddress;
}
function setSushiSwapPoolAddress(address _sushiSwapPoolAddress)
external
onlyAdmin
{
sushiSwapPoolAddress = _sushiSwapPoolAddress;
}
function setUARCalculatorAddress(address _uarCalculatorAddress)
external
onlyAdmin
{
uarCalculatorAddress = _uarCalculatorAddress;
}
function setCouponCalculatorAddress(address _couponCalculatorAddress)
external
onlyAdmin
{
couponCalculatorAddress = _couponCalculatorAddress;
}
function setDollarMintingCalculatorAddress(
address _dollarMintingCalculatorAddress
) external onlyAdmin {
dollarMintingCalculatorAddress = _dollarMintingCalculatorAddress;
}
function setExcessDollarsDistributor(
address debtCouponManagerAddress,
address excessCouponDistributor
) external onlyAdmin {
_excessDollarDistributors[
debtCouponManagerAddress
] = excessCouponDistributor;
}
function setMasterChefAddress(address _masterChefAddress)
external
onlyAdmin
{
masterChefAddress = _masterChefAddress;
}
function setFormulasAddress(address _formulasAddress) external onlyAdmin {
formulasAddress = _formulasAddress;
}
function setBondingShareAddress(address _bondingShareAddress)
external
onlyAdmin
{
bondingShareAddress = _bondingShareAddress;
}
function setStableSwapMetaPoolAddress(address _stableSwapMetaPoolAddress)
external
onlyAdmin
{
stableSwapMetaPoolAddress = _stableSwapMetaPoolAddress;
}
/**
@notice set the bonding bontract smart contract address
@dev bonding contract participants deposit curve LP token
for a certain duration to earn uGOV and more curve LP token
@param _bondingContractAddress bonding contract address
*/
function setBondingContractAddress(address _bondingContractAddress)
external
onlyAdmin
{
bondingContractAddress = _bondingContractAddress;
}
/**
@notice set the treasury address
@dev the treasury fund is used to maintain the protocol
@param _treasuryAddress treasury fund address
*/
function setTreasuryAddress(address _treasuryAddress) external onlyAdmin {
treasuryAddress = _treasuryAddress;
}
/**
@notice deploy a new Curve metapools for uAD Token uAD/3Pool
@dev From the curve documentation for uncollateralized algorithmic
stablecoins amplification should be 5-10
@param _curveFactory MetaPool factory address
@param _crvBasePool Address of the base pool to use within the new metapool.
@param _crv3PoolTokenAddress curve 3Pool token Address
@param _amplificationCoefficient amplification coefficient. The smaller
it is the closer to a constant product we are.
@param _fee Trade fee, given as an integer with 1e10 precision.
*/
function deployStableSwapPool(
address _curveFactory,
address _crvBasePool,
address _crv3PoolTokenAddress,
uint256 _amplificationCoefficient,
uint256 _fee
) external onlyAdmin {
// Create new StableSwap meta pool (uAD <-> 3Crv)
address metaPool =
ICurveFactory(_curveFactory).deploy_metapool(
_crvBasePool,
ERC20(dollarTokenAddress).name(),
ERC20(dollarTokenAddress).symbol(),
dollarTokenAddress,
_amplificationCoefficient,
_fee
);
stableSwapMetaPoolAddress = metaPool;
// Approve the newly-deployed meta pool to transfer this contract's funds
uint256 crv3PoolTokenAmount =
IERC20(_crv3PoolTokenAddress).balanceOf(address(this));
uint256 uADTokenAmount =
IERC20(dollarTokenAddress).balanceOf(address(this));
// safe approve revert if approve from non-zero to non-zero allowance
IERC20(_crv3PoolTokenAddress).safeApprove(metaPool, 0);
IERC20(_crv3PoolTokenAddress).safeApprove(
metaPool,
crv3PoolTokenAmount
);
IERC20(dollarTokenAddress).safeApprove(metaPool, 0);
IERC20(dollarTokenAddress).safeApprove(metaPool, uADTokenAmount);
// coin at index 0 is uAD and index 1 is 3CRV
require(
IMetaPool(metaPool).coins(0) == dollarTokenAddress &&
IMetaPool(metaPool).coins(1) == _crv3PoolTokenAddress,
"uADMGR: COIN_ORDER_MISMATCH"
);
// Add the initial liquidity to the StableSwap meta pool
uint256[2] memory amounts =
[
IERC20(dollarTokenAddress).balanceOf(address(this)),
IERC20(_crv3PoolTokenAddress).balanceOf(address(this))
];
// set curve 3Pool address
curve3PoolTokenAddress = _crv3PoolTokenAddress;
IMetaPool(metaPool).add_liquidity(amounts, 0, msg.sender);
}
function getExcessDollarsDistributor(address _debtCouponManagerAddress)
external
view
returns (address)
{
return _excessDollarDistributors[_debtCouponManagerAddress];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
/// @title A mechanism for calculating dollars to be minted
interface IDollarMintingCalculator {
function getDollarsToMint() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "./interfaces/IMetaPool.sol";
contract TWAPOracle {
address public immutable pool;
address public immutable token0;
address public immutable token1;
uint256 public price0Average;
uint256 public price1Average;
uint256 public pricesBlockTimestampLast;
uint256[2] public priceCumulativeLast;
constructor(
address _pool,
address _uADtoken0,
address _curve3CRVtoken1
) {
pool = _pool;
// coin at index 0 is uAD and index 1 is 3CRV
require(
IMetaPool(_pool).coins(0) == _uADtoken0 &&
IMetaPool(_pool).coins(1) == _curve3CRVtoken1,
"TWAPOracle: COIN_ORDER_MISMATCH"
);
token0 = _uADtoken0;
token1 = _curve3CRVtoken1;
uint256 _reserve0 = uint112(IMetaPool(_pool).balances(0));
uint256 _reserve1 = uint112(IMetaPool(_pool).balances(1));
// ensure that there's liquidity in the pair
require(_reserve0 != 0 && _reserve1 != 0, "TWAPOracle: NO_RESERVES");
// ensure that pair balance is perfect
require(_reserve0 == _reserve1, "TWAPOracle: PAIR_UNBALANCED");
priceCumulativeLast = IMetaPool(_pool).get_price_cumulative_last();
pricesBlockTimestampLast = IMetaPool(_pool).block_timestamp_last();
price0Average = 1 ether;
price1Average = 1 ether;
}
// calculate average price
function update() external {
(uint256[2] memory priceCumulative, uint256 blockTimestamp) =
_currentCumulativePrices();
if (blockTimestamp - pricesBlockTimestampLast > 0) {
// get the balances between now and the last price cumulative snapshot
uint256[2] memory twapBalances =
IMetaPool(pool).get_twap_balances(
priceCumulativeLast,
priceCumulative,
blockTimestamp - pricesBlockTimestampLast
);
// price to exchange amounIn uAD to 3CRV based on TWAP
price0Average = IMetaPool(pool).get_dy(0, 1, 1 ether, twapBalances);
// price to exchange amounIn 3CRV to uAD based on TWAP
price1Average = IMetaPool(pool).get_dy(1, 0, 1 ether, twapBalances);
// we update the priceCumulative
priceCumulativeLast = priceCumulative;
pricesBlockTimestampLast = blockTimestamp;
}
}
// note this will always return 0 before update has been called successfully
// for the first time.
function consult(address token) external view returns (uint256 amountOut) {
if (token == token0) {
// price to exchange 1 uAD to 3CRV based on TWAP
amountOut = price0Average;
} else {
require(token == token1, "TWAPOracle: INVALID_TOKEN");
// price to exchange 1 3CRV to uAD based on TWAP
amountOut = price1Average;
}
}
function _currentCumulativePrices()
internal
view
returns (uint256[2] memory priceCumulative, uint256 blockTimestamp)
{
priceCumulative = IMetaPool(pool).get_price_cumulative_last();
blockTimestamp = IMetaPool(pool).block_timestamp_last();
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math Quad Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.8.0;
/**
* Smart contract library of mathematical functions operating with IEEE 754
* quadruple-precision binary floating-point numbers (quadruple precision
* numbers). As long as quadruple precision numbers are 16-bytes long, they are
* represented by bytes16 type.
*/
library ABDKMathQuad {
/*
* 0.
*/
bytes16 private constant _POSITIVE_ZERO =
0x00000000000000000000000000000000;
/*
* -0.
*/
bytes16 private constant _NEGATIVE_ZERO =
0x80000000000000000000000000000000;
/*
* +Infinity.
*/
bytes16 private constant _POSITIVE_INFINITY =
0x7FFF0000000000000000000000000000;
/*
* -Infinity.
*/
bytes16 private constant _NEGATIVE_INFINITY =
0xFFFF0000000000000000000000000000;
/*
* Canonical NaN value.
*/
bytes16 private constant NaN = 0x7FFF8000000000000000000000000000;
/**
* Convert signed 256-bit integer number into quadruple precision number.
*
* @param x signed 256-bit integer number
* @return quadruple precision number
*/
function fromInt(int256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16383 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 256-bit integer number
* rounding towards zero. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 256-bit integer number
*/
function toInt(bytes16 x) internal pure returns (int256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16638); // Overflow
if (exponent < 16383) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(
result <=
0x8000000000000000000000000000000000000000000000000000000000000000
);
return -int256(result); // We rely on overflow behavior here
} else {
require(
result <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
return int256(result);
}
}
}
/**
* Convert unsigned 256-bit integer number into quadruple precision number.
*
* @param x unsigned 256-bit integer number
* @return quadruple precision number
*/
function fromUInt(uint256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
uint256 result = x;
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16383 + msb) << 112);
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into unsigned 256-bit integer number
* rounding towards zero. Revert on underflow. Note, that negative floating
* point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer
* without error, because they are rounded to zero.
*
* @param x quadruple precision number
* @return unsigned 256-bit integer number
*/
function toUInt(bytes16 x) internal pure returns (uint256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
if (exponent < 16383) return 0; // Underflow
require(uint128(x) < 0x80000000000000000000000000000000); // Negative
require(exponent <= 16638); // Overflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16495) result >>= 16495 - exponent;
else if (exponent > 16495) result <<= exponent - 16495;
return result;
}
}
/**
* Convert signed 128.128 bit fixed point number into quadruple precision
* number.
*
* @param x signed 128.128 bit fixed point number
* @return quadruple precision number
*/
function from128x128(int256 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint256(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16255 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 128.128 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 128.128 bit fixed point number
*/
function to128x128(bytes16 x) internal pure returns (int256) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16510); // Overflow
if (exponent < 16255) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16367) result >>= 16367 - exponent;
else if (exponent > 16367) result <<= exponent - 16367;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(
result <=
0x8000000000000000000000000000000000000000000000000000000000000000
);
return -int256(result); // We rely on overflow behavior here
} else {
require(
result <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
);
return int256(result);
}
}
}
/**
* Convert signed 64.64 bit fixed point number into quadruple precision
* number.
*
* @param x signed 64.64 bit fixed point number
* @return quadruple precision number
*/
function from64x64(int128 x) internal pure returns (bytes16) {
unchecked {
if (x == 0) return bytes16(0);
else {
// We rely on overflow behavior here
uint256 result = uint128(x > 0 ? x : -x);
uint256 msb = mostSignificantBit(result);
if (msb < 112) result <<= 112 - msb;
else if (msb > 112) result >>= msb - 112;
result =
(result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
((16319 + msb) << 112);
if (x < 0) result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
}
/**
* Convert quadruple precision number into signed 64.64 bit fixed point
* number. Revert on overflow.
*
* @param x quadruple precision number
* @return signed 64.64 bit fixed point number
*/
function to64x64(bytes16 x) internal pure returns (int128) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
require(exponent <= 16446); // Overflow
if (exponent < 16319) return 0; // Underflow
uint256 result =
(uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF) |
0x10000000000000000000000000000;
if (exponent < 16431) result >>= 16431 - exponent;
else if (exponent > 16431) result <<= exponent - 16431;
if (uint128(x) >= 0x80000000000000000000000000000000) {
// Negative
require(result <= 0x80000000000000000000000000000000);
return -int128(int256(result)); // We rely on overflow behavior here
} else {
require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128(int256(result));
}
}
}
/**
* Convert octuple precision number into quadruple precision number.
*
* @param x octuple precision number
* @return quadruple precision number
*/
function fromOctuple(bytes32 x) internal pure returns (bytes16) {
unchecked {
bool negative =
x &
0x8000000000000000000000000000000000000000000000000000000000000000 >
0;
uint256 exponent = (uint256(x) >> 236) & 0x7FFFF;
uint256 significand =
uint256(x) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFFF) {
if (significand > 0) return NaN;
else return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
}
if (exponent > 278526)
return negative ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else if (exponent < 245649)
return negative ? _NEGATIVE_ZERO : _POSITIVE_ZERO;
else if (exponent < 245761) {
significand =
(significand |
0x100000000000000000000000000000000000000000000000000000000000) >>
(245885 - exponent);
exponent = 0;
} else {
significand >>= 124;
exponent -= 245760;
}
uint128 result = uint128(significand | (exponent << 112));
if (negative) result |= 0x80000000000000000000000000000000;
return bytes16(result);
}
}
/**
* Convert quadruple precision number into octuple precision number.
*
* @param x quadruple precision number
* @return octuple precision number
*/
function toOctuple(bytes16 x) internal pure returns (bytes32) {
unchecked {
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 result = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF)
exponent = 0x7FFFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = mostSignificantBit(result);
result =
(result << (236 - msb)) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 245649 + msb;
}
} else {
result <<= 124;
exponent += 245760;
}
result |= exponent << 236;
if (uint128(x) >= 0x80000000000000000000000000000000)
result |= 0x8000000000000000000000000000000000000000000000000000000000000000;
return bytes32(result);
}
}
/**
* Convert double precision number into quadruple precision number.
*
* @param x double precision number
* @return quadruple precision number
*/
function fromDouble(bytes8 x) internal pure returns (bytes16) {
unchecked {
uint256 exponent = (uint64(x) >> 52) & 0x7FF;
uint256 result = uint64(x) & 0xFFFFFFFFFFFFF;
if (exponent == 0x7FF)
exponent = 0x7FFF; // Infinity or NaN
else if (exponent == 0) {
if (result > 0) {
uint256 msb = mostSignificantBit(result);
result =
(result << (112 - msb)) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
exponent = 15309 + msb;
}
} else {
result <<= 60;
exponent += 15360;
}
result |= exponent << 112;
if (x & 0x8000000000000000 > 0)
result |= 0x80000000000000000000000000000000;
return bytes16(uint128(result));
}
}
/**
* Convert quadruple precision number into double precision number.
*
* @param x quadruple precision number
* @return double precision number
*/
function toDouble(bytes16 x) internal pure returns (bytes8) {
unchecked {
bool negative = uint128(x) >= 0x80000000000000000000000000000000;
uint256 exponent = (uint128(x) >> 112) & 0x7FFF;
uint256 significand = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (exponent == 0x7FFF) {
if (significand > 0) return 0x7FF8000000000000;
// NaN
else
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000); // Infinity
}
if (exponent > 17406)
return
negative
? bytes8(0xFFF0000000000000) // -Infinity
: bytes8(0x7FF0000000000000);
// Infinity
else if (exponent < 15309)
return
negative
? bytes8(0x8000000000000000) // -0
: bytes8(0x0000000000000000);
// 0
else if (exponent < 15361) {
significand =
(significand | 0x10000000000000000000000000000) >>
(15421 - exponent);
exponent = 0;
} else {
significand >>= 60;
exponent -= 15360;
}
uint64 result = uint64(significand | (exponent << 52));
if (negative) result |= 0x8000000000000000;
return bytes8(result);
}
}
/**
* Test whether given quadruple precision number is NaN.
*
* @param x quadruple precision number
* @return true if x is NaN, false otherwise
*/
function isNaN(bytes16 x) internal pure returns (bool) {
unchecked {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF >
0x7FFF0000000000000000000000000000;
}
}
/**
* Test whether given quadruple precision number is positive or negative
* infinity.
*
* @param x quadruple precision number
* @return true if x is positive or negative infinity, false otherwise
*/
function isInfinity(bytes16 x) internal pure returns (bool) {
unchecked {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ==
0x7FFF0000000000000000000000000000;
}
}
/**
* Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x
* is positive. Note that sign (-0) is zero. Revert if x is NaN.
*
* @param x quadruple precision number
* @return sign of x
*/
function sign(bytes16 x) internal pure returns (int8) {
unchecked {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
if (absoluteX == 0) return 0;
else if (uint128(x) >= 0x80000000000000000000000000000000)
return -1;
else return 1;
}
}
/**
* Calculate sign (x - y). Revert if either argument is NaN, or both
* arguments are infinities of the same sign.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return sign (x - y)
*/
function cmp(bytes16 x, bytes16 y) internal pure returns (int8) {
unchecked {
uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN
uint128 absoluteY = uint128(y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
require(absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN
// Not infinities of the same sign
require(x != y || absoluteX < 0x7FFF0000000000000000000000000000);
if (x == y) return 0;
else {
bool negativeX =
uint128(x) >= 0x80000000000000000000000000000000;
bool negativeY =
uint128(y) >= 0x80000000000000000000000000000000;
if (negativeX) {
if (negativeY) return absoluteX > absoluteY ? -1 : int8(1);
else return -1;
} else {
if (negativeY) return 1;
else return absoluteX > absoluteY ? int8(1) : -1;
}
}
}
}
/**
* Test whether x equals y. NaN, infinity, and -infinity are not equal to
* anything.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return true if x equals to y, false otherwise
*/
function eq(bytes16 x, bytes16 y) internal pure returns (bool) {
unchecked {
if (x == y) {
return
uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF <
0x7FFF0000000000000000000000000000;
} else return false;
}
}
/**
* Calculate x + y. Special values behave in the following way:
*
* NaN + x = NaN for any x.
* Infinity + x = Infinity for any finite x.
* -Infinity + x = -Infinity for any finite x.
* Infinity + Infinity = Infinity.
* -Infinity + -Infinity = -Infinity.
* Infinity + -Infinity = -Infinity + Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function add(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y) return x;
else return NaN;
} else return x;
} else if (yExponent == 0x7FFF) return y;
else {
bool xSign = uint128(x) >= 0x80000000000000000000000000000000;
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
bool ySign = uint128(y) >= 0x80000000000000000000000000000000;
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0)
return y == _NEGATIVE_ZERO ? _POSITIVE_ZERO : y;
else if (ySignifier == 0)
return x == _NEGATIVE_ZERO ? _POSITIVE_ZERO : x;
else {
int256 delta = int256(xExponent) - int256(yExponent);
if (xSign == ySign) {
if (delta > 112) return x;
else if (delta > 0) ySignifier >>= uint256(delta);
else if (delta < -112) return y;
else if (delta < 0) {
xSignifier >>= uint256(-delta);
xExponent = yExponent;
}
xSignifier += ySignifier;
if (xSignifier >= 0x20000000000000000000000000000) {
xSignifier >>= 1;
xExponent += 1;
}
if (xExponent == 0x7FFF)
return
xSign ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else {
if (xSignifier < 0x10000000000000000000000000000)
xExponent = 0;
else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
return
bytes16(
uint128(
(
xSign
? 0x80000000000000000000000000000000
: 0
) |
(xExponent << 112) |
xSignifier
)
);
}
} else {
if (delta > 0) {
xSignifier <<= 1;
xExponent -= 1;
} else if (delta < 0) {
ySignifier <<= 1;
xExponent = yExponent - 1;
}
if (delta > 112) ySignifier = 1;
else if (delta > 1)
ySignifier =
((ySignifier - 1) >> uint256(delta - 1)) +
1;
else if (delta < -112) xSignifier = 1;
else if (delta < -1)
xSignifier =
((xSignifier - 1) >> uint256(-delta - 1)) +
1;
if (xSignifier >= ySignifier) xSignifier -= ySignifier;
else {
xSignifier = ySignifier - xSignifier;
xSign = ySign;
}
if (xSignifier == 0) return _POSITIVE_ZERO;
uint256 msb = mostSignificantBit(xSignifier);
if (msb == 113) {
xSignifier =
(xSignifier >> 1) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent += 1;
} else if (msb < 112) {
uint256 shift = 112 - msb;
if (xExponent > shift) {
xSignifier =
(xSignifier << shift) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent -= shift;
} else {
xSignifier <<= xExponent - 1;
xExponent = 0;
}
} else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF)
return
xSign ? _NEGATIVE_INFINITY : _POSITIVE_INFINITY;
else
return
bytes16(
uint128(
(
xSign
? 0x80000000000000000000000000000000
: 0
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
}
}
/**
* Calculate x - y. Special values behave in the following way:
*
* NaN - x = NaN for any x.
* Infinity - x = Infinity for any finite x.
* -Infinity - x = -Infinity for any finite x.
* Infinity - -Infinity = Infinity.
* -Infinity - Infinity = -Infinity.
* Infinity - Infinity = -Infinity - -Infinity = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function sub(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {return add(x, y ^ 0x80000000000000000000000000000000);}
}
/**
* Calculate x * y. Special values behave in the following way:
*
* NaN * x = NaN for any x.
* Infinity * x = Infinity for any finite positive x.
* Infinity * x = -Infinity for any finite negative x.
* -Infinity * x = -Infinity for any finite positive x.
* -Infinity * x = Infinity for any finite negative x.
* Infinity * 0 = NaN.
* -Infinity * 0 = NaN.
* Infinity * Infinity = Infinity.
* Infinity * -Infinity = -Infinity.
* -Infinity * Infinity = -Infinity.
* -Infinity * -Infinity = Infinity.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function mul(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) {
if (x == y)
return x ^ (y & 0x80000000000000000000000000000000);
else if (x ^ y == 0x80000000000000000000000000000000)
return x | y;
else return NaN;
} else {
if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
}
} else if (yExponent == 0x7FFF) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else return y ^ (x & 0x80000000000000000000000000000000);
} else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
xSignifier *= ySignifier;
if (xSignifier == 0)
return
(x ^ y) & 0x80000000000000000000000000000000 > 0
? _NEGATIVE_ZERO
: _POSITIVE_ZERO;
xExponent += yExponent;
uint256 msb =
xSignifier >=
0x200000000000000000000000000000000000000000000000000000000
? 225
: xSignifier >=
0x100000000000000000000000000000000000000000000000000000000
? 224
: mostSignificantBit(xSignifier);
if (xExponent + msb < 16496) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb < 16608) {
// Subnormal
if (xExponent < 16496) xSignifier >>= 16496 - xExponent;
else if (xExponent > 16496)
xSignifier <<= xExponent - 16496;
xExponent = 0;
} else if (xExponent + msb > 49373) {
xExponent = 0x7FFF;
xSignifier = 0;
} else {
if (msb > 112) xSignifier >>= msb - 112;
else if (msb < 112) xSignifier <<= 112 - msb;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb - 16607;
}
return
bytes16(
uint128(
uint128(
(x ^ y) & 0x80000000000000000000000000000000
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
/**
* Calculate x / y. Special values behave in the following way:
*
* NaN / x = NaN for any x.
* x / NaN = NaN for any x.
* Infinity / x = Infinity for any finite non-negative x.
* Infinity / x = -Infinity for any finite negative x including -0.
* -Infinity / x = -Infinity for any finite non-negative x.
* -Infinity / x = Infinity for any finite negative x including -0.
* x / Infinity = 0 for any finite non-negative x.
* x / -Infinity = -0 for any finite non-negative x.
* x / Infinity = -0 for any finite non-negative x including -0.
* x / -Infinity = 0 for any finite non-negative x including -0.
*
* Infinity / Infinity = NaN.
* Infinity / -Infinity = -NaN.
* -Infinity / Infinity = -NaN.
* -Infinity / -Infinity = NaN.
*
* Division by zero behaves in the following way:
*
* x / 0 = Infinity for any finite positive x.
* x / -0 = -Infinity for any finite positive x.
* x / 0 = -Infinity for any finite negative x.
* x / -0 = Infinity for any finite negative x.
* 0 / 0 = NaN.
* 0 / -0 = NaN.
* -0 / 0 = NaN.
* -0 / -0 = NaN.
*
* @param x quadruple precision number
* @param y quadruple precision number
* @return quadruple precision number
*/
function div(bytes16 x, bytes16 y) internal pure returns (bytes16) {
unchecked {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 yExponent = (uint128(y) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) {
if (yExponent == 0x7FFF) return NaN;
else return x ^ (y & 0x80000000000000000000000000000000);
} else if (yExponent == 0x7FFF) {
if (y & 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF != 0) return NaN;
else
return
_POSITIVE_ZERO |
((x ^ y) & 0x80000000000000000000000000000000);
} else if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) {
if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
else
return
_POSITIVE_INFINITY |
((x ^ y) & 0x80000000000000000000000000000000);
} else {
uint256 ySignifier =
uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (yExponent == 0) yExponent = 1;
else ySignifier |= 0x10000000000000000000000000000;
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) {
if (xSignifier != 0) {
uint256 shift = 226 - mostSignificantBit(xSignifier);
xSignifier <<= shift;
xExponent = 1;
yExponent += shift - 114;
}
} else {
xSignifier =
(xSignifier | 0x10000000000000000000000000000) <<
114;
}
xSignifier = xSignifier / ySignifier;
if (xSignifier == 0)
return
(x ^ y) & 0x80000000000000000000000000000000 > 0
? _NEGATIVE_ZERO
: _POSITIVE_ZERO;
assert(xSignifier >= 0x1000000000000000000000000000);
uint256 msb =
xSignifier >= 0x80000000000000000000000000000
? mostSignificantBit(xSignifier)
: xSignifier >= 0x40000000000000000000000000000
? 114
: xSignifier >= 0x20000000000000000000000000000
? 113
: 112;
if (xExponent + msb > yExponent + 16497) {
// Overflow
xExponent = 0x7FFF;
xSignifier = 0;
} else if (xExponent + msb + 16380 < yExponent) {
// Underflow
xExponent = 0;
xSignifier = 0;
} else if (xExponent + msb + 16268 < yExponent) {
// Subnormal
if (xExponent + 16380 > yExponent)
xSignifier <<= xExponent + 16380 - yExponent;
else if (xExponent + 16380 < yExponent)
xSignifier >>= yExponent - xExponent - 16380;
xExponent = 0;
} else {
// Normal
if (msb > 112) xSignifier >>= msb - 112;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
xExponent = xExponent + msb + 16269 - yExponent;
}
return
bytes16(
uint128(
uint128(
(x ^ y) & 0x80000000000000000000000000000000
) |
(xExponent << 112) |
xSignifier
)
);
}
}
}
/**
* Calculate -x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function neg(bytes16 x) internal pure returns (bytes16) {
unchecked {return x ^ 0x80000000000000000000000000000000;}
}
/**
* Calculate |x|.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function abs(bytes16 x) internal pure returns (bytes16) {
unchecked {return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;}
}
/**
* Calculate square root of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function sqrt(bytes16 x) internal pure returns (bytes16) {
unchecked {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return _POSITIVE_ZERO;
bool oddExponent = xExponent & 0x1 == 0;
xExponent = (xExponent + 16383) >> 1;
if (oddExponent) {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 113;
else {
uint256 msb = mostSignificantBit(xSignifier);
uint256 shift = (226 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
} else {
if (xSignifier >= 0x10000000000000000000000000000)
xSignifier <<= 112;
else {
uint256 msb = mostSignificantBit(xSignifier);
uint256 shift = (225 - msb) & 0xFE;
xSignifier <<= shift;
xExponent -= (shift - 112) >> 1;
}
}
uint256 r = 0x10000000000000000000000000000;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1;
r = (r + xSignifier / r) >> 1; // Seven iterations should be enough
uint256 r1 = xSignifier / r;
if (r1 < r) r = r1;
return
bytes16(
uint128(
(xExponent << 112) |
(r & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
}
}
}
}
/**
* Calculate binary logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function log_2(bytes16 x) internal pure returns (bytes16) {
unchecked {
if (uint128(x) > 0x80000000000000000000000000000000) return NaN;
else if (x == 0x3FFF0000000000000000000000000000)
return _POSITIVE_ZERO;
else {
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
if (xExponent == 0x7FFF) return x;
else {
uint256 xSignifier =
uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xSignifier == 0) return _NEGATIVE_INFINITY;
bool resultNegative;
uint256 resultExponent = 16495;
uint256 resultSignifier;
if (xExponent >= 0x3FFF) {
resultNegative = false;
resultSignifier = xExponent - 0x3FFF;
xSignifier <<= 15;
} else {
resultNegative = true;
if (xSignifier >= 0x10000000000000000000000000000) {
resultSignifier = 0x3FFE - xExponent;
xSignifier <<= 15;
} else {
uint256 msb = mostSignificantBit(xSignifier);
resultSignifier = 16493 - msb;
xSignifier <<= 127 - msb;
}
}
if (xSignifier == 0x80000000000000000000000000000000) {
if (resultNegative) resultSignifier += 1;
uint256 shift =
112 - mostSignificantBit(resultSignifier);
resultSignifier <<= shift;
resultExponent -= shift;
} else {
uint256 bb = resultNegative ? 1 : 0;
while (
resultSignifier < 0x10000000000000000000000000000
) {
resultSignifier <<= 1;
resultExponent -= 1;
xSignifier *= xSignifier;
uint256 b = xSignifier >> 255;
resultSignifier += b ^ bb;
xSignifier >>= 127 + b;
}
}
return
bytes16(
uint128(
(
resultNegative
? 0x80000000000000000000000000000000
: 0
) |
(resultExponent << 112) |
(resultSignifier &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
}
}
}
}
/**
* Calculate natural logarithm of x. Return NaN on negative x excluding -0.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function ln(bytes16 x) internal pure returns (bytes16) {
unchecked {return mul(log_2(x), 0x3FFE62E42FEFA39EF35793C7673007E5);}
}
/**
* Calculate 2^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function pow_2(bytes16 x) internal pure returns (bytes16) {
unchecked {
bool xNegative = uint128(x) > 0x80000000000000000000000000000000;
uint256 xExponent = (uint128(x) >> 112) & 0x7FFF;
uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xExponent == 0x7FFF && xSignifier != 0) return NaN;
else if (xExponent > 16397)
return xNegative ? _POSITIVE_ZERO : _POSITIVE_INFINITY;
else if (xExponent < 16255)
return 0x3FFF0000000000000000000000000000;
else {
if (xExponent == 0) xExponent = 1;
else xSignifier |= 0x10000000000000000000000000000;
if (xExponent > 16367) xSignifier <<= xExponent - 16367;
else if (xExponent < 16367) xSignifier >>= 16367 - xExponent;
if (
xNegative &&
xSignifier > 0x406E00000000000000000000000000000000
) return _POSITIVE_ZERO;
if (
!xNegative &&
xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
) return _POSITIVE_INFINITY;
uint256 resultExponent = xSignifier >> 128;
xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
if (xNegative && xSignifier != 0) {
xSignifier = ~xSignifier;
resultExponent += 1;
}
uint256 resultSignifier = 0x80000000000000000000000000000000;
if (xSignifier & 0x80000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x16A09E667F3BCC908B2FB1366EA957D3E) >>
128;
if (xSignifier & 0x40000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1306FE0A31B7152DE8D5A46305C85EDEC) >>
128;
if (xSignifier & 0x20000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1172B83C7D517ADCDF7C8C50EB14A791F) >>
128;
if (xSignifier & 0x10000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10B5586CF9890F6298B92B71842A98363) >>
128;
if (xSignifier & 0x8000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1059B0D31585743AE7C548EB68CA417FD) >>
128;
if (xSignifier & 0x4000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x102C9A3E778060EE6F7CACA4F7A29BDE8) >>
128;
if (xSignifier & 0x2000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10163DA9FB33356D84A66AE336DCDFA3F) >>
128;
if (xSignifier & 0x1000000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100B1AFA5ABCBED6129AB13EC11DC9543) >>
128;
if (xSignifier & 0x800000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10058C86DA1C09EA1FF19D294CF2F679B) >>
128;
if (xSignifier & 0x400000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1002C605E2E8CEC506D21BFC89A23A00F) >>
128;
if (xSignifier & 0x200000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100162F3904051FA128BCA9C55C31E5DF) >>
128;
if (xSignifier & 0x100000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000B175EFFDC76BA38E31671CA939725) >>
128;
if (xSignifier & 0x80000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100058BA01FB9F96D6CACD4B180917C3D) >>
128;
if (xSignifier & 0x40000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10002C5CC37DA9491D0985C348C68E7B3) >>
128;
if (xSignifier & 0x20000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000162E525EE054754457D5995292026) >>
128;
if (xSignifier & 0x10000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000B17255775C040618BF4A4ADE83FC) >>
128;
if (xSignifier & 0x8000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >>
128;
if (xSignifier & 0x4000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >>
128;
if (xSignifier & 0x2000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000162E43F4F831060E02D839A9D16D) >>
128;
if (xSignifier & 0x1000000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000B1721BCFC99D9F890EA06911763) >>
128;
if (xSignifier & 0x800000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000058B90CF1E6D97F9CA14DBCC1628) >>
128;
if (xSignifier & 0x400000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000002C5C863B73F016468F6BAC5CA2B) >>
128;
if (xSignifier & 0x200000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000162E430E5A18F6119E3C02282A5) >>
128;
if (xSignifier & 0x100000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000B1721835514B86E6D96EFD1BFE) >>
128;
if (xSignifier & 0x80000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000058B90C0B48C6BE5DF846C5B2EF) >>
128;
if (xSignifier & 0x40000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000002C5C8601CC6B9E94213C72737A) >>
128;
if (xSignifier & 0x20000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000162E42FFF037DF38AA2B219F06) >>
128;
if (xSignifier & 0x10000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000B17217FBA9C739AA5819F44F9) >>
128;
if (xSignifier & 0x8000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000058B90BFCDEE5ACD3C1CEDC823) >>
128;
if (xSignifier & 0x4000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000002C5C85FE31F35A6A30DA1BE50) >>
128;
if (xSignifier & 0x2000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000162E42FF0999CE3541B9FFFCF) >>
128;
if (xSignifier & 0x1000000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000B17217F80F4EF5AADDA45554) >>
128;
if (xSignifier & 0x800000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000058B90BFBF8479BD5A81B51AD) >>
128;
if (xSignifier & 0x400000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000002C5C85FDF84BD62AE30A74CC) >>
128;
if (xSignifier & 0x200000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000162E42FEFB2FED257559BDAA) >>
128;
if (xSignifier & 0x100000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000B17217F7D5A7716BBA4A9AE) >>
128;
if (xSignifier & 0x80000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000058B90BFBE9DDBAC5E109CCE) >>
128;
if (xSignifier & 0x40000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000002C5C85FDF4B15DE6F17EB0D) >>
128;
if (xSignifier & 0x20000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000162E42FEFA494F1478FDE05) >>
128;
if (xSignifier & 0x10000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000B17217F7D20CF927C8E94C) >>
128;
if (xSignifier & 0x8000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000058B90BFBE8F71CB4E4B33D) >>
128;
if (xSignifier & 0x4000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000002C5C85FDF477B662B26945) >>
128;
if (xSignifier & 0x2000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000162E42FEFA3AE53369388C) >>
128;
if (xSignifier & 0x1000000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000B17217F7D1D351A389D40) >>
128;
if (xSignifier & 0x800000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000058B90BFBE8E8B2D3D4EDE) >>
128;
if (xSignifier & 0x400000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000002C5C85FDF4741BEA6E77E) >>
128;
if (xSignifier & 0x200000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000162E42FEFA39FE95583C2) >>
128;
if (xSignifier & 0x100000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000B17217F7D1CFB72B45E1) >>
128;
if (xSignifier & 0x80000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000058B90BFBE8E7CC35C3F0) >>
128;
if (xSignifier & 0x40000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000002C5C85FDF473E242EA38) >>
128;
if (xSignifier & 0x20000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000162E42FEFA39F02B772C) >>
128;
if (xSignifier & 0x10000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000B17217F7D1CF7D83C1A) >>
128;
if (xSignifier & 0x8000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000058B90BFBE8E7BDCBE2E) >>
128;
if (xSignifier & 0x4000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000002C5C85FDF473DEA871F) >>
128;
if (xSignifier & 0x2000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000162E42FEFA39EF44D91) >>
128;
if (xSignifier & 0x1000000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000B17217F7D1CF79E949) >>
128;
if (xSignifier & 0x800000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000058B90BFBE8E7BCE544) >>
128;
if (xSignifier & 0x400000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000002C5C85FDF473DE6ECA) >>
128;
if (xSignifier & 0x200000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000162E42FEFA39EF366F) >>
128;
if (xSignifier & 0x100000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000B17217F7D1CF79AFA) >>
128;
if (xSignifier & 0x80000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000058B90BFBE8E7BCD6D) >>
128;
if (xSignifier & 0x40000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000002C5C85FDF473DE6B2) >>
128;
if (xSignifier & 0x20000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000162E42FEFA39EF358) >>
128;
if (xSignifier & 0x10000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000B17217F7D1CF79AB) >>
128;
if (xSignifier & 0x8000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000058B90BFBE8E7BCD5) >>
128;
if (xSignifier & 0x4000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000002C5C85FDF473DE6A) >>
128;
if (xSignifier & 0x2000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000162E42FEFA39EF34) >>
128;
if (xSignifier & 0x1000000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000B17217F7D1CF799) >>
128;
if (xSignifier & 0x800000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000058B90BFBE8E7BCC) >>
128;
if (xSignifier & 0x400000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000002C5C85FDF473DE5) >>
128;
if (xSignifier & 0x200000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000162E42FEFA39EF2) >>
128;
if (xSignifier & 0x100000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000B17217F7D1CF78) >>
128;
if (xSignifier & 0x80000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000058B90BFBE8E7BB) >>
128;
if (xSignifier & 0x40000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000002C5C85FDF473DD) >>
128;
if (xSignifier & 0x20000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000162E42FEFA39EE) >>
128;
if (xSignifier & 0x10000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000B17217F7D1CF6) >>
128;
if (xSignifier & 0x8000000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000058B90BFBE8E7A) >>
128;
if (xSignifier & 0x4000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000002C5C85FDF473C) >>
128;
if (xSignifier & 0x2000000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000162E42FEFA39D) >>
128;
if (xSignifier & 0x1000000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000B17217F7D1CE) >>
128;
if (xSignifier & 0x800000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000058B90BFBE8E6) >>
128;
if (xSignifier & 0x400000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000002C5C85FDF472) >>
128;
if (xSignifier & 0x200000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000162E42FEFA38) >>
128;
if (xSignifier & 0x100000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000B17217F7D1B) >>
128;
if (xSignifier & 0x80000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000058B90BFBE8D) >>
128;
if (xSignifier & 0x40000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000002C5C85FDF46) >>
128;
if (xSignifier & 0x20000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000162E42FEFA2) >>
128;
if (xSignifier & 0x10000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000B17217F7D0) >>
128;
if (xSignifier & 0x8000000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000058B90BFBE7) >>
128;
if (xSignifier & 0x4000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000002C5C85FDF3) >>
128;
if (xSignifier & 0x2000000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000162E42FEF9) >>
128;
if (xSignifier & 0x1000000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000B17217F7C) >>
128;
if (xSignifier & 0x800000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000058B90BFBD) >>
128;
if (xSignifier & 0x400000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000002C5C85FDE) >>
128;
if (xSignifier & 0x200000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000162E42FEE) >>
128;
if (xSignifier & 0x100000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000B17217F6) >>
128;
if (xSignifier & 0x80000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000058B90BFA) >>
128;
if (xSignifier & 0x40000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000002C5C85FC) >>
128;
if (xSignifier & 0x20000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000162E42FD) >>
128;
if (xSignifier & 0x10000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000B17217E) >>
128;
if (xSignifier & 0x8000000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000058B90BE) >>
128;
if (xSignifier & 0x4000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000002C5C85E) >>
128;
if (xSignifier & 0x2000000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000162E42E) >>
128;
if (xSignifier & 0x1000000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000B17216) >>
128;
if (xSignifier & 0x800000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000058B90A) >>
128;
if (xSignifier & 0x400000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000002C5C84) >>
128;
if (xSignifier & 0x200000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000162E41) >>
128;
if (xSignifier & 0x100000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000B1720) >>
128;
if (xSignifier & 0x80000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000058B8F) >>
128;
if (xSignifier & 0x40000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000002C5C7) >>
128;
if (xSignifier & 0x20000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000162E3) >>
128;
if (xSignifier & 0x10000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000B171) >>
128;
if (xSignifier & 0x8000 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000058B8) >>
128;
if (xSignifier & 0x4000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000002C5B) >>
128;
if (xSignifier & 0x2000 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000162D) >>
128;
if (xSignifier & 0x1000 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000B16) >>
128;
if (xSignifier & 0x800 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000058A) >>
128;
if (xSignifier & 0x400 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000002C4) >>
128;
if (xSignifier & 0x200 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000161) >>
128;
if (xSignifier & 0x100 > 0)
resultSignifier =
(resultSignifier *
0x1000000000000000000000000000000B0) >>
128;
if (xSignifier & 0x80 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000057) >>
128;
if (xSignifier & 0x40 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000002B) >>
128;
if (xSignifier & 0x20 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000015) >>
128;
if (xSignifier & 0x10 > 0)
resultSignifier =
(resultSignifier *
0x10000000000000000000000000000000A) >>
128;
if (xSignifier & 0x8 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000004) >>
128;
if (xSignifier & 0x4 > 0)
resultSignifier =
(resultSignifier *
0x100000000000000000000000000000001) >>
128;
if (!xNegative) {
resultSignifier =
(resultSignifier >> 15) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent += 0x3FFF;
} else if (resultExponent <= 0x3FFE) {
resultSignifier =
(resultSignifier >> 15) &
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
resultExponent = 0x3FFF - resultExponent;
} else {
resultSignifier =
resultSignifier >>
(resultExponent - 16367);
resultExponent = 0;
}
return
bytes16(uint128((resultExponent << 112) | resultSignifier));
}
}
}
/**
* Calculate e^x.
*
* @param x quadruple precision number
* @return quadruple precision number
*/
function exp(bytes16 x) internal pure returns (bytes16) {
unchecked {return pow_2(mul(x, 0x3FFF71547652B82FE1777D0FFDA0D23A));}
}
/**
* Get index of the most significant non-zero bit in binary representation of
* x. Reverts if x is zero.
*
* @return index of the most significant non-zero bit in binary representation
* of x
*/
function mostSignificantBit(uint256 x) private pure returns (uint256) {
unchecked {
require(x > 0);
uint256 result = 0;
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
result += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
result += 64;
}
if (x >= 0x100000000) {
x >>= 32;
result += 32;
}
if (x >= 0x10000) {
x >>= 16;
result += 16;
}
if (x >= 0x100) {
x >>= 8;
result += 8;
}
if (x >= 0x10) {
x >>= 4;
result += 4;
}
if (x >= 0x4) {
x >>= 2;
result += 2;
}
if (x >= 0x2) result += 1; // No need to shift x anymore
return result;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "./IERC20Ubiquity.sol";
/// @title UAD stablecoin interface
/// @author Ubiquity Algorithmic Dollar
interface IUbiquityAlgorithmicDollar is IERC20Ubiquity {
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
function setIncentiveContract(address account, address incentive) external;
function incentiveContract(address account) external view returns (address);
}
// SPDX-License-Identifier: MIT
// !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !!
pragma solidity ^0.8.3;
interface ICurveFactory {
event BasePoolAdded(address base_pool, address implementat);
event MetaPoolDeployed(
address coin,
address base_pool,
uint256 A,
uint256 fee,
address deployer
);
function find_pool_for_coins(address _from, address _to)
external
view
returns (address);
function find_pool_for_coins(
address _from,
address _to,
uint256 i
) external view returns (address);
function get_n_coins(address _pool)
external
view
returns (uint256, uint256);
function get_coins(address _pool) external view returns (address[2] memory);
function get_underlying_coins(address _pool)
external
view
returns (address[8] memory);
function get_decimals(address _pool)
external
view
returns (uint256[2] memory);
function get_underlying_decimals(address _pool)
external
view
returns (uint256[8] memory);
function get_rates(address _pool) external view returns (uint256[2] memory);
function get_balances(address _pool)
external
view
returns (uint256[2] memory);
function get_underlying_balances(address _pool)
external
view
returns (uint256[8] memory);
function get_A(address _pool) external view returns (uint256);
function get_fees(address _pool) external view returns (uint256, uint256);
function get_admin_balances(address _pool)
external
view
returns (uint256[2] memory);
function get_coin_indices(
address _pool,
address _from,
address _to
)
external
view
returns (
int128,
int128,
bool
);
function add_base_pool(
address _base_pool,
address _metapool_implementation,
address _fee_receiver
) external;
function deploy_metapool(
address _base_pool,
string memory _name,
string memory _symbol,
address _coin,
uint256 _A,
uint256 _fee
) external returns (address);
function commit_transfer_ownership(address addr) external;
function accept_transfer_ownership() external;
function set_fee_receiver(address _base_pool, address _fee_receiver)
external;
function convert_fees() external returns (bool);
function admin() external view returns (address);
function future_admin() external view returns (address);
function pool_list(uint256 arg0) external view returns (address);
function pool_count() external view returns (uint256);
function base_pool_list(uint256 arg0) external view returns (address);
function base_pool_count() external view returns (uint256);
function fee_receiver(address arg0) external view returns (address);
}
// SPDX-License-Identifier: UNLICENSED
// !! THIS FILE WAS AUTOGENERATED BY abi-to-sol. SEE BELOW FOR SOURCE. !!
pragma solidity ^0.8.3;
interface IMetaPool {
event Transfer(
address indexed sender,
address indexed receiver,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event TokenExchange(
address indexed buyer,
int128 sold_id,
uint256 tokens_sold,
int128 bought_id,
uint256 tokens_bought
);
event TokenExchangeUnderlying(
address indexed buyer,
int128 sold_id,
uint256 tokens_sold,
int128 bought_id,
uint256 tokens_bought
);
event AddLiquidity(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 invariant,
uint256 token_supply
);
event RemoveLiquidity(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 token_supply
);
event RemoveLiquidityOne(
address indexed provider,
uint256 token_amount,
uint256 coin_amount,
uint256 token_supply
);
event RemoveLiquidityImbalance(
address indexed provider,
uint256[2] token_amounts,
uint256[2] fees,
uint256 invariant,
uint256 token_supply
);
event CommitNewAdmin(uint256 indexed deadline, address indexed admin);
event NewAdmin(address indexed admin);
event CommitNewFee(
uint256 indexed deadline,
uint256 fee,
uint256 admin_fee
);
event NewFee(uint256 fee, uint256 admin_fee);
event RampA(
uint256 old_A,
uint256 new_A,
uint256 initial_time,
uint256 future_time
);
event StopRampA(uint256 A, uint256 t);
function initialize(
string memory _name,
string memory _symbol,
address _coin,
uint256 _decimals,
uint256 _A,
uint256 _fee,
address _admin
) external;
function decimals() external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function get_previous_balances() external view returns (uint256[2] memory);
function get_balances() external view returns (uint256[2] memory);
function get_twap_balances(
uint256[2] memory _first_balances,
uint256[2] memory _last_balances,
uint256 _time_elapsed
) external view returns (uint256[2] memory);
function get_price_cumulative_last()
external
view
returns (uint256[2] memory);
function admin_fee() external view returns (uint256);
function A() external view returns (uint256);
function A_precise() external view returns (uint256);
function get_virtual_price() external view returns (uint256);
function calc_token_amount(uint256[2] memory _amounts, bool _is_deposit)
external
view
returns (uint256);
function calc_token_amount(
uint256[2] memory _amounts,
bool _is_deposit,
bool _previous
) external view returns (uint256);
function add_liquidity(uint256[2] memory _amounts, uint256 _min_mint_amount)
external
returns (uint256);
function add_liquidity(
uint256[2] memory _amounts,
uint256 _min_mint_amount,
address _receiver
) external returns (uint256);
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_dy(
int128 i,
int128 j,
uint256 dx,
uint256[2] memory _balances
) external view returns (uint256);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx,
uint256[2] memory _balances
) external view returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address _receiver
) external returns (uint256);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
address _receiver
) external returns (uint256);
function remove_liquidity(
uint256 _burn_amount,
uint256[2] memory _min_amounts
) external returns (uint256[2] memory);
function remove_liquidity(
uint256 _burn_amount,
uint256[2] memory _min_amounts,
address _receiver
) external returns (uint256[2] memory);
function remove_liquidity_imbalance(
uint256[2] memory _amounts,
uint256 _max_burn_amount
) external returns (uint256);
function remove_liquidity_imbalance(
uint256[2] memory _amounts,
uint256 _max_burn_amount,
address _receiver
) external returns (uint256);
function calc_withdraw_one_coin(uint256 _burn_amount, int128 i)
external
view
returns (uint256);
function calc_withdraw_one_coin(
uint256 _burn_amount,
int128 i,
bool _previous
) external view returns (uint256);
function remove_liquidity_one_coin(
uint256 _burn_amount,
int128 i,
uint256 _min_received
) external returns (uint256);
function remove_liquidity_one_coin(
uint256 _burn_amount,
int128 i,
uint256 _min_received,
address _receiver
) external returns (uint256);
function ramp_A(uint256 _future_A, uint256 _future_time) external;
function stop_ramp_A() external;
function admin_balances(uint256 i) external view returns (uint256);
function withdraw_admin_fees() external;
function admin() external view returns (address);
function coins(uint256 arg0) external view returns (address);
function balances(uint256 arg0) external view returns (uint256);
function fee() external view returns (uint256);
function block_timestamp_last() external view returns (uint256);
function initial_A() external view returns (uint256);
function future_A() external view returns (uint256);
function initial_A_time() external view returns (uint256);
function future_A_time() external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function balanceOf(address arg0) external view returns (uint256);
function allowance(address arg0, address arg1)
external
view
returns (uint256);
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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: Apache-2.0
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title ERC20 Ubiquiti preset interface
/// @author Ubiquity Algorithmic Dollar
interface IERC20Ubiquity is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(address indexed _burned, uint256 _amount);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
| ERC20 Ubiquiti preset interface Ubiquity Algorithmic Dollar ----------- Events ----------- ----------- State changing api ----------- ----------- Burner only state changing api ----------- ----------- Minter only state changing api ----------- | interface IERC20Ubiquity is IERC20 {
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(address indexed _burned, uint256 _amount);
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function burnFrom(address account, uint256 amount) external;
function mint(address account, uint256 amount) external;
pragma solidity ^0.8.3;
}
| 96,267 |
/*
An ERC20 compliant token that is linked to an external identifier. For exmaple, Meetup.com
This software 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 MIT Licence for further details.
<https://opensource.org/licenses/MIT>.
*/
pragma solidity ^0.4.15;
contract ERC20Token
{
/* State */
// The Total supply of tokens
uint256 totSupply;
/// @return Token symbol
string sym;
string nam;
uint8 public decimals = 0;
// Token ownership mapping
mapping (address => uint256) balances;
// Allowances mapping
mapping (address => mapping (address => uint256)) allowed;
/* Events */
// Triggered when tokens are transferred.
event Transfer(
address indexed from,
address indexed to,
uint256 value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(
address indexed owner,
address indexed spender,
uint256 value);
/* Funtions Public */
function symbol() public constant returns (string)
{
return sym;
}
function name() public constant returns (string)
{
return nam;
}
// Using an explicit getter allows for function overloading
function totalSupply() public constant returns (uint256)
{
return totSupply;
}
// Using an explicit getter allows for function overloading
function balanceOf(address holderAddress) public constant returns (uint256 balance)
{
return balances[holderAddress];
}
// Using an explicit getter allows for function overloading
function allowance(address ownerAddress, address spenderAddress) public constant returns (uint256 remaining)
{
return allowed[ownerAddress][spenderAddress];
}
// Send amount amount of tokens to address _to
function transfer(address toAddress, uint256 amount) public returns (bool success)
{
return xfer(msg.sender, toAddress, amount);
}
// Send amount amount of tokens from address _from to address _to
function transferFrom(address fromAddress, address toAddress, uint256 amount) public returns (bool success)
{
require(amount <= allowed[fromAddress][msg.sender]);
allowed[fromAddress][msg.sender] -= amount;
xfer(fromAddress, toAddress, amount);
return true;
}
// Process a transfer internally.
function xfer(address fromAddress, address toAddress, uint amount) internal returns (bool success)
{
require(amount <= balances[fromAddress]);
balances[fromAddress] -= amount;
balances[toAddress] += amount;
Transfer(fromAddress, toAddress, amount);
return true;
}
// Approves a third-party spender
function approve(address spender, uint256 value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((value == 0) || (allowed[msg.sender][spender] == 0));
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
return true;
}
/**
* 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] + 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 - subtractedValue;
}
Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
}
contract TransferableMeetupToken is ERC20Token
{
address owner = msg.sender;
function TransferableMeetupToken(string tokenSymbol, string toeknName)
{
sym = tokenSymbol;
nam = toeknName;
}
event Issue(
address indexed toAddress,
uint256 amount,
string externalId,
string reason);
event Redeem(
address indexed fromAddress,
uint256 amount);
function issue(address toAddress, uint amount, string externalId, string reason) public returns (bool)
{
require(owner == msg.sender);
totSupply += amount;
balances[toAddress] += amount;
Issue(toAddress, amount, externalId, reason);
Transfer(0x0, toAddress, amount);
return true;
}
function redeem(uint amount) public returns (bool)
{
require(balances[msg.sender] >= amount);
totSupply -= amount;
balances[msg.sender] -= amount;
Redeem(msg.sender, amount);
Transfer(msg.sender, 0x0, amount);
return true;
}
} | Send amount amount of tokens to address _to | function transfer(address toAddress, uint256 amount) public returns (bool success)
{
return xfer(msg.sender, toAddress, amount);
}
| 991,618 |
/**
*Submitted for verification at Etherscan.io on 2021-07-29
*/
// Sources flattened with hardhat v2.3.0 https://hardhat.org
// File contracts/interfaces/ICoFiXMapping.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev The interface defines methods for CoFiX builtin contract address mapping
interface ICoFiXMapping {
/// @dev Set the built-in contract address of the system
/// @param cofiToken Address of CoFi token contract
/// @param cofiNode Address of CoFi Node contract
/// @param cofixDAO ICoFiXDAO implementation contract address
/// @param cofixRouter ICoFiXRouter implementation contract address for CoFiX
/// @param cofixController ICoFiXController implementation contract address
/// @param cofixVaultForStaking ICoFiXVaultForStaking implementation contract address
function setBuiltinAddress(
address cofiToken,
address cofiNode,
address cofixDAO,
address cofixRouter,
address cofixController,
address cofixVaultForStaking
) external;
/// @dev Get the built-in contract address of the system
/// @return cofiToken Address of CoFi token contract
/// @return cofiNode Address of CoFi Node contract
/// @return cofixDAO ICoFiXDAO implementation contract address
/// @return cofixRouter ICoFiXRouter implementation contract address for CoFiX
/// @return cofixController ICoFiXController implementation contract address
function getBuiltinAddress() external view returns (
address cofiToken,
address cofiNode,
address cofixDAO,
address cofixRouter,
address cofixController,
address cofixVaultForStaking
);
/// @dev Get address of CoFi token contract
/// @return Address of CoFi Node token contract
function getCoFiTokenAddress() external view returns (address);
/// @dev Get address of CoFi Node contract
/// @return Address of CoFi Node contract
function getCoFiNodeAddress() external view returns (address);
/// @dev Get ICoFiXDAO implementation contract address
/// @return ICoFiXDAO implementation contract address
function getCoFiXDAOAddress() external view returns (address);
/// @dev Get ICoFiXRouter implementation contract address for CoFiX
/// @return ICoFiXRouter implementation contract address for CoFiX
function getCoFiXRouterAddress() external view returns (address);
/// @dev Get ICoFiXController implementation contract address
/// @return ICoFiXController implementation contract address
function getCoFiXControllerAddress() external view returns (address);
/// @dev Get ICoFiXVaultForStaking implementation contract address
/// @return ICoFiXVaultForStaking implementation contract address
function getCoFiXVaultForStakingAddress() external view returns (address);
/// @dev Registered address. The address registered here is the address accepted by CoFiX system
/// @param key The key
/// @param addr Destination address. 0 means to delete the registration information
function registerAddress(string calldata key, address addr) external;
/// @dev Get registered address
/// @param key The key
/// @return Destination address. 0 means empty
function checkAddress(string calldata key) external view returns (address);
}
// File contracts/interfaces/ICoFiXGovernance.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the governance methods
interface ICoFiXGovernance is ICoFiXMapping {
/// @dev Set governance authority
/// @param addr Destination address
/// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function setGovernance(address addr, uint flag) external;
/// @dev Get governance rights
/// @param addr Destination address
/// @return Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function getGovernance(address addr) external view returns (uint);
/// @dev Check whether the target address has governance rights for the given target
/// @param addr Destination address
/// @param flag Permission weight. The permission of the target address must be greater than this weight
/// to pass the check
/// @return True indicates permission
function checkGovernance(address addr, uint flag) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/libs/TransferHelper.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File contracts/interfaces/ICoFiXDAO.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev This interface defines the DAO methods
interface ICoFiXDAO {
/// @dev Application Flag Changed event
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
event ApplicationChanged(address addr, uint flag);
/// @dev Configuration structure of CoFiXDAO contract
struct Config {
// Redeem status, 1 means normal
uint8 status;
// The number of CoFi redeem per block. 100
uint16 cofiPerBlock;
// The maximum number of CoFi in a single redeem. 30000
uint32 cofiLimit;
// Price deviation limit, beyond this upper limit stop redeem (10000 based). 1000
uint16 priceDeviationLimit;
}
/// @dev Modify configuration
/// @param config Configuration object
function setConfig(Config calldata config) external;
/// @dev Get configuration
/// @return Configuration object
function getConfig() external view returns (Config memory);
/// @dev Set DAO application
/// @param addr DAO application contract address
/// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization
function setApplication(address addr, uint flag) external;
/// @dev Check DAO application flag
/// @param addr DAO application contract address
/// @return Authorization flag, 1 means authorization, 0 means cancel authorization
function checkApplication(address addr) external view returns (uint);
/// @dev Set the exchange relationship between the token and the price of the anchored target currency.
/// For example, set USDC to anchor usdt, because USDC is 18 decimal places and usdt is 6 decimal places.
/// so exchange = 1e6 * 1 ether / 1e18 = 1e6
/// @param token Address of origin token
/// @param target Address of target anchor token
/// @param exchange Exchange rate of token and target
function setTokenExchange(address token, address target, uint exchange) external;
/// @dev Get the exchange relationship between the token and the price of the anchored target currency.
/// For example, set USDC to anchor usdt, because USDC is 18 decimal places and usdt is 6 decimal places.
/// so exchange = 1e6 * 1 ether / 1e18 = 1e6
/// @param token Address of origin token
/// @return target Address of target anchor token
/// @return exchange Exchange rate of token and target
function getTokenExchange(address token) external view returns (address target, uint exchange);
/// @dev Add reward
/// @param pool Destination pool
function addETHReward(address pool) external payable;
/// @dev The function returns eth rewards of specified pool
/// @param pool Destination pool
function totalETHRewards(address pool) external view returns (uint);
/// @dev Settlement
/// @param pool Destination pool. Indicates which pool to pay with
/// @param tokenAddress Token address of receiving funds (0 means ETH)
/// @param to Address to receive
/// @param value Amount to receive
function settle(address pool, address tokenAddress, address to, uint value) external payable;
/// @dev Redeem CoFi for ethers
/// @notice Eth fee will be charged
/// @param amount The amount of CoFi
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
function redeem(uint amount, address payback) external payable;
/// @dev Redeem CoFi for Token
/// @notice Eth fee will be charged
/// @param token The target token
/// @param amount The amount of CoFi
/// @param payback As the charging fee may change, it is suggested that the caller pay more fees,
/// and the excess fees will be returned through this address
function redeemToken(address token, uint amount, address payback) external payable;
/// @dev Get the current amount available for repurchase
function quotaOf() external view returns (uint);
}
// File contracts/CoFiXBase.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
// Router contract to interact with each CoFiXPair, no owner or governance
/// @dev Base contract of CoFiX
contract CoFiXBase {
// Address of CoFiToken contract
address constant COFI_TOKEN_ADDRESS = 0x1a23a6BfBAdB59fa563008c0fB7cf96dfCF34Ea1;
// Address of CoFiNode contract
address constant CNODE_TOKEN_ADDRESS = 0x558201DC4741efc11031Cdc3BC1bC728C23bF512;
// Genesis block number of CoFi
// CoFiToken contract is created at block height 11040156. However, because the mining algorithm of CoFiX1.0
// is different from that at present, a new mining algorithm is adopted from CoFiX2.1. The new algorithm
// includes the attenuation logic according to the block. Therefore, it is necessary to trace the block
// where the CoFi begins to decay. According to the circulation when CoFi2.0 is online, the new mining
// algorithm is used to deduce and convert the CoFi, and the new algorithm is used to mine the CoFiX2.1
// on-line flow, the actual block is 11040688
uint constant COFI_GENESIS_BLOCK = 11040688;
/// @dev ICoFiXGovernance implementation contract address
address public _governance;
/// @dev To support open-zeppelin/upgrades
/// @param governance ICoFiXGovernance implementation contract address
function initialize(address governance) virtual public {
require(_governance == address(0), "CoFiX:!initialize");
_governance = governance;
}
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(newGovernance) when overriding, and override method without onlyGovernance
/// @param newGovernance ICoFiXGovernance implementation contract address
function update(address newGovernance) public virtual {
address governance = _governance;
require(governance == msg.sender || ICoFiXGovernance(governance).checkGovernance(msg.sender, 0), "CoFiX:!gov");
_governance = newGovernance;
}
/// @dev Migrate funds from current contract to CoFiXDAO
/// @param tokenAddress Destination token address.(0 means eth)
/// @param value Migrate amount
function migrate(address tokenAddress, uint value) external onlyGovernance {
address to = ICoFiXGovernance(_governance).getCoFiXDAOAddress();
if (tokenAddress == address(0)) {
ICoFiXDAO(to).addETHReward { value: value } (address(0));
} else {
TransferHelper.safeTransfer(tokenAddress, to, value);
}
}
//---------modifier------------
modifier onlyGovernance() {
require(ICoFiXGovernance(_governance).checkGovernance(msg.sender, 0), "CoFiX:!gov");
_;
}
modifier noContract() {
require(msg.sender == tx.origin, "CoFiX:!contract");
_;
}
}
// File contracts/CoFiXMapping.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev The contract is for CoFiX builtin contract address mapping
abstract contract CoFiXMapping is CoFiXBase, ICoFiXMapping {
/// @dev Address of CoFi token contract
address _cofiToken;
/// @dev Address of CoFi Node contract
address _cofiNode;
/// @dev ICoFiXDAO implementation contract address
address _cofixDAO;
/// @dev ICoFiXRouter implementation contract address for CoFiX
address _cofixRouter;
/// @dev ICoFiXController implementation contract address
address _cofixController;
/// @dev ICoFiXVaultForStaking implementation contract address
address _cofixVaultForStaking;
/// @dev Address registered in the system
mapping(string=>address) _registeredAddress;
/// @dev Set the built-in contract address of the system
/// @param cofiToken Address of CoFi token contract
/// @param cofiNode Address of CoFi Node contract
/// @param cofixDAO ICoFiXDAO implementation contract address
/// @param cofixRouter ICoFiXRouter implementation contract address for CoFiX
/// @param cofixController ICoFiXController implementation contract address
/// @param cofixVaultForStaking ICoFiXVaultForStaking implementation contract address
function setBuiltinAddress(
address cofiToken,
address cofiNode,
address cofixDAO,
address cofixRouter,
address cofixController,
address cofixVaultForStaking
) external override onlyGovernance {
if (cofiToken != address(0)) {
_cofiToken = cofiToken;
}
if (cofiNode != address(0)) {
_cofiNode = cofiNode;
}
if (cofixDAO != address(0)) {
_cofixDAO = cofixDAO;
}
if (cofixRouter != address(0)) {
_cofixRouter = cofixRouter;
}
if (cofixController != address(0)) {
_cofixController = cofixController;
}
if (cofixVaultForStaking != address(0)) {
_cofixVaultForStaking = cofixVaultForStaking;
}
}
/// @dev Get the built-in contract address of the system
/// @return cofiToken Address of CoFi token contract
/// @return cofiNode Address of CoFi Node contract
/// @return cofixDAO ICoFiXDAO implementation contract address
/// @return cofixRouter ICoFiXRouter implementation contract address for CoFiX
/// @return cofixController ICoFiXController implementation contract address
function getBuiltinAddress() external view override returns (
address cofiToken,
address cofiNode,
address cofixDAO,
address cofixRouter,
address cofixController,
address cofixVaultForStaking
) {
return (
_cofiToken,
_cofiNode,
_cofixDAO,
_cofixRouter,
_cofixController,
_cofixVaultForStaking
);
}
/// @dev Get address of CoFi token contract
/// @return Address of CoFi Node token contract
function getCoFiTokenAddress() external view override returns (address) { return _cofiToken; }
/// @dev Get address of CoFi Node contract
/// @return Address of CoFi Node contract
function getCoFiNodeAddress() external view override returns (address) { return _cofiNode; }
/// @dev Get ICoFiXDAO implementation contract address
/// @return ICoFiXDAO implementation contract address
function getCoFiXDAOAddress() external view override returns (address) { return _cofixDAO; }
/// @dev Get ICoFiXRouter implementation contract address for CoFiX
/// @return ICoFiXRouter implementation contract address for CoFiX
function getCoFiXRouterAddress() external view override returns (address) { return _cofixRouter; }
/// @dev Get ICoFiXController implementation contract address
/// @return ICoFiXController implementation contract address
function getCoFiXControllerAddress() external view override returns (address) { return _cofixController; }
/// @dev Get ICoFiXVaultForStaking implementation contract address
/// @return ICoFiXVaultForStaking implementation contract address
function getCoFiXVaultForStakingAddress() external view override returns (address) { return _cofixVaultForStaking; }
/// @dev Registered address. The address registered here is the address accepted by CoFiX system
/// @param key The key
/// @param addr Destination address. 0 means to delete the registration information
function registerAddress(string calldata key, address addr) external override onlyGovernance {
_registeredAddress[key] = addr;
}
/// @dev Get registered address
/// @param key The key
/// @return Destination address. 0 means empty
function checkAddress(string calldata key) external view override returns (address) {
return _registeredAddress[key];
}
}
// File contracts/CoFiXGovernance.sol
// GPL-3.0-or-later
pragma solidity ^0.8.6;
/// @dev CoFiX governance contract
contract CoFiXGovernance is CoFiXMapping, ICoFiXGovernance {
/// @dev To support open-zeppelin/upgrades
/// @param governance ICoFiXGovernance implementation contract address
function initialize(address governance) public override {
// While initialize CoFiXGovernance, newGovernance is address(this),
// So must let newGovernance to 0
require(governance == address(0), "CoFiXGovernance:!address");
// newGovernance is address(this)
super.initialize(address(this));
// Add msg.sender to governance
_governanceMapping[msg.sender] = GovernanceInfo(msg.sender, uint96(0xFFFFFFFFFFFFFFFFFFFFFFFF));
}
/// @dev Structure of governance address information
struct GovernanceInfo {
address addr;
uint96 flag;
}
/// @dev Governance address information
mapping(address=>GovernanceInfo) _governanceMapping;
/// @dev Set governance authority
/// @param addr Destination address
/// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function setGovernance(address addr, uint flag) external override onlyGovernance {
if (flag > 0) {
_governanceMapping[addr] = GovernanceInfo(addr, uint96(flag));
} else {
_governanceMapping[addr] = GovernanceInfo(address(0), uint96(0));
}
}
/// @dev Get governance rights
/// @param addr Destination address
/// @return Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function getGovernance(address addr) external view override returns (uint) {
return _governanceMapping[addr].flag;
}
/// @dev Check whether the target address has governance rights for the given target
/// @param addr Destination address
/// @param flag Permission weight. The permission of the target address must be greater than this
/// weight to pass the check
/// @return True indicates permission
function checkGovernance(address addr, uint flag) public view override returns (bool) {
return _governanceMapping[addr].flag > flag;
}
} | Check whether the target address has governance rights for the given target addr Destination address flag Permission weight. The permission of the target address must be greater than this weight to pass the check return True indicates permission | function checkGovernance(address addr, uint flag) public view override returns (bool) {
return _governanceMapping[addr].flag > flag;
}
| 2,221,828 |
./full_match/1/0x873066F098E6A3A4FEbF65c9e437F7F71C8ef314/sources/src/swappers/UniswapV2Swapper.sol | Swaps the specified amount of `tokenIn` for `tokenOut`. tokenIn The address of the input token. amountIn The amount of the input token to be swapped. tokenOut The address of the output token. minAmountOut The minimum amount of the output token to be returned. return The amount of the output token returned. If the amount of `tokenOut` returned is less than `minAmountOut`, the transaction reverts./ | function swap(address tokenIn, uint256 amount, address tokenOut, uint256 minAmountOut, bytes memory)
external
override
returns (uint256 amountOutput)
{
SwapRoute storage swapRoute = tokenSwapRoutes[IERC20(tokenIn)][IERC20(tokenOut)];
return swapWithRouterAndPath(
_getRouter(swapRoute),
_getPath(swapRoute, IERC20(tokenIn), IERC20(tokenOut)),
amount,
minAmountOut,
msg.sender
);
}
| 2,931,679 |
./partial_match/97/0x32a2817C6FC913c82cdEef56F21e71F8AC1372bD/sources/CErc20.sol | Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified it is >= amount, this should not revert in normal conditions. Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value./ solium-disable-next-line security/no-inline-assembly | function doTransferOut(address payable to, uint amount) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
bool result;
token.transfer(to, amount);
assembly {
switch returndatasize()
}
returndatacopy(0, 0, 32)
}
| 11,465,464 |
./full_match/1/0x9bfBD7CaDbF2AD0980eb04D6769E766c22E801CA/sources/src/ProtectionPlan.sol | Event for Querying Approvals approvedWallet address of the wallet owning the asset tokenId uint256 tokenId of asset being backed up tokenAddress address contract of the asset being protectd tokenType string i.e. ERC20 | ERC1155 | ERC721 tokensAllocated uint256 number of tokens to be protected success whether the transfer was successful or not claimedWallet address of receipient of assets We ommited the backupWallets array and the dateApproved fields here is that ok?/ this event is emitted when a related wallet is added member wallet address of member relatedWallet wallet address of related wallet approved whether the member is related or not/ Event for CryptoWill tokenId uint256 tokenId of asset being backed up tokenAddress address contract of the asset being protectd tokenType string i.e. ERC20 | ERC1155 | ERC721 tokensAllocated uint256 number of tokens to be protected success whether the transfer was successful or not inheritedWallet address of receipient of assets/ This initializer sets up the constructor and initial relayer address _member parameter to pass in the member on initializing/ | function initialize(address _member, address _protocolDirectoryAddr) public initializer {
require(_member != address(0), "Error: Member cannot be 0x");
require(_protocolDirectoryAddr != address(0), "Error: Registry cannot be 0x");
__Context_init_unchained();
__Ownable_init();
__ReentrancyGuard_init();
member = _member;
protocolRegistry = IProtocolRegistry(_protocolDirectoryAddr);
inheritable = false;
}
| 16,468,939 |
./full_match/4/0xCb444455b6b51CD1aa99681E09C430Ef14CAB2d7/sources/Scrambles.sol | Unpause redeems until pause is called. this unpauses the whole contract./ | function unpause() external override onlyOwner {
_unpause();
}
| 773,327 |
./partial_match/1/0x9a0b2FFD7e32D5501034df127C849Ae3dc74F728/sources/contracts/legacy/L1ChugSplashProxy.sol | Performs the proxy call via a delegatecall./ Copy calldata into memory at 0x0....calldatasize. Perform the delegatecall, make sure to pass all available gas. Copy returndata into memory at 0x0....returndatasize. Note that this will overwrite the calldata that we just copied into memory but that doesn't really matter because we'll be returning in a second anyway. Success == 0 means a revert. We'll revert too and pass the data up. | function _doProxyCall() internal onlyWhenNotPaused {
address implementation = _getImplementation();
require(implementation != address(0), "L1ChugSplashProxy: implementation is not set yet");
assembly {
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(gas(), implementation, 0x0, calldatasize(), 0x0, 0x0)
returndatacopy(0x0, 0x0, returndatasize())
if iszero(success) {
revert(0x0, returndatasize())
}
}
}
| 15,910,995 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
contract NauticalNarwhals is ERC721, Ownable, VRFConsumerBase, ReentrancyGuard {
using Counters for Counters.Counter;
using Strings for uint256; //allows for uint256var.tostring()
Counters.Counter private _mintedSupply;
string private baseURI;
string public notRevealedURI;
uint256 constant TOKEN_PRICE = 0.0457 ether;
uint256 constant MAX_SUPPLY = 5757;
uint256 constant MAX_PER_TRANSACTION = 10;
uint256 private _randomShift;
uint256 immutable LINK_FEE;
bytes32 internal immutable LINK_KEY_HASH;
address public immutable LINK_TOKEN;
bool public paused = true ;
bool public presale = true;
bool public revealed;
mapping(address => bool) private whitelistedAddresses;
constructor(
string memory _initbaseURI,
string memory _initNotRevealedURI,
address _LINK_TOKEN,
address _LINK_VRF_COORDINATOR_ADDRESS,
bytes32 _LINK_KEY_HASH,
uint256 _LINK_FEE
) ERC721("Nautical Narwhals", "NN")
VRFConsumerBase(_LINK_VRF_COORDINATOR_ADDRESS, _LINK_TOKEN){
baseURI = _initbaseURI;
notRevealedURI = _initNotRevealedURI;
LINK_TOKEN = _LINK_TOKEN;
LINK_KEY_HASH = _LINK_KEY_HASH;
LINK_FEE = _LINK_FEE;
}
function mintPreSale(uint256 _mintAmount) public payable {
require(presale, "Presale is not active");
require(whitelistedAddresses[msg.sender], "Sorry, no access unless you're whitelisted");
require(msg.value == TOKEN_PRICE * _mintAmount, "Incorrect ether amount");
_mint(_mintAmount);
}
function mintPublicSale(uint256 _mintAmount) public payable{
require(!presale, "Presale is active");
require(msg.value == TOKEN_PRICE * _mintAmount, "Incorrect ether amount");
_mint(_mintAmount);
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "tokenID does not exist");
if (!revealed) {
return notRevealedURI;
}
string memory currentBaseURI = _baseURI();
// shifting the tokenId by a randomNumber which is generated by Chainlink VRF before we do a reveal
uint256 tokenIdShifted = ((tokenId + _randomShift) % MAX_SUPPLY) + 1 ;
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(currentBaseURI, tokenIdShifted.toString(), '.json')
)
: "";
}
function isWhitelisted(address _user) external view returns (bool){
return whitelistedAddresses[_user];
}
function mintedAmount() external view returns (uint256){
return _mintedSupply.current();
}
/// ============ INTERNAL ============
function _mint(uint256 _mintAmount) internal nonReentrant{
require(!paused, "Please wait until unpaused");
require(_mintAmount > 0, "Mint at least one token");
require(_mintAmount <= 10, "Max 10 Allowed.");
require(_mintedSupply.current() + _mintAmount <= MAX_SUPPLY, "Not enough tokens left to mint that many");
for(uint256 i = 1; i <= _mintAmount; i++){
_mintedSupply.increment();
_safeMint(msg.sender, _mintedSupply.current());
}
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
//Callback function used by Chainlink VRF Coordinator.
function fulfillRandomness(bytes32, uint256 randomness) internal override {
_randomShift = (randomness % MAX_SUPPLY) + 1;
}
/// ============ ONLY OWNER ============
//Requests randomness from Chainlink
function getRandomNumber() public onlyOwner returns (bytes32 requestId) {
require(
LINK.balanceOf(address(this)) >= LINK_FEE,
"Not enough LINK"
);
return requestRandomness(LINK_KEY_HASH, LINK_FEE);
}
function airdrop(address[] memory _users) external onlyOwner nonReentrant{
require(_mintedSupply.current() + _users.length <= MAX_SUPPLY, "Not this many tokens left");
for(uint256 i = 1; i <= _users.length; i++){
_mintedSupply.increment();
_safeMint(_users[i-1], _mintedSupply.current());
}
}
function withdraw() external onlyOwner {
(bool success, ) = payable(owner()).call{value: address(this).balance}("");
require(success);
}
function setBaseURI(string calldata _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
function setNotRevealedURI(string memory _notRevealedURI) external onlyOwner {
notRevealedURI = _notRevealedURI;
}
function setReveal(bool _revealed) external onlyOwner {
revealed = _revealed;
}
function setPresale(bool _presale) external onlyOwner {
presale = _presale;
}
function setPaused(bool _paused) external onlyOwner {
paused = _paused;
}
function setWhitelist(address[] calldata _users) external onlyOwner {
for(uint256 i = 0; i < _users.length; i++){
whitelistedAddresses[_users[i]] = true;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(
bytes32 requestId,
uint256 randomness
)
internal
virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 constant private USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee
)
internal
returns (
bytes32 requestId
)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(
address _vrfCoordinator,
address _link
) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(
bytes32 requestId,
uint256 randomness
)
external
{
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (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.0 (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.0 (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.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(
address owner,
address spender
)
external
view
returns (
uint256 remaining
);
function approve(
address spender,
uint256 value
)
external
returns (
bool success
);
function balanceOf(
address owner
)
external
view
returns (
uint256 balance
);
function decimals()
external
view
returns (
uint8 decimalPlaces
);
function decreaseApproval(
address spender,
uint256 addedValue
)
external
returns (
bool success
);
function increaseApproval(
address spender,
uint256 subtractedValue
) external;
function name()
external
view
returns (
string memory tokenName
);
function symbol()
external
view
returns (
string memory tokenSymbol
);
function totalSupply()
external
view
returns (
uint256 totalTokensIssued
);
function transfer(
address to,
uint256 value
)
external
returns (
bool success
);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
)
external
returns (
bool success
);
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (
bool success
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
)
internal
pure
returns (
uint256
)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash,
uint256 _vRFInputSeed
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
} | Requests randomness from Chainlink | function getRandomNumber() public onlyOwner returns (bytes32 requestId) {
require(
LINK.balanceOf(address(this)) >= LINK_FEE,
"Not enough LINK"
);
return requestRandomness(LINK_KEY_HASH, LINK_FEE);
}
| 1,284,786 |
./partial_match/4/0xc4Ed932865F52B0458f0817A522eB69A0F304e2b/sources/PriceBettingT1S.sol | console.log("[sc] ----== handleLosing"); Pool gets 0.88, the governance gets 0.12 | function handleLosing(uint256 period, uint256 betIdx, uint256 gain) internal {
Bet memory bet = getBet(period, betIdx);
poolBalance = poolBalance.add(gain);
totalUnclaimed=totalUnclaimed.sub(bet.amount);
updateBetterUnclaimed(false, bet.amount, bet.addr);
setBetResult(period, betIdx, 0);
Lose(bet.addr, block.timestamp, bet.amount, betIdx, bet.period);
}
| 8,748,032 |
./partial_match/1/0x4Ad8A7406Caac3457981A1B3C88B8aAB00D6e13d/sources/nftPandemic.sol | allows holders to burn their own tokens if desired | function burn(uint256 tokenID) external {
require(_msgSender() == ownerOf(tokenID));
_burn(tokenID);
}
| 4,397,785 |
./partial_match/1/0x86f78d3cbCa0636817AD9e27a44996C738Ec4932/sources/stableQiVault.sol | vaultID is the token id of the vault being interacted with. Calculates collateral to extract when liquidating a vault Can be used to calculate earnings from liquidating a vault. full liquidation if under the min debt. | function checkExtract(uint256 vaultID) public view returns (uint256) {
if (vaultCollateral[vaultID] == 0 || !checkLiquidation(vaultID)) {
return 0;
}
uint256 vaultDebtNow = vaultDebt(vaultID);
(, uint256 debtValue) = calculateCollateralProperties(
vaultCollateral[vaultID],
vaultDebtNow
);
if (halfDebt == 0) {
return 0;
}
if ((halfDebt) / (10**priceSourceDecimals) <= minDebt) {
return (debtValue * ( gainRatio)) / (THOUSAND) / (getEthPriceSource()) / decimalDifferenceRaisedToTen;
return (halfDebt * (gainRatio)) / THOUSAND / (getEthPriceSource()) / decimalDifferenceRaisedToTen;
}
}
| 2,821,070 |
/**
*Submitted for verification at Etherscan.io on 2020-09-18
*/
/**
*Submitted for verification at Etherscan.io on 2020-09-18
*/
// File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/token/ERC20/IERC20.sol
pragma solidity 0.5.7;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/math/SafeMath.sol
pragma solidity 0.5.7;
/**
* @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: nexusmutual-contracts/contracts/NXMToken.sol
/* Copyright (C) 2017 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.7;
contract NXMToken is IERC20 {
using SafeMath 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);
}
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IProposalCategory.sol
/* 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.7;
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;
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/Governed.sol
/* 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.7;
contract IMaster {
function getLatestAddress(bytes2 _module) public 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);
}
}
// File: nexusmutual-contracts/contracts/INXMMaster.sol
/* Copyright (C) 2017 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.7;
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);
}
// File: nexusmutual-contracts/contracts/Iupgradable.sol
pragma solidity 0.5.7;
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;
}
}
// File: nexusmutual-contracts/contracts/interfaces/IPooledStaking.sol
pragma solidity ^0.5.7;
interface IPooledStaking {
function accumulateReward(address contractAddress, uint amount) external;
function pushBurn(address contractAddress, uint amount) external;
function hasPendingActions() external view returns (bool);
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;
}
// File: nexusmutual-contracts/contracts/TokenFunctions.sol
/* 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.7;
contract TokenFunctions is Iupgradable {
using SafeMath for uint;
MCR internal m1;
MemberRoles internal mr;
NXMToken public tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
PoolData internal pd;
IPooledStaking pooledStaking;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev Rewards stakers on purchase of cover on smart contract.
* @param _contractAddress smart contract address.
* @param _coverPriceNXM cover price in NXM.
*/
function pushStakerRewards(address _contractAddress, uint _coverPriceNXM) external onlyInternal {
uint rewardValue = _coverPriceNXM.mul(td.stakerCommissionPer()).div(100);
pooledStaking.accumulateReward(_contractAddress, rewardValue);
}
/**
* @dev Deprecated in favor of burnStakedTokens
*/
function burnStakerLockedToken(uint, bytes4, uint) external {
// noop
}
/**
* @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed.
* @param coverId cover id
* @param coverCurrency cover currency
* @param sumAssured amount of $curr to burn
*/
function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal {
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = m1.calculateTokenPrice(coverCurrency);
uint burnNXMAmount = sumAssured.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnNXMAmount);
}
/**
* @dev Gets the total staked NXM tokens against
* Smart contract by all stakers
* @param _stakedContractAddress smart contract address.
* @return amount total staked NXM tokens.
*/
function deprecated_getTotalStakedTokensOnSmartContract(
address _stakedContractAddress
)
external
view
returns(uint)
{
uint stakedAmount = 0;
address stakerAddress;
uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress);
for (uint i = 0; i < staketLen; i++) {
stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i);
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, i);
uint currentlyStaked;
(, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress,
_stakedContractAddress, stakerIndex);
stakedAmount = stakedAmount.add(currentlyStaked);
}
return stakedAmount;
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note for given coverId.
* @param _of address of the coverHolder.
* @param _coverId coverId of the cover.
*/
function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) {
return _getUserLockedCNTokens(_of, _coverId);
}
/**
* @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 amount) {
for (uint i = 0; i < qd.getUserCoverLength(_of); i++) {
amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i]));
}
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note against given coverId.
* @param _coverId coverId of the cover.
*/
function getLockedCNAgainstCover(uint _coverId) external view returns(uint) {
return _getLockedCNAgainstCover(_coverId);
}
/**
* @dev Returns total amount of staked NXM Tokens on all smart contracts.
* @param _stakerAddress address of the Staker.
*/
function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) {
uint stakedAmount = 0;
address scAddress;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
uint currentlyStaked;
(, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i);
stakedAmount = stakedAmount.add(currentlyStaked);
}
amount = stakedAmount;
}
/**
* @dev Returns total unlockable amount of staked NXM Tokens on all smart contract .
* @param _stakerAddress address of the Staker.
*/
function deprecated_getStakerAllUnlockableStakedTokens(
address _stakerAddress
)
external
view
returns (uint amount)
{
uint unlockableAmount = 0;
address scAddress;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = unlockableAmount.add(
_deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress,
scIndex));
}
amount = unlockableAmount;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tk = NXMToken(ms.tokenAddress());
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
m1 = MCR(ms.getLatestAddress("MC"));
gv = Governance(ms.getLatestAddress("GV"));
mr = MemberRoles(ms.getLatestAddress("MR"));
pd = PoolData(ms.getLatestAddress("PD"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
/**
* @dev Gets the Token price in a given currency
* @param curr Currency name.
* @return price Token Price.
*/
function getTokenPrice(bytes4 curr) public view returns(uint price) {
price = m1.calculateTokenPrice(curr);
}
/**
* @dev Set the flag to check if cover note is deposited against the cover id
* @param coverId Cover Id.
*/
function depositCN(uint coverId) public onlyInternal returns (bool success) {
require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available");
td.setDepositCN(coverId, true);
success = true;
}
/**
* @param _of address of Member
* @param _coverId Cover Id
* @param _lockTime Pending Time + Cover Period 7*1 days
*/
function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal {
uint timeStamp = now.add(_lockTime);
uint coverValidUntil = qd.getValidityOfCover(_coverId);
if (timeStamp >= coverValidUntil) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId));
tc.extendLockOf(_of, reason, timeStamp);
}
}
/**
* @dev to burn the deposited cover tokens
* @param coverId is id of cover whose tokens have to be burned
* @return the status of the successful burning
*/
function burnDepositCN(uint coverId) public onlyInternal returns (bool success) {
address _of = qd.getCoverMemberAddress(coverId);
uint amount;
(amount, ) = td.depositedCN(coverId);
amount = (amount.mul(50)).div(100);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
tc.burnLockedTokens(_of, reason, amount);
success = true;
}
/**
* @dev Unlocks covernote locked against a given cover
* @param coverId id of cover
*/
function unlockCN(uint coverId) public onlyInternal {
(, bool isDeposited) = td.depositedCN(coverId);
require(!isDeposited,"Cover note is deposited and can not be released");
uint lockedCN = _getLockedCNAgainstCover(coverId);
if (lockedCN != 0) {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/**
* @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) public {
require(ms.checkIsAuthToGoverned(msg.sender));
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to lock cover note tokens
* @param coverNoteAmount is number of tokens to be locked
* @param coverPeriod is cover period in concern
* @param coverId is the cover id of cover in concern
* @param _of address whose tokens are to be locked
*/
function lockCN(
uint coverNoteAmount,
uint coverPeriod,
uint coverId,
address _of
)
public
onlyInternal
{
uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp());
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
td.setDepositCNAmount(coverId, coverNoteAmount);
tc.lockOf(_of, reason, coverNoteAmount, validity);
}
/**
* @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);
}
/**
* @dev Internal function to gets amount of locked NXM tokens,
* staked against smartcontract by index
* @param _stakerAddress address of user
* @param _stakedContractAddress staked contract address
* @param _stakedContractIndex index of staking
*/
function deprecated_getStakerLockedTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns
(uint amount)
{
amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress,
_stakedContractAddress, _stakedContractIndex);
}
/**
* @dev Function to gets unlockable amount of locked NXM
* tokens, staked against smartcontract by index
* @param stakerAddress address of staker
* @param stakedContractAddress staked contract address
* @param stakerIndex index of staking
*/
function deprecated_getStakerUnlockableTokensOnSmartContract (
address stakerAddress,
address stakedContractAddress,
uint stakerIndex
)
public
view
returns (uint)
{
return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress,
td.getStakerStakedContractIndex(stakerAddress, stakerIndex));
}
/**
* @dev releases unlockable staked tokens to staker
*/
function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause {
uint unlockableAmount;
address scAddress;
bytes32 reason;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract(
_stakerAddress, scAddress,
scIndex);
td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0);
td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount);
reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex));
tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount);
}
}
/**
* @dev to get tokens of staker locked before burning that are allowed to burn
* @param stakerAdd is the address of the staker
* @param stakedAdd is the address of staked contract in concern
* @param stakerIndex is the staker index in concern
* @return amount of unlockable tokens
* @return amount of tokens that can burn
*/
function _deprecated_unlockableBeforeBurningAndCanBurn(
address stakerAdd,
address stakedAdd,
uint stakerIndex
)
public
view
returns
(uint amount, uint canBurn) {
uint dateAdd;
uint initialStake;
uint totalBurnt;
uint ub;
(, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex);
canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays());
// Can't use SafeMaths for int.
int v = int(initialStake - (canBurn) - (totalBurnt) - (
td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub));
uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract(
stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex));
if (v < 0) {
v = 0;
}
amount = uint(v);
if (canBurn > currentLockedTokens.sub(amount).sub(ub)) {
canBurn = currentLockedTokens.sub(amount).sub(ub);
}
}
/**
* @dev to get tokens of staker that are unlockable
* @param _stakerAddress is the address of the staker
* @param _stakedContractAddress is the address of staked contract in concern
* @param _stakedContractIndex is the staked contract index in concern
* @return amount of unlockable tokens
*/
function _deprecated_getStakerUnlockableTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns
(uint amount)
{
uint initialStake;
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, _stakedContractIndex);
uint burnt;
(, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex);
uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex);
uint currentStakedTokens;
(, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress,
_stakedContractAddress, stakerIndex);
amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt);
}
/**
* @dev Internal function to get the amount of locked NXM tokens,
* staked against smartcontract by index
* @param _stakerAddress address of user
* @param _stakedContractAddress staked contract address
* @param _stakedContractIndex index of staking
*/
function _deprecated_getStakerLockedTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
internal
view
returns
(uint amount)
{
bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress,
_stakedContractAddress, _stakedContractIndex));
amount = tc.tokensLocked(_stakerAddress, reason);
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note for given coverId.
* @param _coverId coverId of the cover.
*/
function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) {
address coverHolder = qd.getCoverMemberAddress(_coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId));
return tc.tokensLockedAtTime(coverHolder, reason, now);
}
/**
* @dev Returns amount of NXM Tokens locked as Cover Note for given coverId.
* @param _of address of the coverHolder.
* @param _coverId coverId of the cover.
*/
function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId));
return tc.tokensLockedAtTime(_of, reason, now);
}
/**
* @dev Internal function to gets remaining amount of staked NXM tokens,
* against smartcontract by index
* @param _stakeAmount address of user
* @param _stakeDays staked contract address
* @param _validDays index of staking
*/
function _deprecated_calculateStakedTokens(
uint _stakeAmount,
uint _stakeDays,
uint _validDays
)
internal
pure
returns (uint amount)
{
if (_validDays > _stakeDays) {
uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays);
amount = (rf.mul(_stakeAmount)).div(100000);
} else {
amount = 0;
}
}
/**
* @dev Gets the total staked NXM tokens against Smart contract
* by all stakers
* @param _stakedContractAddress smart contract address.
* @return amount total staked NXM tokens.
*/
function _deprecated_burnStakerTokenLockedAgainstSmartContract(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _amount
)
internal
{
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, _stakedContractIndex);
td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount);
bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress,
_stakedContractAddress, _stakedContractIndex));
tc.burnLockedTokens(_stakerAddress, reason, _amount);
}
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IMemberRoles.sol
/* 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.7;
contract IMemberRoles {
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
/// @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) public;
/// @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(address _memberAddress, uint _roleId, bool _active) public;
/// @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 _authorized New authorized address against role id
function changeAuthorized(uint _roleId, address _authorized) public;
/// @dev Return number of member roles
function totalRoles() public view returns(uint256);
/// @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 allMemberAddress);
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberAddress.length Member length
function numberOfMembers(uint _memberRoleId) public view returns(uint);
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns(address);
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns(uint[] memory 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);
}
// File: nexusmutual-contracts/contracts/external/ERC1132/IERC1132.sol
pragma solidity 0.5.7;
/**
* @title ERC1132 interface
* @dev see https://github.com/ethereum/EIPs/issues/1132
*/
contract IERC1132 {
/**
* @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;
/**
* @dev Records data of all the tokens Locked
*/
event Locked(
address indexed _of,
bytes32 indexed _reason,
uint256 _amount,
uint256 _validity
);
/**
* @dev Records data of all the tokens unlocked
*/
event Unlocked(
address indexed _of,
bytes32 indexed _reason,
uint256 _amount
);
/**
* @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
*/
function lock(bytes32 _reason, uint256 _amount, uint256 _time)
public returns (bool);
/**
* @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);
/**
* @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);
/**
* @dev Returns total tokens held by an address (locked + transferable)
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of)
public view returns (uint256 amount);
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLock(bytes32 _reason, uint256 _time)
public returns (bool);
/**
* @dev Increase number of tokens locked for a specified reason
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be increased
*/
function increaseLockAmount(bytes32 _reason, uint256 _amount)
public returns (bool);
/**
* @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);
/**
* @dev Unlocks the unlockable tokens of a specified address
* @param _of Address of user, claiming back unlockable tokens
*/
function unlock(address _of)
public returns (uint256 unlockableTokens);
/**
* @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);
}
// File: nexusmutual-contracts/contracts/TokenController.sol
/* 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.7;
contract TokenController is IERC1132, Iupgradable {
using SafeMath for uint256;
event Burned(address indexed member, bytes32 lockedUnder, uint256 amount);
NXMToken public token;
IPooledStaking public pooledStaking;
uint public minCALockTime = uint(30).mul(1 days);
bytes32 private constant CLA = bytes32("CLA");
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {
token = NXMToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress('PS'));
}
/**
* @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) onlyInternal external returns (bool) {
require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address");
require(token.operatorTransfer(_from, _value), "Operator transfer failed");
require(token.transfer(_to, _value), "Internal transfer failed");
return true;
}
/**
* @dev Locks a specified amount of tokens,
* for CLA reason and for a specified time
* @param _reason The reason to lock tokens, currently restricted to CLA
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
require(minCALockTime <= _time,"Should lock for minimum time");
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(msg.sender, _reason, _amount, _time);
return true;
}
/**
* @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 Extends lock for reason CLA for a specified time
* @param _reason The reason to lock tokens, currently restricted to CLA
* @param _time Lock extension time in seconds
*/
function extendLock(bytes32 _reason, uint256 _time)
public
checkPause
returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
_extendLock(msg.sender, _reason, _time);
return true;
}
/**
* @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 _reason The reason to lock tokens, currently restricted to CLA
* @param _amount Number of tokens to be increased
*/
function increaseLockAmount(bytes32 _reason, uint256 _amount)
public
checkPause
returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
require(_tokensLocked(msg.sender, _reason) > 0);
token.operatorTransfer(msg.sender, _amount);
locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity);
return true;
}
/**
* @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 unlockable tokens against CLA of a specified address
* @param _of Address of user, claiming back unlockable tokens against CLA
*/
function unlock(address _of)
public
checkPause
returns (uint256 unlockableTokens)
{
unlockableTokens = _tokensUnlockable(_of, CLA);
if (unlockableTokens > 0) {
locked[_of][CLA].claimed = true;
emit Unlocked(_of, CLA, unlockableTokens);
require(token.transfer(_of, unlockableTokens));
}
}
/**
* @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 == "MNCLT") {
minCALockTime = val.mul(1 days);
} else {
revert("Invalid param code");
}
}
/**
* @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 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 locked tokens at time
* Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility
* for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment.
* Does not take into account pending burns.
*
* @param _of member whose locked tokens are to be calculate
* @param _time timestamp when the tokens should be locked
*/
function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time));
}
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);
require(_amount != 0);
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
require(token.operatorTransfer(_of, _amount));
uint256 validUntil = now.add(_time); //solhint-disable-line
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);
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);
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);
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
if (locked[_of][_reason].amount == 0) {
_removeReason(_of, _reason);
}
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);
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
if (locked[_of][_reason].amount == 0) {
_removeReason(_of, _reason);
}
require(token.transfer(_of, _amount));
emit Unlocked(_of, _reason, _amount);
}
function _removeReason(address _of, bytes32 _reason) internal {
uint len = lockReason[_of].length;
for (uint i = 0; i < len; i++) {
if (lockReason[_of][i] == _reason) {
lockReason[_of][i] = lockReason[_of][len.sub(1)];
lockReason[_of].pop();
break;
}
}
}
}
// File: nexusmutual-contracts/contracts/ClaimsData.sol
/* Copyright (C) 2017 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.7;
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); //injected INTEGER OVERFLOW OR UNDERFLOW
if (_vote == -1)
claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @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); //injected INTEGER OVERFLOW OR UNDERFLOW
if (_vote == -1)
claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @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); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @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;
}
}
// File: nexusmutual-contracts/contracts/PoolData.sol
/* Copyright (C) 2017 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.7;
contract DSValue {
function peek() public view returns (bytes32, bool);
function read() public view returns (bytes32);
}
contract PoolData is Iupgradable {
using SafeMath for uint;
struct ApiId {
bytes4 typeOf;
bytes4 currency;
uint id;
uint64 dateAdd;
uint64 dateUpd;
}
struct CurrencyAssets {
address currAddress;
uint baseMin;
uint varMin;
}
struct InvestmentAssets {
address currAddress;
bool status;
uint64 minHoldingPercX100;
uint64 maxHoldingPercX100;
uint8 decimals;
}
struct IARankDetails {
bytes4 maxIACurr;
uint64 maxRate;
bytes4 minIACurr;
uint64 minRate;
}
struct McrData {
uint mcrPercx100;
uint mcrEther;
uint vFull; //Pool funds
uint64 date;
}
IARankDetails[] internal allIARankDetails;
McrData[] public allMCRData;
bytes4[] internal allInvestmentCurrencies;
bytes4[] internal allCurrencies;
bytes32[] public allAPIcall;
mapping(bytes32 => ApiId) public allAPIid;
mapping(uint64 => uint) internal datewiseId;
mapping(bytes16 => uint) internal currencyLastIndex;
mapping(bytes4 => CurrencyAssets) internal allCurrencyAssets;
mapping(bytes4 => InvestmentAssets) internal allInvestmentAssets;
mapping(bytes4 => uint) internal caAvgRate;
mapping(bytes4 => uint) internal iaAvgRate;
address public notariseMCR;
address public daiFeedAddress;
uint private constant DECIMAL1E18 = uint(10) ** 18;
uint public uniswapDeadline;
uint public liquidityTradeCallbackTime;
uint public lastLiquidityTradeTrigger;
uint64 internal lastDate;
uint public variationPercX100;
uint public iaRatesTime;
uint public minCap;
uint public mcrTime;
uint public a;
uint public shockParameter;
uint public c;
uint public mcrFailTime;
uint public ethVolumeLimit;
uint public capReached;
uint public capacityLimit;
constructor(address _notariseAdd, address _daiFeedAdd, address _daiAdd) public {
notariseMCR = _notariseAdd;
daiFeedAddress = _daiFeedAdd;
c = 5800000;
a = 1028;
mcrTime = 24 hours;
mcrFailTime = 6 hours;
allMCRData.push(McrData(0, 0, 0, 0));
minCap = 12000 * DECIMAL1E18;
shockParameter = 50;
variationPercX100 = 100; //1%
iaRatesTime = 24 hours; //24 hours in seconds
uniswapDeadline = 20 minutes;
liquidityTradeCallbackTime = 4 hours;
ethVolumeLimit = 4;
capacityLimit = 10;
allCurrencies.push("ETH");
allCurrencyAssets["ETH"] = CurrencyAssets(address(0), 1000 * DECIMAL1E18, 0);
allCurrencies.push("DAI");
allCurrencyAssets["DAI"] = CurrencyAssets(_daiAdd, 50000 * DECIMAL1E18, 0);
allInvestmentCurrencies.push("ETH");
allInvestmentAssets["ETH"] = InvestmentAssets(address(0), true, 2500, 10000, 18);
allInvestmentCurrencies.push("DAI");
allInvestmentAssets["DAI"] = InvestmentAssets(_daiAdd, true, 250, 1500, 18);
}
/**
* @dev to set the maximum cap allowed
* @param val is the new value
*/
function setCapReached(uint val) external onlyInternal {
capReached = val;
}
/// @dev Updates the 3 day average rate of a IA currency.
/// To be replaced by MakerDao's on chain rates
/// @param curr IA Currency Name.
/// @param rate Average exchange rate X 100 (of last 3 days).
function updateIAAvgRate(bytes4 curr, uint rate) external onlyInternal {
iaAvgRate[curr] = rate;
}
/// @dev Updates the 3 day average rate of a CA currency.
/// To be replaced by MakerDao's on chain rates
/// @param curr Currency Name.
/// @param rate Average exchange rate X 100 (of last 3 days).
function updateCAAvgRate(bytes4 curr, uint rate) external onlyInternal {
caAvgRate[curr] = rate;
}
/// @dev Adds details of (Minimum Capital Requirement)MCR.
/// @param mcrp Minimum Capital Requirement percentage (MCR% * 100 ,Ex:for 54.56% ,given 5456)
/// @param vf Pool fund value in Ether used in the last full daily calculation from the Capital model.
function pushMCRData(uint mcrp, uint mcre, uint vf, uint64 time) external onlyInternal {
allMCRData.push(McrData(mcrp, mcre, vf, time));
}
/**
* @dev Updates the Timestamp at which result of oracalize call is received.
*/
function updateDateUpdOfAPI(bytes32 myid) external onlyInternal {
allAPIid[myid].dateUpd = uint64(now);
}
/**
* @dev Saves the details of the Oraclize API.
* @param myid Id return by the oraclize query.
* @param _typeof type of the query for which oraclize call is made.
* @param id ID of the proposal,quote,cover etc. for which oraclize call is made
*/
function saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) external onlyInternal {
allAPIid[myid] = ApiId(_typeof, "", id, uint64(now), uint64(now));
}
/**
* @dev Stores the id return by the oraclize query.
* Maintains record of all the Ids return by oraclize query.
* @param myid Id return by the oraclize query.
*/
function addInAllApiCall(bytes32 myid) external onlyInternal {
allAPIcall.push(myid);
}
/**
* @dev Saves investment asset rank details.
* @param maxIACurr Maximum ranked investment asset currency.
* @param maxRate Maximum ranked investment asset rate.
* @param minIACurr Minimum ranked investment asset currency.
* @param minRate Minimum ranked investment asset rate.
* @param date in yyyymmdd.
*/
function saveIARankDetails(
bytes4 maxIACurr,
uint64 maxRate,
bytes4 minIACurr,
uint64 minRate,
uint64 date
)
external
onlyInternal
{
allIARankDetails.push(IARankDetails(maxIACurr, maxRate, minIACurr, minRate));
datewiseId[date] = allIARankDetails.length.sub(1);
}
/**
* @dev to get the time for the laste liquidity trade trigger
*/
function setLastLiquidityTradeTrigger() external onlyInternal {
lastLiquidityTradeTrigger = now;
}
/**
* @dev Updates Last Date.
*/
function updatelastDate(uint64 newDate) external onlyInternal {
lastDate = newDate;
}
/**
* @dev Adds currency asset currency.
* @param curr currency of the asset
* @param currAddress address of the currency
* @param baseMin base minimum in 10^18.
*/
function addCurrencyAssetCurrency(
bytes4 curr,
address currAddress,
uint baseMin
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allCurrencies.push(curr);
allCurrencyAssets[curr] = CurrencyAssets(currAddress, baseMin, 0);
}
/**
* @dev Adds investment asset.
*/
function addInvestmentAssetCurrency(
bytes4 curr,
address currAddress,
bool status,
uint64 minHoldingPercX100,
uint64 maxHoldingPercX100,
uint8 decimals
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentCurrencies.push(curr);
allInvestmentAssets[curr] = InvestmentAssets(currAddress, status,
minHoldingPercX100, maxHoldingPercX100, decimals);
}
/**
* @dev Changes base minimum of a given currency asset.
*/
function changeCurrencyAssetBaseMin(bytes4 curr, uint baseMin) external {
require(ms.checkIsAuthToGoverned(msg.sender));
allCurrencyAssets[curr].baseMin = baseMin;
}
/**
* @dev changes variable minimum of a given currency asset.
*/
function changeCurrencyAssetVarMin(bytes4 curr, uint varMin) external onlyInternal {
allCurrencyAssets[curr].varMin = varMin;
}
/**
* @dev Changes the investment asset status.
*/
function changeInvestmentAssetStatus(bytes4 curr, bool status) external {
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentAssets[curr].status = status;
}
/**
* @dev Changes the investment asset Holding percentage of a given currency.
*/
function changeInvestmentAssetHoldingPerc(
bytes4 curr,
uint64 minPercX100,
uint64 maxPercX100
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentAssets[curr].minHoldingPercX100 = minPercX100;
allInvestmentAssets[curr].maxHoldingPercX100 = maxPercX100;
}
/**
* @dev Gets Currency asset token address.
*/
function changeCurrencyAssetAddress(bytes4 curr, address currAdd) external {
require(ms.checkIsAuthToGoverned(msg.sender));
allCurrencyAssets[curr].currAddress = currAdd;
}
/**
* @dev Changes Investment asset token address.
*/
function changeInvestmentAssetAddressAndDecimal(
bytes4 curr,
address currAdd,
uint8 newDecimal
)
external
{
require(ms.checkIsAuthToGoverned(msg.sender));
allInvestmentAssets[curr].currAddress = currAdd;
allInvestmentAssets[curr].decimals = newDecimal;
}
/// @dev Changes address allowed to post MCR.
function changeNotariseAddress(address _add) external onlyInternal {
notariseMCR = _add;
}
/// @dev updates daiFeedAddress address.
/// @param _add address of DAI feed.
function changeDAIfeedAddress(address _add) external onlyInternal {
daiFeedAddress = _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 == "MCRTIM") {
val = mcrTime / (1 hours);
} else if (code == "MCRFTIM") {
val = mcrFailTime / (1 hours);
} else if (code == "MCRMIN") {
val = minCap;
} else if (code == "MCRSHOCK") {
val = shockParameter;
} else if (code == "MCRCAPL") {
val = capacityLimit;
} else if (code == "IMZ") {
val = variationPercX100;
} else if (code == "IMRATET") {
val = iaRatesTime / (1 hours);
} else if (code == "IMUNIDL") {
val = uniswapDeadline / (1 minutes);
} else if (code == "IMLIQT") {
val = liquidityTradeCallbackTime / (1 hours);
} else if (code == "IMETHVL") {
val = ethVolumeLimit;
} else if (code == "C") {
val = c;
} else if (code == "A") {
val = a;
}
}
/// @dev Checks whether a given address can notaise MCR data or not.
/// @param _add Address.
/// @return res Returns 0 if address is not authorized, else 1.
function isnotarise(address _add) external view returns(bool res) {
res = false;
if (_add == notariseMCR)
res = true;
}
/// @dev Gets the details of last added MCR.
/// @return mcrPercx100 Total Minimum Capital Requirement percentage of that month of year(multiplied by 100).
/// @return vFull Total Pool fund value in Ether used in the last full daily calculation.
function getLastMCR() external view returns(uint mcrPercx100, uint mcrEtherx1E18, uint vFull, uint64 date) {
uint index = allMCRData.length.sub(1);
return (
allMCRData[index].mcrPercx100,
allMCRData[index].mcrEther,
allMCRData[index].vFull,
allMCRData[index].date
);
}
/// @dev Gets last Minimum Capital Requirement percentage of Capital Model
/// @return val MCR% value,multiplied by 100.
function getLastMCRPerc() external view returns(uint) {
return allMCRData[allMCRData.length.sub(1)].mcrPercx100;
}
/// @dev Gets last Ether price of Capital Model
/// @return val ether value,multiplied by 100.
function getLastMCREther() external view returns(uint) {
return allMCRData[allMCRData.length.sub(1)].mcrEther;
}
/// @dev Gets Pool fund value in Ether used in the last full daily calculation from the Capital model.
function getLastVfull() external view returns(uint) {
return allMCRData[allMCRData.length.sub(1)].vFull;
}
/// @dev Gets last Minimum Capital Requirement in Ether.
/// @return date of MCR.
function getLastMCRDate() external view returns(uint64 date) {
date = allMCRData[allMCRData.length.sub(1)].date;
}
/// @dev Gets details for token price calculation.
function getTokenPriceDetails(bytes4 curr) external view returns(uint _a, uint _c, uint rate) {
_a = a;
_c = c;
rate = _getAvgRate(curr, false);
}
/// @dev Gets the total number of times MCR calculation has been made.
function getMCRDataLength() external view returns(uint len) {
len = allMCRData.length;
}
/**
* @dev Gets investment asset rank details by given date.
*/
function getIARankDetailsByDate(
uint64 date
)
external
view
returns(
bytes4 maxIACurr,
uint64 maxRate,
bytes4 minIACurr,
uint64 minRate
)
{
uint index = datewiseId[date];
return (
allIARankDetails[index].maxIACurr,
allIARankDetails[index].maxRate,
allIARankDetails[index].minIACurr,
allIARankDetails[index].minRate
);
}
/**
* @dev Gets Last Date.
*/
function getLastDate() external view returns(uint64 date) {
return lastDate;
}
/**
* @dev Gets investment currency for a given index.
*/
function getInvestmentCurrencyByIndex(uint index) external view returns(bytes4 currName) {
return allInvestmentCurrencies[index];
}
/**
* @dev Gets count of investment currency.
*/
function getInvestmentCurrencyLen() external view returns(uint len) {
return allInvestmentCurrencies.length;
}
/**
* @dev Gets all the investment currencies.
*/
function getAllInvestmentCurrencies() external view returns(bytes4[] memory currencies) {
return allInvestmentCurrencies;
}
/**
* @dev Gets All currency for a given index.
*/
function getCurrenciesByIndex(uint index) external view returns(bytes4 currName) {
return allCurrencies[index];
}
/**
* @dev Gets count of All currency.
*/
function getAllCurrenciesLen() external view returns(uint len) {
return allCurrencies.length;
}
/**
* @dev Gets all currencies
*/
function getAllCurrencies() external view returns(bytes4[] memory currencies) {
return allCurrencies;
}
/**
* @dev Gets currency asset details for a given currency.
*/
function getCurrencyAssetVarBase(
bytes4 curr
)
external
view
returns(
bytes4 currency,
uint baseMin,
uint varMin
)
{
return (
curr,
allCurrencyAssets[curr].baseMin,
allCurrencyAssets[curr].varMin
);
}
/**
* @dev Gets minimum variable value for currency asset.
*/
function getCurrencyAssetVarMin(bytes4 curr) external view returns(uint varMin) {
return allCurrencyAssets[curr].varMin;
}
/**
* @dev Gets base minimum of a given currency asset.
*/
function getCurrencyAssetBaseMin(bytes4 curr) external view returns(uint baseMin) {
return allCurrencyAssets[curr].baseMin;
}
/**
* @dev Gets investment asset maximum and minimum holding percentage of a given currency.
*/
function getInvestmentAssetHoldingPerc(
bytes4 curr
)
external
view
returns(
uint64 minHoldingPercX100,
uint64 maxHoldingPercX100
)
{
return (
allInvestmentAssets[curr].minHoldingPercX100,
allInvestmentAssets[curr].maxHoldingPercX100
);
}
/**
* @dev Gets investment asset decimals.
*/
function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) {
return allInvestmentAssets[curr].decimals;
}
/**
* @dev Gets investment asset maximum holding percentage of a given currency.
*/
function getInvestmentAssetMaxHoldingPerc(bytes4 curr) external view returns(uint64 maxHoldingPercX100) {
return allInvestmentAssets[curr].maxHoldingPercX100;
}
/**
* @dev Gets investment asset minimum holding percentage of a given currency.
*/
function getInvestmentAssetMinHoldingPerc(bytes4 curr) external view returns(uint64 minHoldingPercX100) {
return allInvestmentAssets[curr].minHoldingPercX100;
}
/**
* @dev Gets investment asset details of a given currency
*/
function getInvestmentAssetDetails(
bytes4 curr
)
external
view
returns(
bytes4 currency,
address currAddress,
bool status,
uint64 minHoldingPerc,
uint64 maxHoldingPerc,
uint8 decimals
)
{
return (
curr,
allInvestmentAssets[curr].currAddress,
allInvestmentAssets[curr].status,
allInvestmentAssets[curr].minHoldingPercX100,
allInvestmentAssets[curr].maxHoldingPercX100,
allInvestmentAssets[curr].decimals
);
}
/**
* @dev Gets Currency asset token address.
*/
function getCurrencyAssetAddress(bytes4 curr) external view returns(address) {
return allCurrencyAssets[curr].currAddress;
}
/**
* @dev Gets investment asset token address.
*/
function getInvestmentAssetAddress(bytes4 curr) external view returns(address) {
return allInvestmentAssets[curr].currAddress;
}
/**
* @dev Gets investment asset active Status of a given currency.
*/
function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) {
return allInvestmentAssets[curr].status;
}
/**
* @dev Gets type of oraclize query for a given Oraclize Query ID.
* @param myid Oraclize Query ID identifying the query for which the result is being received.
* @return _typeof It could be of type "quote","quotation","cover","claim" etc.
*/
function getApiIdTypeOf(bytes32 myid) external view returns(bytes4) {
return allAPIid[myid].typeOf;
}
/**
* @dev Gets ID associated to oraclize query for a given Oraclize Query ID.
* @param myid Oraclize Query ID identifying the query for which the result is being received.
* @return id1 It could be the ID of "proposal","quotation","cover","claim" etc.
*/
function getIdOfApiId(bytes32 myid) external view returns(uint) {
return allAPIid[myid].id;
}
/**
* @dev Gets the Timestamp of a oracalize call.
*/
function getDateAddOfAPI(bytes32 myid) external view returns(uint64) {
return allAPIid[myid].dateAdd;
}
/**
* @dev Gets the Timestamp at which result of oracalize call is received.
*/
function getDateUpdOfAPI(bytes32 myid) external view returns(uint64) {
return allAPIid[myid].dateUpd;
}
/**
* @dev Gets currency by oracalize id.
*/
function getCurrOfApiId(bytes32 myid) external view returns(bytes4) {
return allAPIid[myid].currency;
}
/**
* @dev Gets ID return by the oraclize query of a given index.
* @param index Index.
* @return myid ID return by the oraclize query.
*/
function getApiCallIndex(uint index) external view returns(bytes32 myid) {
myid = allAPIcall[index];
}
/**
* @dev Gets Length of API call.
*/
function getApilCallLength() external view returns(uint) {
return allAPIcall.length;
}
/**
* @dev Get Details of Oraclize API when given Oraclize Id.
* @param myid ID return by the oraclize query.
* @return _typeof ype of the query for which oraclize
* call is made.("proposal","quote","quotation" etc.)
*/
function getApiCallDetails(
bytes32 myid
)
external
view
returns(
bytes4 _typeof,
bytes4 curr,
uint id,
uint64 dateAdd,
uint64 dateUpd
)
{
return (
allAPIid[myid].typeOf,
allAPIid[myid].currency,
allAPIid[myid].id,
allAPIid[myid].dateAdd,
allAPIid[myid].dateUpd
);
}
/**
* @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 == "MCRTIM") {
_changeMCRTime(val * 1 hours);
} else if (code == "MCRFTIM") {
_changeMCRFailTime(val * 1 hours);
} else if (code == "MCRMIN") {
_changeMinCap(val);
} else if (code == "MCRSHOCK") {
_changeShockParameter(val);
} else if (code == "MCRCAPL") {
_changeCapacityLimit(val);
} else if (code == "IMZ") {
_changeVariationPercX100(val);
} else if (code == "IMRATET") {
_changeIARatesTime(val * 1 hours);
} else if (code == "IMUNIDL") {
_changeUniswapDeadlineTime(val * 1 minutes);
} else if (code == "IMLIQT") {
_changeliquidityTradeCallbackTime(val * 1 hours);
} else if (code == "IMETHVL") {
_setEthVolumeLimit(val);
} else if (code == "C") {
_changeC(val);
} else if (code == "A") {
_changeA(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev to get the average rate of currency rate
* @param curr is the currency in concern
* @return required rate
*/
function getCAAvgRate(bytes4 curr) public view returns(uint rate) {
return _getAvgRate(curr, false);
}
/**
* @dev to get the average rate of investment rate
* @param curr is the investment in concern
* @return required rate
*/
function getIAAvgRate(bytes4 curr) public view returns(uint rate) {
return _getAvgRate(curr, true);
}
function changeDependentContractAddress() public onlyInternal {}
/// @dev Gets the average rate of a CA currency.
/// @param curr Currency Name.
/// @return rate Average rate X 100(of last 3 days).
function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) {
if (curr == "DAI") {
DSValue ds = DSValue(daiFeedAddress);
rate = uint(ds.read()).div(uint(10) ** 16);
} else if (isIA) {
rate = iaAvgRate[curr];
} else {
rate = caAvgRate[curr];
}
}
/**
* @dev to set the ethereum volume limit
* @param val is the new limit value
*/
function _setEthVolumeLimit(uint val) internal {
ethVolumeLimit = val;
}
/// @dev Sets minimum Cap.
function _changeMinCap(uint newCap) internal {
minCap = newCap;
}
/// @dev Sets Shock Parameter.
function _changeShockParameter(uint newParam) internal {
shockParameter = newParam;
}
/// @dev Changes time period for obtaining new MCR data from external oracle query.
function _changeMCRTime(uint _time) internal {
mcrTime = _time;
}
/// @dev Sets MCR Fail time.
function _changeMCRFailTime(uint _time) internal {
mcrFailTime = _time;
}
/**
* @dev to change the uniswap deadline time
* @param newDeadline is the value
*/
function _changeUniswapDeadlineTime(uint newDeadline) internal {
uniswapDeadline = newDeadline;
}
/**
* @dev to change the liquidity trade call back time
* @param newTime is the new value to be set
*/
function _changeliquidityTradeCallbackTime(uint newTime) internal {
liquidityTradeCallbackTime = newTime;
}
/**
* @dev Changes time after which investment asset rates need to be fed.
*/
function _changeIARatesTime(uint _newTime) internal {
iaRatesTime = _newTime;
}
/**
* @dev Changes the variation range percentage.
*/
function _changeVariationPercX100(uint newPercX100) internal {
variationPercX100 = newPercX100;
}
/// @dev Changes Growth Step
function _changeC(uint newC) internal {
c = newC;
}
/// @dev Changes scaling factor.
function _changeA(uint val) internal {
a = val;
}
/**
* @dev to change the capacity limit
* @param val is the new value
*/
function _changeCapacityLimit(uint val) internal {
capacityLimit = val;
}
}
// File: nexusmutual-contracts/contracts/QuotationData.sol
/* Copyright (C) 2017 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.7;
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); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/// @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); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/// @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); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/// @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;
}
}
// File: nexusmutual-contracts/contracts/TokenData.sol
/* Copyright (C) 2017 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.7;
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); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @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); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @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); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @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); //injected INTEGER OVERFLOW OR UNDERFLOW
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); //injected INTEGER OVERFLOW OR UNDERFLOW
}
/**
* @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;
}
}
// File: nexusmutual-contracts/contracts/external/oraclize/ethereum-api/usingOraclize.sol
/*
ORACLIZE_API
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
pragma solidity >= 0.5.0 < 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI!
// Dummy contract only used to emit to end-user they are using wrong solc
contract solcChecker {
/* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external;
}
contract OraclizeI {
address public cbAddress;
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function getPrice(string memory _datasource) public returns (uint _dsprice);
function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash);
function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice);
function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id);
function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id);
function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _address);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory _buf, uint _capacity) internal pure {
uint capacity = _capacity;
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
_buf.capacity = capacity; // Allocate space for the buffer data
assembly {
let ptr := mload(0x40)
mstore(_buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory _buf, uint _capacity) private pure {
bytes memory oldbuf = _buf.buf;
init(_buf, _capacity);
append(_buf, oldbuf);
}
function max(uint _a, uint _b) private pure returns (uint _max) {
if (_a > _b) {
return _a;
}
return _b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) {
if (_data.length + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _data.length) * 2);
}
uint dest;
uint src;
uint len = _data.length;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length)
mstore(bufptr, add(buflen, mload(_data))) // Update buffer length
src := add(_data, 32)
}
for(; len >= 32; len -= 32) { // Copy word-length chunks while possible
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return _buf;
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function append(buffer memory _buf, uint8 _data) internal pure {
if (_buf.buf.length + 1 > _buf.capacity) {
resize(_buf, _buf.capacity * 2);
}
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)
mstore8(dest, _data)
mstore(bufptr, add(buflen, 1)) // Update buffer length
}
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return The original buffer.
*
*/
function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) {
if (_len + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _len) * 2);
}
uint mask = 256 ** _len - 1;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len
mstore(dest, or(and(mload(dest), not(mask)), _data))
mstore(bufptr, add(buflen, _len)) // Update buffer length
}
return _buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure {
if (_value <= 23) {
_buf.append(uint8((_major << 5) | _value));
} else if (_value <= 0xFF) {
_buf.append(uint8((_major << 5) | 24));
_buf.appendInt(_value, 1);
} else if (_value <= 0xFFFF) {
_buf.append(uint8((_major << 5) | 25));
_buf.appendInt(_value, 2);
} else if (_value <= 0xFFFFFFFF) {
_buf.append(uint8((_major << 5) | 26));
_buf.appendInt(_value, 4);
} else if (_value <= 0xFFFFFFFFFFFFFFFF) {
_buf.append(uint8((_major << 5) | 27));
_buf.appendInt(_value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure {
_buf.append(uint8((_major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure {
encodeType(_buf, MAJOR_TYPE_INT, _value);
}
function encodeInt(Buffer.buffer memory _buf, int _value) internal pure {
if (_value >= 0) {
encodeType(_buf, MAJOR_TYPE_INT, uint(_value));
} else {
encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value));
}
}
function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_BYTES, _value.length);
_buf.append(_value);
}
function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length);
_buf.append(bytes(_value));
}
function startArray(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
using CBOR for Buffer.buffer;
OraclizeI oraclize;
OraclizeAddrResolverI OAR;
uint constant day = 60 * 60 * 24;
uint constant week = 60 * 60 * 24 * 7;
uint constant month = 60 * 60 * 24 * 30;
byte constant proofType_NONE = 0x00;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
byte constant proofType_Android = 0x40;
byte constant proofType_TLSNotary = 0x10;
string oraclize_network_name;
uint8 constant networkID_auto = 0;
uint8 constant networkID_morden = 2;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_consensys = 161;
mapping(bytes32 => bytes32) oraclize_randomDS_args;
mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified;
modifier oraclizeAPI {
if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) {
oraclize_setNetwork(networkID_auto);
}
if (address(oraclize) != OAR.getAddress()) {
oraclize = OraclizeI(OAR.getAddress());
}
_;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) {
// RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1)));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) {
return oraclize_setNetwork();
_networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetworkName(string memory _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string memory _networkName) {
return oraclize_network_name;
}
function oraclize_setNetwork() internal returns (bool _networkSet) {
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet
OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41);
oraclize_setNetworkName("eth_goerli");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 _myid, string memory _result) public {
__callback(_myid, _result, new bytes(0));
}
function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public {
return;
_myid; _result; _proof; // Silence compiler warnings
}
function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) {
return oraclize.getPrice(_datasource);
}
function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) {
return oraclize.getPrice(_datasource, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query.value(price)(0, _datasource, _arg);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query.value(price)(_timestamp, _datasource, _arg);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource,_gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query_withGasLimit.value(price)(_timestamp, _datasource, _arg, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query_withGasLimit.value(price)(0, _datasource, _arg, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query2.value(price)(0, _datasource, _arg1, _arg2);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return oraclize.query2.value(price)(_timestamp, _datasource, _arg1, _arg2);
}
function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query2_withGasLimit.value(price)(_timestamp, _datasource, _arg1, _arg2, _gasLimit);
}
function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return oraclize.query2_withGasLimit.value(price)(0, _datasource, _arg1, _arg2, _gasLimit);
}
function oraclize_query(string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN.value(price)(0, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN.value(price)(_timestamp, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN.value(price)(0, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN.value(price)(_timestamp, _datasource, args);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
uint price = oraclize.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs);
}
function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function oraclize_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return oraclize_query(_datasource, dynargs, _gasLimit);
}
function oraclize_setProof(byte _proofP) oraclizeAPI internal {
return oraclize.setProofType(_proofP);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) {
return oraclize.cbAddress();
}
function getCodeSize(address _addr) view internal returns (uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(_gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) {
return oraclize.randomDS_getSessionPubKeyHash();
}
function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i = 2; i < 2 + 2 * 20; i += 2) {
iaddr *= 256;
b1 = uint160(uint8(tmp[i]));
b2 = uint160(uint8(tmp[i + 1]));
if ((b1 >= 97) && (b1 <= 102)) {
b1 -= 87;
} else if ((b1 >= 65) && (b1 <= 70)) {
b1 -= 55;
} else if ((b1 >= 48) && (b1 <= 57)) {
b1 -= 48;
}
if ((b2 >= 97) && (b2 <= 102)) {
b2 -= 87;
} else if ((b2 >= 65) && (b2 <= 70)) {
b2 -= 55;
} else if ((b2 >= 48) && (b2 <= 57)) {
b2 -= 48;
}
iaddr += (b1 * 16 + b2);
}
return address(iaddr);
}
function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) {
minLength = b.length;
}
for (uint i = 0; i < minLength; i ++) {
if (a[i] < b[i]) {
return -1;
} else if (a[i] > b[i]) {
return 1;
}
}
if (a.length < b.length) {
return -1;
} else if (a.length > b.length) {
return 1;
} else {
return 0;
}
}
function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if (h.length < 1 || n.length < 1 || (n.length > h.length)) {
return -1;
} else if (h.length > (2 ** 128 - 1)) {
return -1;
} else {
uint subindex = 0;
for (uint i = 0; i < h.length; i++) {
if (h[i] == n[0]) {
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) {
subindex++;
}
if (subindex == n.length) {
return int(i);
}
}
}
return -1;
}
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, "", "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) {
babcde[k++] = _bc[i];
}
for (i = 0; i < _bd.length; i++) {
babcde[k++] = _bd[i];
}
for (i = 0; i < _be.length; i++) {
babcde[k++] = _be[i];
}
return string(babcde);
}
function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) {
return safeParseInt(_a, 0);
}
function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
require(!decimals, 'More than one decimal encountered in string!');
decimals = true;
} else {
revert("Non-numeral character encountered in string!");
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function parseInt(string memory _a) internal pure returns (uint _parsedInt) {
return parseInt(_a, 0);
}
function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) {
break;
} else {
_b--;
}
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
decimals = true;
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeString(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeBytes(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) {
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10; // Convert from seconds to ledger timer ticks
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(uint8(_nbytes));
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
/*
The following variables can be relaxed.
Check the relaxed random contract at https://github.com/oraclize/ethereum-examples
for an idea on how to override and replace commit hash variables.
*/
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal {
oraclize_randomDS_args[_queryId] = _commitment;
}
function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) {
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20);
sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs);
if (address(uint160(uint256(keccak256(_pubkey)))) == signer) {
return true;
} else {
(sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs);
return (address(uint160(uint256(keccak256(_pubkey)))) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) {
bool sigok;
// Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2);
copyBytes(_proof, _sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1 + 65 + 32);
tosign2[0] = byte(uint8(1)); //role
copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (!sigok) {
return false;
}
// Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1 + 65);
tosign3[0] = 0xFE;
copyBytes(_proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2);
copyBytes(_proof, 3 + 65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) {
// Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) {
return 1;
}
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (!proofVerified) {
return 2;
}
return 0;
}
function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) {
bool match_ = true;
require(_prefix.length == _nRandomBytes);
for (uint256 i = 0; i< _nRandomBytes; i++) {
if (_content[i] != _prefix[i]) {
match_ = false;
}
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) {
// Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId)
uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32;
bytes memory keyhash = new bytes(32);
copyBytes(_proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) {
return false;
}
bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2);
copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0);
// Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) {
return false;
}
// Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8 + 1 + 32);
copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65;
copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[_queryId];
} else return false;
// Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32 + 8 + 1 + 32);
copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) {
return false;
}
// Verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) {
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
*/
function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) {
uint minLength = _length + _toOffset;
require(_to.length >= minLength); // Buffer too small. Should be a better way?
uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint j = 32 + _toOffset;
while (i < (32 + _fromOffset + _length)) {
assembly {
let tmp := mload(add(_from, i))
mstore(add(_to, j), tmp)
}
i += 32;
j += 32;
}
return _to;
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
Duplicate Solidity's ecrecover, but catching the CALL return value
*/
function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) {
/*
We do our own memory management here. Solidity uses memory offset
0x40 to store the current end of memory. We write past it (as
writes are memory extensions), but don't update the offset so
Solidity will reuse it. The memory used here is only needed for
this context.
FIXME: inline assembly can't access return values
*/
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, _hash)
mstore(add(size, 32), _v)
mstore(add(size, 64), _r)
mstore(add(size, 96), _s)
ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code.
addr := mload(size)
}
return (ret, addr);
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
*/
function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
return (false, address(0));
}
/*
The signature format is a compact form of:
{bytes32 r}{bytes32 s}{uint8 v}
Compact means, uint8 is not padded to 32 bytes.
*/
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
/*
Here we are loading the last 32 bytes. We exploit the fact that
'mload' will pad with zeroes if we overread.
There is no 'mload8' to do this, but that would be nicer.
*/
v := byte(0, mload(add(_sig, 96)))
/*
Alternative solution:
'byte' is not working due to the Solidity parser, so lets
use the second best option, 'and'
v := and(mload(add(_sig, 65)), 255)
*/
}
/*
albeit non-transactional signatures are not specified by the YP, one would expect it
to match the YP range of [27, 28]
geth uses [0, 1] and some clients have followed. This might change, see:
https://github.com/ethereum/go-ethereum/issues/2053
*/
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (false, address(0));
}
return safer_ecrecover(_hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
/*
END ORACLIZE_API
*/
// File: nexusmutual-contracts/contracts/Quotation.sol
/* Copyright (C) 2017 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.7;
contract Quotation is Iupgradable {
using SafeMath for uint;
TokenFunctions internal tf;
TokenController internal tc;
TokenData internal td;
Pool1 internal p1;
PoolData internal pd;
QuotationData internal qd;
MCR internal m1;
MemberRoles internal mr;
bool internal locked;
event RefundEvent(address indexed user, bool indexed status, uint holdedCoverID, bytes32 reason);
modifier noReentrancy() {
require(!locked, "Reentrant call.");
locked = true;
_;
locked = false;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
m1 = MCR(ms.getLatestAddress("MC"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
qd = QuotationData(ms.getLatestAddress("QD"));
p1 = Pool1(ms.getLatestAddress("P1"));
pd = PoolData(ms.getLatestAddress("PD"));
mr = MemberRoles(ms.getLatestAddress("MR"));
}
function sendEther() public payable {
}
/**
* @dev Expires a cover after a set period of time.
* Changes the status of the Cover and reduces the current
* sum assured of all areas in which the quotation lies
* Unlocks the CN tokens of the cover. Updates the Total Sum Assured value.
* @param _cid Cover Id.
*/
function expireCover(uint _cid) public {
require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired));
tf.unlockCN(_cid);
bytes4 curr;
address scAddress;
uint sumAssured;
(, , scAddress, curr, sumAssured, ) = qd.getCoverDetailsByCoverID1(_cid);
if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted))
_removeSAFromCSA(_cid, sumAssured);
qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired));
}
/**
* @dev Checks if a cover should get expired/closed or not.
* @param _cid Cover Index.
* @return expire true if the Cover's time has expired, false otherwise.
*/
function checkCoverExpired(uint _cid) public view returns(bool expire) {
expire = qd.getValidityOfCover(_cid) < uint64(now);
}
/**
* @dev Updates the Sum Assured Amount of all the quotation.
* @param _cid Cover id
* @param _amount that will get subtracted Current Sum Assured
* amount that comes under a quotation.
*/
function removeSAFromCSA(uint _cid, uint _amount) public onlyInternal {
_removeSAFromCSA(_cid, _amount);
}
/**
* @dev Makes Cover funded via NXM tokens.
* @param smartCAdd Smart Contract Address
*/
function makeCoverUsingNXMTokens(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 coverCurr,
address smartCAdd,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
isMemberAndcheckPause
{
tc.burnFrom(msg.sender, coverDetails[2]); //need burn allowance
_verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @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
);
}
/**
* @dev Verifies signature.
* @param coverDetails details related to cover.
* @param coverPeriod validity of cover.
* @param smaratCA smarat contract address.
* @param _v argument from vrs hash.
* @param _r argument from vrs hash.
* @param _s argument from vrs hash.
*/
function verifySign(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 curr,
address smaratCA,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
view
returns(bool)
{
require(smaratCA != address(0));
require(pd.capReached() == 1, "Can not buy cover until cap reached for 1st time");
bytes32 hash = getOrderHash(coverDetails, coverPeriod, curr, smaratCA);
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 smaratCA smarat contract address.
*/
function getOrderHash(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 curr,
address smaratCA
)
public
view
returns(bytes32)
{
return keccak256(
abi.encodePacked(
coverDetails[0],
curr, coverPeriod,
smaratCA,
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 to get the status of recently holded coverID
* @param userAdd is the user address in concern
* @return the status of the concerned coverId
*/
function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) {
uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd);
if (holdedCoverLen == 0) {
return -1;
} else {
uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1));
return int(qd.holdedCoverIDStatus(holdedCoverID));
}
}
/**
* @dev to initiate the membership and the cover
* @param smartCAdd is the smart contract address to make cover on
* @param coverCurr is the currency used to make cover
* @param coverDetails list of details related to cover like cover amount, expire time, coverCurrPrice and priceNXM
* @param coverPeriod is cover period for which cover is being bought
* @param _v argument from vrs hash
* @param _r argument from vrs hash
* @param _s argument from vrs hash
*/
function initiateMembershipAndCover(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
payable
checkPause
{
require(coverDetails[3] > now);
require(!qd.timestampRepeated(coverDetails[4]));
qd.setTimestampRepeated(coverDetails[4]);
require(!ms.isMember(msg.sender));
require(qd.refundEligible(msg.sender) == false);
uint joinFee = td.joiningFee();
uint totalFee = joinFee;
if (coverCurr == "ETH") {
totalFee = joinFee.add(coverDetails[1]);
} else {
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr));
require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]));
}
require(msg.value == totalFee);
require(verifySign(coverDetails, coverPeriod, coverCurr, smartCAdd, _v, _r, _s));
qd.addHoldCover(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod);
qd.setRefundEligible(msg.sender, true);
}
/**
* @dev to get the verdict of kyc process
* @param status is the kyc status
* @param _add is the address of member
*/
function kycVerdict(address _add, bool status) public checkPause noReentrancy {
require(msg.sender == qd.kycAuthAddress());
_kycTrigger(status, _add);
}
/**
* @dev transfering Ethers to newly created quotation contract.
*/
function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy {
uint amount = address(this).balance;
IERC20 erc20;
if (amount > 0) {
// newAdd.transfer(amount);
Quotation newQT = Quotation(newAdd);
newQT.sendEther.value(amount)();
}
uint currAssetLen = pd.getAllCurrenciesLen();
for (uint64 i = 1; i < currAssetLen; i++) {
bytes4 currName = pd.getCurrenciesByIndex(i);
address currAddr = pd.getCurrencyAssetAddress(currName);
erc20 = IERC20(currAddr); //solhint-disable-line
if (erc20.balanceOf(address(this)) > 0) {
require(erc20.transfer(newAdd, erc20.balanceOf(address(this))));
}
}
}
/**
* @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 scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod
)
internal
{
uint cid = qd.getCoverLength();
qd.addCover(coverPeriod, coverDetails[0],
from, coverCurr, scAddress, coverDetails[1], coverDetails[2]);
// if cover period of quote is less than 60 days.
if (coverPeriod <= 60) {
p1.closeCoverOraclise(cid, uint64(uint(coverPeriod).mul(1 days)));
}
uint coverNoteAmount = (coverDetails[2].mul(qd.tokensRetained())).div(100);
tc.mint(from, coverNoteAmount);
tf.lockCN(coverNoteAmount, coverPeriod, cid, from);
qd.addInTotalSumAssured(coverCurr, coverDetails[0]);
qd.addInTotalSumAssuredSC(scAddress, coverCurr, coverDetails[0]);
tf.pushStakerRewards(scAddress, coverDetails[2]);
}
/**
* @dev Makes a vover.
* @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
)
internal
{
require(coverDetails[3] > now);
require(!qd.timestampRepeated(coverDetails[4]));
qd.setTimestampRepeated(coverDetails[4]);
require(verifySign(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s));
_makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod);
}
/**
* @dev Updates the Sum Assured Amount of all the quotation.
* @param _cid Cover id
* @param _amount that will get subtracted Current Sum Assured
* amount that comes under a quotation.
*/
function _removeSAFromCSA(uint _cid, uint _amount) internal checkPause {
address _add;
bytes4 coverCurr;
(, , _add, coverCurr, , ) = qd.getCoverDetailsByCoverID1(_cid);
qd.subFromTotalSumAssured(coverCurr, _amount);
qd.subFromTotalSumAssuredSC(_add, coverCurr, _amount);
}
/**
* @dev to trigger the kyc process
* @param status is the kyc status
* @param _add is the address of member
*/
function _kycTrigger(bool status, address _add) internal {
uint holdedCoverLen = qd.getUserHoldedCoverLength(_add).sub(1);
uint holdedCoverID = qd.getUserHoldedCoverByIndex(_add, holdedCoverLen);
address payable userAdd;
address scAddress;
bytes4 coverCurr;
uint16 coverPeriod;
uint[] memory coverDetails = new uint[](4);
IERC20 erc20;
(, userAdd, coverDetails) = qd.getHoldedCoverDetailsByID2(holdedCoverID);
(, scAddress, coverCurr, coverPeriod) = qd.getHoldedCoverDetailsByID1(holdedCoverID);
require(qd.refundEligible(userAdd));
qd.setRefundEligible(userAdd, false);
require(qd.holdedCoverIDStatus(holdedCoverID) == uint(QuotationData.HCIDStatus.kycPending));
uint joinFee = td.joiningFee();
if (status) {
mr.payJoiningFee.value(joinFee)(userAdd);
if (coverDetails[3] > now) {
qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPass));
address poolAdd = ms.getLatestAddress("P1");
if (coverCurr == "ETH") {
p1.sendEther.value(coverDetails[1])();
} else {
erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line
require(erc20.transfer(poolAdd, coverDetails[1]));
}
emit RefundEvent(userAdd, status, holdedCoverID, "KYC Passed");
_makeCover(userAdd, scAddress, coverCurr, coverDetails, coverPeriod);
} else {
qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPassNoCover));
if (coverCurr == "ETH") {
userAdd.transfer(coverDetails[1]);
} else {
erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line
require(erc20.transfer(userAdd, coverDetails[1]));
}
emit RefundEvent(userAdd, status, holdedCoverID, "Cover Failed");
}
} else {
qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycFailedOrRefunded));
uint totalRefund = joinFee;
if (coverCurr == "ETH") {
totalRefund = coverDetails[1].add(joinFee);
} else {
erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line
require(erc20.transfer(userAdd, coverDetails[1]));
}
userAdd.transfer(totalRefund);
emit RefundEvent(userAdd, status, holdedCoverID, "KYC Failed");
}
}
}
// File: nexusmutual-contracts/contracts/external/uniswap/solidity-interface.sol
pragma solidity 0.5.7;
contract Factory {
function getExchange(address token) public view returns (address);
function getToken(address exchange) public view returns (address);
}
contract Exchange {
function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256);
function getTokenToEthInputPrice(uint256 tokensSold) public view returns(uint256);
function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) public payable returns (uint256);
function ethToTokenTransferInput(uint256 minTokens, uint256 deadline, address recipient)
public payable returns (uint256);
function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline)
public payable returns (uint256);
function tokenToEthTransferInput(uint256 tokensSold, uint256 minEth, uint256 deadline, address recipient)
public payable returns (uint256);
function tokenToTokenSwapInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address tokenAddress
)
public returns (uint256);
function tokenToTokenTransferInput(
uint256 tokensSold,
uint256 minTokensBought,
uint256 minEthBought,
uint256 deadline,
address recipient,
address tokenAddress
)
public returns (uint256);
}
// File: nexusmutual-contracts/contracts/Pool2.sol
/* Copyright (C) 2017 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.7;
contract Pool2 is Iupgradable {
using SafeMath for uint;
MCR internal m1;
Pool1 internal p1;
PoolData internal pd;
Factory internal factory;
address public uniswapFactoryAddress;
uint internal constant DECIMAL1E18 = uint(10) ** 18;
bool internal locked;
constructor(address _uniswapFactoryAdd) public {
uniswapFactoryAddress = _uniswapFactoryAdd;
factory = Factory(_uniswapFactoryAdd);
}
function() external payable {}
event Liquidity(bytes16 typeOf, bytes16 functionName);
event Rebalancing(bytes4 iaCurr, uint tokenAmount);
modifier noReentrancy() {
require(!locked, "Reentrant call.");
locked = true;
_;
locked = false;
}
/**
* @dev to change the uniswap factory address
* @param newFactoryAddress is the new factory address in concern
* @return the status of the concerned coverId
*/
function changeUniswapFactoryAddress(address newFactoryAddress) external onlyInternal {
// require(ms.isOwner(msg.sender) || ms.checkIsAuthToGoverned(msg.sender));
uniswapFactoryAddress = newFactoryAddress;
factory = Factory(uniswapFactoryAddress);
}
/**
* @dev On upgrade transfer all investment assets and ether to new Investment Pool
* @param newPoolAddress New Investment Assest Pool address
*/
function upgradeInvestmentPool(address payable newPoolAddress) external onlyInternal noReentrancy {
uint len = pd.getInvestmentCurrencyLen();
for (uint64 i = 1; i < len; i++) {
bytes4 iaName = pd.getInvestmentCurrencyByIndex(i);
_upgradeInvestmentPool(iaName, newPoolAddress);
}
if (address(this).balance > 0) {
Pool2 newP2 = Pool2(newPoolAddress);
newP2.sendEther.value(address(this).balance)();
}
}
/**
* @dev Internal Swap of assets between Capital
* and Investment Sub pool for excess or insufficient
* liquidity conditions of a given currency.
*/
function internalLiquiditySwap(bytes4 curr) external onlyInternal noReentrancy {
uint caBalance;
uint baseMin;
uint varMin;
(, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr);
caBalance = _getCurrencyAssetsBalance(curr);
if (caBalance > uint(baseMin).add(varMin).mul(2)) {
_internalExcessLiquiditySwap(curr, baseMin, varMin, caBalance);
} else if (caBalance < uint(baseMin).add(varMin)) {
_internalInsufficientLiquiditySwap(curr, baseMin, varMin, caBalance);
}
}
/**
* @dev Saves a given investment asset details. To be called daily.
* @param curr array of Investment asset name.
* @param rate array of investment asset exchange rate.
* @param date current date in yyyymmdd.
*/
function saveIADetails(bytes4[] calldata curr, uint64[] calldata rate, uint64 date, bool bit)
external checkPause noReentrancy {
bytes4 maxCurr;
bytes4 minCurr;
uint64 maxRate;
uint64 minRate;
//ONLY NOTARZIE ADDRESS CAN POST
require(pd.isnotarise(msg.sender));
(maxCurr, maxRate, minCurr, minRate) = _calculateIARank(curr, rate);
pd.saveIARankDetails(maxCurr, maxRate, minCurr, minRate, date);
pd.updatelastDate(date);
uint len = curr.length;
for (uint i = 0; i < len; i++) {
pd.updateIAAvgRate(curr[i], rate[i]);
}
if (bit) //for testing purpose
_rebalancingLiquidityTrading(maxCurr, maxRate);
p1.saveIADetailsOracalise(pd.iaRatesTime());
}
/**
* @dev External Trade for excess or insufficient
* liquidity conditions of a given currency.
*/
function externalLiquidityTrade() external onlyInternal {
bool triggerTrade;
bytes4 curr;
bytes4 minIACurr;
bytes4 maxIACurr;
uint amount;
uint minIARate;
uint maxIARate;
uint baseMin;
uint varMin;
uint caBalance;
(maxIACurr, maxIARate, minIACurr, minIARate) = pd.getIARankDetailsByDate(pd.getLastDate());
uint len = pd.getAllCurrenciesLen();
for (uint64 i = 0; i < len; i++) {
curr = pd.getCurrenciesByIndex(i);
(, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr);
caBalance = _getCurrencyAssetsBalance(curr);
if (caBalance > uint(baseMin).add(varMin).mul(2)) { //excess
amount = caBalance.sub(((uint(baseMin).add(varMin)).mul(3)).div(2)); //*10**18;
triggerTrade = _externalExcessLiquiditySwap(curr, minIACurr, amount);
} else if (caBalance < uint(baseMin).add(varMin)) { // insufficient
amount = (((uint(baseMin).add(varMin)).mul(3)).div(2)).sub(caBalance);
triggerTrade = _externalInsufficientLiquiditySwap(curr, maxIACurr, amount);
}
if (triggerTrade) {
p1.triggerExternalLiquidityTrade();
}
}
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
m1 = MCR(ms.getLatestAddress("MC"));
pd = PoolData(ms.getLatestAddress("PD"));
p1 = Pool1(ms.getLatestAddress("P1"));
}
function sendEther() public payable {
}
/**
* @dev Gets currency asset balance for a given currency name.
*/
function _getCurrencyAssetsBalance(bytes4 _curr) public view returns(uint caBalance) {
if (_curr == "ETH") {
caBalance = address(p1).balance;
} else {
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr));
caBalance = erc20.balanceOf(address(p1));
}
}
/**
* @dev Transfers ERC20 investment asset from this Pool to another Pool.
*/
function _transferInvestmentAsset(
bytes4 _curr,
address _transferTo,
uint _amount
)
internal
{
if (_curr == "ETH") {
if (_amount > address(this).balance)
_amount = address(this).balance;
p1.sendEther.value(_amount)();
} else {
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr));
if (_amount > erc20.balanceOf(address(this)))
_amount = erc20.balanceOf(address(this));
require(erc20.transfer(_transferTo, _amount));
}
}
/**
* @dev to perform rebalancing
* @param iaCurr is the investment asset currency
* @param iaRate is the investment asset rate
*/
function _rebalancingLiquidityTrading(
bytes4 iaCurr,
uint64 iaRate
)
internal
checkPause
{
uint amountToSell;
uint totalRiskBal = pd.getLastVfull();
uint intermediaryEth;
uint ethVol = pd.ethVolumeLimit();
totalRiskBal = (totalRiskBal.mul(100000)).div(DECIMAL1E18);
Exchange exchange;
if (totalRiskBal > 0) {
amountToSell = ((totalRiskBal.mul(2).mul(
iaRate)).mul(pd.variationPercX100())).div(100 * 100 * 100000);
amountToSell = (amountToSell.mul(
10**uint(pd.getInvestmentAssetDecimals(iaCurr)))).div(100); // amount of asset to sell
if (iaCurr != "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) {
exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(iaCurr)));
intermediaryEth = exchange.getTokenToEthInputPrice(amountToSell);
if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) {
intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100);
amountToSell = (exchange.getEthToTokenInputPrice(intermediaryEth).mul(995)).div(1000);
}
IERC20 erc20;
erc20 = IERC20(pd.getCurrencyAssetAddress(iaCurr));
erc20.approve(address(exchange), amountToSell);
exchange.tokenToEthSwapInput(amountToSell, (exchange.getTokenToEthInputPrice(
amountToSell).mul(995)).div(1000), pd.uniswapDeadline().add(now));
} else if (iaCurr == "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) {
_transferInvestmentAsset(iaCurr, ms.getLatestAddress("P1"), amountToSell);
}
emit Rebalancing(iaCurr, amountToSell);
}
}
/**
* @dev Checks whether trading is required for a
* given investment asset at a given exchange rate.
*/
function _checkTradeConditions(
bytes4 curr,
uint64 iaRate,
uint totalRiskBal
)
internal
view
returns(bool check)
{
if (iaRate > 0) {
uint iaBalance = _getInvestmentAssetBalance(curr).div(DECIMAL1E18);
if (iaBalance > 0 && totalRiskBal > 0) {
uint iaMax;
uint iaMin;
uint checkNumber;
uint z;
(iaMin, iaMax) = pd.getInvestmentAssetHoldingPerc(curr);
z = pd.variationPercX100();
checkNumber = (iaBalance.mul(100 * 100000)).div(totalRiskBal.mul(iaRate));
if ((checkNumber > ((totalRiskBal.mul(iaMax.add(z))).mul(100000)).div(100)) ||
(checkNumber < ((totalRiskBal.mul(iaMin.sub(z))).mul(100000)).div(100)))
check = true; //eligibleIA
}
}
}
/**
* @dev Gets the investment asset rank.
*/
function _getIARank(
bytes4 curr,
uint64 rateX100,
uint totalRiskPoolBalance
)
internal
view
returns (int rhsh, int rhsl) //internal function
{
uint currentIAmaxHolding;
uint currentIAminHolding;
uint iaBalance = _getInvestmentAssetBalance(curr);
(currentIAminHolding, currentIAmaxHolding) = pd.getInvestmentAssetHoldingPerc(curr);
if (rateX100 > 0) {
uint rhsf;
rhsf = (iaBalance.mul(1000000)).div(totalRiskPoolBalance.mul(rateX100));
rhsh = int(rhsf - currentIAmaxHolding);
rhsl = int(rhsf - currentIAminHolding);
}
}
/**
* @dev Calculates the investment asset rank.
*/
function _calculateIARank(
bytes4[] memory curr,
uint64[] memory rate
)
internal
view
returns(
bytes4 maxCurr,
uint64 maxRate,
bytes4 minCurr,
uint64 minRate
)
{
int max = 0;
int min = -1;
int rhsh;
int rhsl;
uint totalRiskPoolBalance;
(totalRiskPoolBalance, ) = m1.calVtpAndMCRtp();
uint len = curr.length;
for (uint i = 0; i < len; i++) {
rhsl = 0;
rhsh = 0;
if (pd.getInvestmentAssetStatus(curr[i])) {
(rhsh, rhsl) = _getIARank(curr[i], rate[i], totalRiskPoolBalance);
if (rhsh > max || i == 0) {
max = rhsh;
maxCurr = curr[i];
maxRate = rate[i];
}
if (rhsl < min || rhsl == 0 || i == 0) {
min = rhsl;
minCurr = curr[i];
minRate = rate[i];
}
}
}
}
/**
* @dev to get balance of an investment asset
* @param _curr is the investment asset in concern
* @return the balance
*/
function _getInvestmentAssetBalance(bytes4 _curr) internal view returns (uint balance) {
if (_curr == "ETH") {
balance = address(this).balance;
} else {
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr));
balance = erc20.balanceOf(address(this));
}
}
/**
* @dev Creates Excess liquidity trading order for a given currency and a given balance.
*/
function _internalExcessLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal {
// require(ms.isInternal(msg.sender) || md.isnotarise(msg.sender));
bytes4 minIACurr;
// uint amount;
(, , minIACurr, ) = pd.getIARankDetailsByDate(pd.getLastDate());
if (_curr == minIACurr) {
// amount = _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)); //*10**18;
p1.transferCurrencyAsset(_curr, _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)));
} else {
p1.triggerExternalLiquidityTrade();
}
}
/**
* @dev insufficient liquidity swap
* for a given currency and a given balance.
*/
function _internalInsufficientLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal {
bytes4 maxIACurr;
uint amount;
(maxIACurr, , , ) = pd.getIARankDetailsByDate(pd.getLastDate());
if (_curr == maxIACurr) {
amount = (((_baseMin.add(_varMin)).mul(3)).div(2)).sub(_caBalance);
_transferInvestmentAsset(_curr, ms.getLatestAddress("P1"), amount);
} else {
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr));
if ((maxIACurr == "ETH" && address(this).balance > 0) ||
(maxIACurr != "ETH" && erc20.balanceOf(address(this)) > 0))
p1.triggerExternalLiquidityTrade();
}
}
/**
* @dev Creates External excess liquidity trading
* order for a given currency and a given balance.
* @param curr Currency Asset to Sell
* @param minIACurr Investment Asset to Buy
* @param amount Amount of Currency Asset to Sell
*/
function _externalExcessLiquiditySwap(
bytes4 curr,
bytes4 minIACurr,
uint256 amount
)
internal
returns (bool trigger)
{
uint intermediaryEth;
Exchange exchange;
IERC20 erc20;
uint ethVol = pd.ethVolumeLimit();
if (curr == minIACurr) {
p1.transferCurrencyAsset(curr, amount);
} else if (curr == "ETH" && minIACurr != "ETH") {
exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(minIACurr)));
if (amount > (address(exchange).balance.mul(ethVol)).div(100)) { // 4% ETH volume limit
amount = (address(exchange).balance.mul(ethVol)).div(100);
trigger = true;
}
p1.transferCurrencyAsset(curr, amount);
exchange.ethToTokenSwapInput.value(amount)
(exchange.getEthToTokenInputPrice(amount).mul(995).div(1000), pd.uniswapDeadline().add(now));
} else if (curr != "ETH" && minIACurr == "ETH") {
exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr)));
erc20 = IERC20(pd.getCurrencyAssetAddress(curr));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) {
intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100);
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
trigger = true;
}
p1.transferCurrencyAsset(curr, amount);
// erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange)));
erc20.approve(address(exchange), amount);
exchange.tokenToEthSwapInput(amount, (
intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now));
} else {
exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr)));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) {
intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100);
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
trigger = true;
}
Exchange tmp = Exchange(factory.getExchange(
pd.getInvestmentAssetAddress(minIACurr))); // minIACurr exchange
if (intermediaryEth > address(tmp).balance.mul(ethVol).div(100)) {
intermediaryEth = address(tmp).balance.mul(ethVol).div(100);
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
trigger = true;
}
p1.transferCurrencyAsset(curr, amount);
erc20 = IERC20(pd.getCurrencyAssetAddress(curr));
erc20.approve(address(exchange), amount);
exchange.tokenToTokenSwapInput(amount, (tmp.getEthToTokenInputPrice(
intermediaryEth).mul(995)).div(1000), (intermediaryEth.mul(995)).div(1000),
pd.uniswapDeadline().add(now), pd.getInvestmentAssetAddress(minIACurr));
}
}
/**
* @dev insufficient liquidity swap
* for a given currency and a given balance.
* @param curr Currency Asset to buy
* @param maxIACurr Investment Asset to sell
* @param amount Amount of Investment Asset to sell
*/
function _externalInsufficientLiquiditySwap(
bytes4 curr,
bytes4 maxIACurr,
uint256 amount
)
internal
returns (bool trigger)
{
Exchange exchange;
IERC20 erc20;
uint intermediaryEth;
// uint ethVol = pd.ethVolumeLimit();
if (curr == maxIACurr) {
_transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount);
} else if (curr == "ETH" && maxIACurr != "ETH") {
exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr)));
intermediaryEth = exchange.getEthToTokenInputPrice(amount);
if (amount > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) {
amount = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100);
// amount = exchange.getEthToTokenInputPrice(intermediaryEth);
intermediaryEth = exchange.getEthToTokenInputPrice(amount);
trigger = true;
}
erc20 = IERC20(pd.getCurrencyAssetAddress(maxIACurr));
if (intermediaryEth > erc20.balanceOf(address(this))) {
intermediaryEth = erc20.balanceOf(address(this));
}
// erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange)));
erc20.approve(address(exchange), intermediaryEth);
exchange.tokenToEthTransferInput(intermediaryEth, (
exchange.getTokenToEthInputPrice(intermediaryEth).mul(995)).div(1000),
pd.uniswapDeadline().add(now), address(p1));
} else if (curr != "ETH" && maxIACurr == "ETH") {
exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr)));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > address(this).balance)
intermediaryEth = address(this).balance;
if (intermediaryEth > (address(exchange).balance.mul
(pd.ethVolumeLimit())).div(100)) { // 4% ETH volume limit
intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100);
trigger = true;
}
exchange.ethToTokenTransferInput.value(intermediaryEth)((exchange.getEthToTokenInputPrice(
intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1));
} else {
address currAdd = pd.getCurrencyAssetAddress(curr);
exchange = Exchange(factory.getExchange(currAdd));
intermediaryEth = exchange.getTokenToEthInputPrice(amount);
if (intermediaryEth > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) {
intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100);
trigger = true;
}
Exchange tmp = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr)));
if (intermediaryEth > address(tmp).balance.mul(pd.ethVolumeLimit()).div(100)) {
intermediaryEth = address(tmp).balance.mul(pd.ethVolumeLimit()).div(100);
// amount = exchange.getEthToTokenInputPrice(intermediaryEth);
trigger = true;
}
uint maxIAToSell = tmp.getEthToTokenInputPrice(intermediaryEth);
erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr));
uint maxIABal = erc20.balanceOf(address(this));
if (maxIAToSell > maxIABal) {
maxIAToSell = maxIABal;
intermediaryEth = tmp.getTokenToEthInputPrice(maxIAToSell);
// amount = exchange.getEthToTokenInputPrice(intermediaryEth);
}
amount = exchange.getEthToTokenInputPrice(intermediaryEth);
erc20.approve(address(tmp), maxIAToSell);
tmp.tokenToTokenTransferInput(maxIAToSell, (
amount.mul(995)).div(1000), (
intermediaryEth), pd.uniswapDeadline().add(now), address(p1), currAdd);
}
}
/**
* @dev Transfers ERC20 investment asset from this Pool to another Pool.
*/
function _upgradeInvestmentPool(
bytes4 _curr,
address _newPoolAddress
)
internal
{
IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr));
if (erc20.balanceOf(address(this)) > 0)
require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this))));
}
}
// File: nexusmutual-contracts/contracts/Pool1.sol
/* Copyright (C) 2017 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.7;
contract Pool1 is usingOraclize, Iupgradable {
using SafeMath for uint;
Quotation internal q2;
NXMToken internal tk;
TokenController internal tc;
TokenFunctions internal tf;
Pool2 internal p2;
PoolData internal pd;
MCR internal m1;
Claims public c1;
TokenData internal td;
bool internal locked;
uint internal constant DECIMAL1E18 = uint(10) ** 18;
// uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18;
event Apiresult(address indexed sender, string msg, bytes32 myid);
event Payout(address indexed to, uint coverId, uint tokens);
modifier noReentrancy() {
require(!locked, "Reentrant call.");
locked = true;
_;
locked = false;
}
function () external payable {} //solhint-disable-line
/**
* @dev Pays out the sum assured in case a claim is accepted
* @param coverid Cover Id.
* @param claimid Claim Id.
* @return succ true if payout is successful, false otherwise.
*/
function sendClaimPayout(
uint coverid,
uint claimid,
uint sumAssured,
address payable coverHolder,
bytes4 coverCurr
)
external
onlyInternal
noReentrancy
returns(bool succ)
{
uint sa = sumAssured.div(DECIMAL1E18);
bool check;
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr));
//Payout
if (coverCurr == "ETH" && address(this).balance >= sumAssured) {
// check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured);
coverHolder.transfer(sumAssured);
check = true;
} else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) {
erc20.transfer(coverHolder, sumAssured);
check = true;
}
if (check == true) {
q2.removeSAFromCSA(coverid, sa);
pd.changeCurrencyAssetVarMin(coverCurr,
pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured));
emit Payout(coverHolder, coverid, sumAssured);
succ = true;
} else {
c1.setClaimStatus(claimid, 12);
}
_triggerExternalLiquidityTrade();
// p2.internalLiquiditySwap(coverCurr);
tf.burnStakerLockedToken(coverid, coverCurr, sumAssured);
}
/**
* @dev to trigger external liquidity trade
*/
function triggerExternalLiquidityTrade() external onlyInternal {
_triggerExternalLiquidityTrade();
}
///@dev Oraclize call to close emergency pause.
function closeEmergencyPause(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", "", 300000);
_saveApiDetails(myid, "EP", 0);
}
/// @dev Calls the Oraclize Query to close a given Claim after a given period of time.
/// @param id Claim Id to be closed
/// @param time Time (in seconds) after which Claims assessment voting needs to be closed
function closeClaimsOraclise(uint id, uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000);
_saveApiDetails(myid, "CLA", id);
}
/// @dev Calls Oraclize Query to expire a given Cover after a given period of time.
/// @param id Quote Id to be expired
/// @param time Time (in seconds) after which the cover should be expired
function closeCoverOraclise(uint id, uint64 time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", strConcat(
"http://a1.nexusmutual.io/api/Claims/closeClaim_hash/", uint2str(id)), 1000000);
_saveApiDetails(myid, "COV", id);
}
/// @dev Calls the Oraclize Query to initiate MCR calculation.
/// @param time Time (in milliseconds) after which the next MCR calculation should be initiated
function mcrOraclise(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/postMCR/M1", 0);
_saveApiDetails(myid, "MCR", 0);
}
/// @dev Calls the Oraclize Query in case MCR calculation fails.
/// @param time Time (in seconds) after which the next MCR calculation should be initiated
function mcrOracliseFail(uint id, uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(4, time, "URL", "", 1000000);
_saveApiDetails(myid, "MCRF", id);
}
/// @dev Oraclize call to update investment asset rates.
function saveIADetailsOracalise(uint time) external onlyInternal {
bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/saveIADetails/M1", 0);
_saveApiDetails(myid, "IARB", 0);
}
/**
* @dev Transfers all assest (i.e ETH balance, Currency Assest) from old Pool to new Pool
* @param newPoolAddress Address of the new Pool
*/
function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal {
for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) {
bytes4 caName = pd.getCurrenciesByIndex(i);
_upgradeCapitalPool(caName, newPoolAddress);
}
if (address(this).balance > 0) {
Pool1 newP1 = Pool1(newPoolAddress);
newP1.sendEther.value(address(this).balance)();
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
m1 = MCR(ms.getLatestAddress("MC"));
tk = NXMToken(ms.tokenAddress());
tf = TokenFunctions(ms.getLatestAddress("TF"));
tc = TokenController(ms.getLatestAddress("TC"));
pd = PoolData(ms.getLatestAddress("PD"));
q2 = Quotation(ms.getLatestAddress("QT"));
p2 = Pool2(ms.getLatestAddress("P2"));
c1 = Claims(ms.getLatestAddress("CL"));
td = TokenData(ms.getLatestAddress("TD"));
}
function sendEther() public payable {
}
/**
* @dev transfers currency asset to an address
* @param curr is the currency of currency asset to transfer
* @param amount is amount of currency asset to transfer
* @return boolean to represent success or failure
*/
function transferCurrencyAsset(
bytes4 curr,
uint amount
)
public
onlyInternal
noReentrancy
returns(bool)
{
return _transferCurrencyAsset(curr, amount);
}
/// @dev Handles callback of external oracle query.
function __callback(bytes32 myid, string memory result) public {
result; //silence compiler warning
// owner will be removed from production build
ms.delegateCallBack(myid);
}
/// @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
isMember
checkPause
payable
{
require(msg.value == coverDetails[1]);
q2.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
isMember
checkPause
{
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr));
require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed");
q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/// @dev Enables user to purchase NXM at the current token price.
function buyToken() public payable isMember checkPause returns(bool success) {
require(msg.value > 0);
uint tokenPurchased = _getToken(address(this).balance, msg.value);
tc.mint(msg.sender, tokenPurchased);
success = true;
}
/// @dev Sends a given amount of Ether to a given address.
/// @param amount amount (in wei) to send.
/// @param _add Receiver's address.
/// @return succ True if transfer is a success, otherwise False.
function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) {
require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern");
succ = _add.send(amount);
}
/**
* @dev 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 isMember noReentrancy checkPause returns(bool success) {
require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance");
require(!tf.isLockedForMemberVote(msg.sender), "Member voted");
require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit");
uint sellingPrice = _getWei(_amount);
tc.burnFrom(msg.sender, _amount);
msg.sender.transfer(sellingPrice);
success = true;
}
/**
* @dev gives the investment asset balance
* @return investment asset balance
*/
function getInvestmentAssetBalance() public view returns (uint balance) {
IERC20 erc20;
uint currTokens;
for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) {
bytes4 currency = pd.getInvestmentCurrencyByIndex(i);
erc20 = IERC20(pd.getInvestmentAssetAddress(currency));
currTokens = erc20.balanceOf(address(p2));
if (pd.getIAAvgRate(currency) > 0)
balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency)));
}
balance = balance.add(address(p2).balance);
}
/**
* @dev 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) public view returns(uint weiToPay) {
return _getWei(amount);
}
/**
* @dev Returns the amount of token a buyer will get for corresponding wei
* @param weiPaid Amount of wei
* @return tokenToGet Amount of tokens the buyer will get
*/
function getToken(uint weiPaid) public view returns(uint tokenToGet) {
return _getToken((address(this).balance).add(weiPaid), weiPaid);
}
/**
* @dev to trigger external liquidity trade
*/
function _triggerExternalLiquidityTrade() internal {
if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) {
pd.setLastLiquidityTradeTrigger();
bytes32 myid = _oraclizeQuery(4, pd.liquidityTradeCallbackTime(), "URL", "", 300000);
_saveApiDetails(myid, "ULT", 0);
}
}
/**
* @dev 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) internal view returns(uint weiToPay) {
uint tokenPrice;
uint weiPaid;
uint tokenSupply = tk.totalSupply();
uint vtp;
uint mcrFullperc;
uint vFull;
uint mcrtp;
(mcrFullperc, , vFull, ) = pd.getLastMCR();
(vtp, ) = m1.calVtpAndMCRtp();
while (_amount > 0) {
mcrtp = (mcrFullperc.mul(vtp)).div(vFull);
tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp);
tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5%
if (_amount <= td.priceStep().mul(DECIMAL1E18)) {
weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18));
break;
} else {
_amount = _amount.sub(td.priceStep().mul(DECIMAL1E18));
tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18));
weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18);
vtp = vtp.sub(weiPaid);
weiToPay = weiToPay.add(weiPaid);
}
}
}
/**
* @dev gives the token
* @param _poolBalance is the pool balance
* @param _weiPaid is the amount paid in wei
* @return the token to get
*/
function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) {
uint tokenPrice;
uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18);
uint tempTokens;
uint superWeiSpent;
uint tokenSupply = tk.totalSupply();
uint vtp;
uint mcrFullperc;
uint vFull;
uint mcrtp;
(mcrFullperc, , vFull, ) = pd.getLastMCR();
(vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid));
require(m1.calculateTokenPrice("ETH") > 0, "Token price can not be zero");
while (superWeiLeft > 0) {
mcrtp = (mcrFullperc.mul(vtp)).div(vFull);
tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp);
tempTokens = superWeiLeft.div(tokenPrice);
if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) {
tokenToGet = tokenToGet.add(tempTokens);
break;
} else {
tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18));
tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18));
superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice);
superWeiLeft = superWeiLeft.sub(superWeiSpent);
vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18));
}
}
}
/**
* @dev Save the details of the Oraclize API.
* @param myid Id return by the oraclize query.
* @param _typeof type of the query for which oraclize call is made.
* @param id ID of the proposal, quote, cover etc. for which oraclize call is made.
*/
function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal {
pd.saveApiDetails(myid, _typeof, id);
pd.addInAllApiCall(myid);
}
/**
* @dev transfers currency asset
* @param _curr is currency of asset to transfer
* @param _amount is the amount to be transferred
* @return boolean representing the success of transfer
*/
function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) {
if (_curr == "ETH") {
if (address(this).balance < _amount)
_amount = address(this).balance;
p2.sendEther.value(_amount)();
succ = true;
} else {
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line
if (erc20.balanceOf(address(this)) < _amount)
_amount = erc20.balanceOf(address(this));
require(erc20.transfer(address(p2), _amount));
succ = true;
}
}
/**
* @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade.
*/
function _upgradeCapitalPool(
bytes4 _curr,
address _newPoolAddress
)
internal
{
IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr));
if (erc20.balanceOf(address(this)) > 0)
require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this))));
}
/**
* @dev oraclize query
* @param paramCount is number of paramters passed
* @param timestamp is the current timestamp
* @param datasource in concern
* @param arg in concern
* @param gasLimit required for query
* @return id of oraclize query
*/
function _oraclizeQuery(
uint paramCount,
uint timestamp,
string memory datasource,
string memory arg,
uint gasLimit
)
internal
returns (bytes32 id)
{
if (paramCount == 4) {
id = oraclize_query(timestamp, datasource, arg, gasLimit);
} else if (paramCount == 3) {
id = oraclize_query(timestamp, datasource, arg);
} else {
id = oraclize_query(datasource, arg);
}
}
}
// File: nexusmutual-contracts/contracts/MCR.sol
/* Copyright (C) 2017 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.7;
contract MCR is Iupgradable {
using SafeMath for uint;
Pool1 internal p1;
PoolData internal pd;
NXMToken internal tk;
QuotationData internal qd;
MemberRoles internal mr;
TokenData internal td;
ProposalCategory internal proposalCategory;
uint private constant DECIMAL1E18 = uint(10) ** 18;
uint private constant DECIMAL1E05 = uint(10) ** 5;
uint private constant DECIMAL1E19 = uint(10) ** 19;
uint private constant minCapFactor = uint(10) ** 21;
uint public variableMincap;
uint public dynamicMincapThresholdx100 = 13000;
uint public dynamicMincapIncrementx100 = 100;
event MCREvent(
uint indexed date,
uint blockNumber,
bytes4[] allCurr,
uint[] allCurrRates,
uint mcrEtherx100,
uint mcrPercx100,
uint vFull
);
/**
* @dev Adds new MCR data.
* @param mcrP Minimum Capital Requirement in percentage.
* @param vF Pool1 fund value in Ether used in the last full daily calculation of the Capital model.
* @param onlyDate Date(yyyymmdd) at which MCR details are getting added.
*/
function addMCRData(
uint mcrP,
uint mcrE,
uint vF,
bytes4[] calldata curr,
uint[] calldata _threeDayAvg,
uint64 onlyDate
)
external
checkPause
{
require(proposalCategory.constructorCheck());
require(pd.isnotarise(msg.sender));
if (mr.launched() && pd.capReached() != 1) {
if (mcrP >= 10000)
pd.setCapReached(1);
}
uint len = pd.getMCRDataLength();
_addMCRData(len, onlyDate, curr, mcrE, mcrP, vF, _threeDayAvg);
}
/**
* @dev Adds MCR Data for last failed attempt.
*/
function addLastMCRData(uint64 date) external checkPause onlyInternal {
uint64 lastdate = uint64(pd.getLastMCRDate());
uint64 failedDate = uint64(date);
if (failedDate >= lastdate) {
uint mcrP;
uint mcrE;
uint vF;
(mcrP, mcrE, vF, ) = pd.getLastMCR();
uint len = pd.getAllCurrenciesLen();
pd.pushMCRData(mcrP, mcrE, vF, date);
for (uint j = 0; j < len; j++) {
bytes4 currName = pd.getCurrenciesByIndex(j);
pd.updateCAAvgRate(currName, pd.getCAAvgRate(currName));
}
emit MCREvent(date, block.number, new bytes4[](0), new uint[](0), mcrE, mcrP, vF);
// Oraclize call for next MCR calculation
_callOracliseForMCR();
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
qd = QuotationData(ms.getLatestAddress("QD"));
p1 = Pool1(ms.getLatestAddress("P1"));
pd = PoolData(ms.getLatestAddress("PD"));
tk = NXMToken(ms.tokenAddress());
mr = MemberRoles(ms.getLatestAddress("MR"));
td = TokenData(ms.getLatestAddress("TD"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Gets total sum assured(in ETH).
* @return amount of sum assured
*/
function getAllSumAssurance() public view returns(uint amount) {
uint len = pd.getAllCurrenciesLen();
for (uint i = 0; i < len; i++) {
bytes4 currName = pd.getCurrenciesByIndex(i);
if (currName == "ETH") {
amount = amount.add(qd.getTotalSumAssured(currName));
} else {
if (pd.getCAAvgRate(currName) > 0)
amount = amount.add((qd.getTotalSumAssured(currName).mul(100)).div(pd.getCAAvgRate(currName)));
}
}
}
/**
* @dev Calculates V(Tp) and MCR%(Tp), i.e, Pool Fund Value in Ether
* and MCR% used in the Token Price Calculation.
* @return vtp Pool Fund Value in Ether used for the Token Price Model
* @return mcrtp MCR% used in the Token Price Model.
*/
function _calVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) {
vtp = 0;
IERC20 erc20;
uint currTokens = 0;
uint i;
for (i = 1; i < pd.getAllCurrenciesLen(); i++) {
bytes4 currency = pd.getCurrenciesByIndex(i);
erc20 = IERC20(pd.getCurrencyAssetAddress(currency));
currTokens = erc20.balanceOf(address(p1));
if (pd.getCAAvgRate(currency) > 0)
vtp = vtp.add((currTokens.mul(100)).div(pd.getCAAvgRate(currency)));
}
vtp = vtp.add(poolBalance).add(p1.getInvestmentAssetBalance());
uint mcrFullperc;
uint vFull;
(mcrFullperc, , vFull, ) = pd.getLastMCR();
if (vFull > 0) {
mcrtp = (mcrFullperc.mul(vtp)).div(vFull);
}
}
/**
* @dev Calculates the Token Price of NXM in a given currency.
* @param curr Currency name.
*/
function calculateStepTokenPrice(
bytes4 curr,
uint mcrtp
)
public
view
onlyInternal
returns(uint tokenPrice)
{
return _calculateTokenPrice(curr, mcrtp);
}
/**
* @dev Calculates the Token Price of NXM in a given currency
* with provided token supply for dynamic token price calculation
* @param curr Currency name.
*/
function calculateTokenPrice (bytes4 curr) public view returns(uint tokenPrice) {
uint mcrtp;
(, mcrtp) = _calVtpAndMCRtp(address(p1).balance);
return _calculateTokenPrice(curr, mcrtp);
}
function calVtpAndMCRtp() public view returns(uint vtp, uint mcrtp) {
return _calVtpAndMCRtp(address(p1).balance);
}
function calculateVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) {
return _calVtpAndMCRtp(poolBalance);
}
function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) public view returns(uint lowerThreshold, uint upperThreshold)
{
minCap = (minCap.mul(minCapFactor)).add(variableMincap);
uint lower = 0;
if (vtp >= vF) {
upperThreshold = vtp.mul(120).mul(100).div((minCap)); //Max Threshold = [MAX(Vtp, Vfull) x 120] / mcrMinCap
} else {
upperThreshold = vF.mul(120).mul(100).div((minCap));
}
if (vtp > 0) {
lower = totalSA.mul(DECIMAL1E18).mul(pd.shockParameter()).div(100);
if(lower < minCap.mul(11).div(10))
lower = minCap.mul(11).div(10);
}
if (lower > 0) { //Min Threshold = [Vtp / MAX(TotalActiveSA x ShockParameter, mcrMinCap x 1.1)] x 100
lowerThreshold = vtp.mul(100).mul(100).div(lower);
}
}
/**
* @dev Gets max numbers of tokens that can be sold at the moment.
*/
function getMaxSellTokens() public view returns(uint maxTokens) {
uint baseMin = pd.getCurrencyAssetBaseMin("ETH");
uint maxTokensAccPoolBal;
if (address(p1).balance > baseMin.mul(50).div(100)) {
maxTokensAccPoolBal = address(p1).balance.sub(
(baseMin.mul(50)).div(100));
}
maxTokensAccPoolBal = (maxTokensAccPoolBal.mul(DECIMAL1E18)).div(
(calculateTokenPrice("ETH").mul(975)).div(1000));
uint lastMCRPerc = pd.getLastMCRPerc();
if (lastMCRPerc > 10000)
maxTokens = (((uint(lastMCRPerc).sub(10000)).mul(2000)).mul(DECIMAL1E18)).div(10000);
if (maxTokens > maxTokensAccPoolBal)
maxTokens = maxTokensAccPoolBal;
}
/**
* @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 == "DMCT") {
val = dynamicMincapThresholdx100;
} else if (code == "DMCI") {
val = dynamicMincapIncrementx100;
}
}
/**
* @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 == "DMCT") {
dynamicMincapThresholdx100 = val;
} else if (code == "DMCI") {
dynamicMincapIncrementx100 = val;
}
else {
revert("Invalid param code");
}
}
/**
* @dev Calls oraclize query to calculate MCR details after 24 hours.
*/
function _callOracliseForMCR() internal {
p1.mcrOraclise(pd.mcrTime());
}
/**
* @dev Calculates the Token Price of NXM in a given currency
* with provided token supply for dynamic token price calculation
* @param _curr Currency name.
* @return tokenPrice Token price.
*/
function _calculateTokenPrice(
bytes4 _curr,
uint mcrtp
)
internal
view
returns(uint tokenPrice)
{
uint getA;
uint getC;
uint getCAAvgRate;
uint tokenExponentValue = td.tokenExponent();
// uint max = (mcrtp.mul(mcrtp).mul(mcrtp).mul(mcrtp));
uint max = mcrtp ** tokenExponentValue;
uint dividingFactor = tokenExponentValue.mul(4);
(getA, getC, getCAAvgRate) = pd.getTokenPriceDetails(_curr);
uint mcrEth = pd.getLastMCREther();
getC = getC.mul(DECIMAL1E18);
tokenPrice = (mcrEth.mul(DECIMAL1E18).mul(max).div(getC)).div(10 ** dividingFactor);
tokenPrice = tokenPrice.add(getA.mul(DECIMAL1E18).div(DECIMAL1E05));
tokenPrice = tokenPrice.mul(getCAAvgRate * 10);
tokenPrice = (tokenPrice).div(10**3);
}
/**
* @dev Adds MCR Data. Checks if MCR is within valid
* thresholds in order to rule out any incorrect calculations
*/
function _addMCRData(
uint len,
uint64 newMCRDate,
bytes4[] memory curr,
uint mcrE,
uint mcrP,
uint vF,
uint[] memory _threeDayAvg
)
internal
{
uint vtp = 0;
uint lowerThreshold = 0;
uint upperThreshold = 0;
if (len > 1) {
(vtp, ) = _calVtpAndMCRtp(address(p1).balance);
(lowerThreshold, upperThreshold) = getThresholdValues(vtp, vF, getAllSumAssurance(), pd.minCap());
}
if(mcrP > dynamicMincapThresholdx100)
variableMincap = (variableMincap.mul(dynamicMincapIncrementx100.add(10000)).add(minCapFactor.mul(pd.minCap().mul(dynamicMincapIncrementx100)))).div(10000);
// Explanation for above formula :-
// actual formula -> variableMinCap = variableMinCap + (variableMinCap+minCap)*dynamicMincapIncrement/100
// Implemented formula is simplified form of actual formula.
// Let consider above formula as b = b + (a+b)*c/100
// here, dynamicMincapIncrement is in x100 format.
// so b+(a+b)*cx100/10000 can be written as => (10000.b + b.cx100 + a.cx100)/10000.
// It can further simplify to (b.(10000+cx100) + a.cx100)/10000.
if (len == 1 || (mcrP) >= lowerThreshold
&& (mcrP) <= upperThreshold) {
vtp = pd.getLastMCRDate(); // due to stack to deep error,we are reusing already declared variable
pd.pushMCRData(mcrP, mcrE, vF, newMCRDate);
for (uint i = 0; i < curr.length; i++) {
pd.updateCAAvgRate(curr[i], _threeDayAvg[i]);
}
emit MCREvent(newMCRDate, block.number, curr, _threeDayAvg, mcrE, mcrP, vF);
// Oraclize call for next MCR calculation
if (vtp < newMCRDate) {
_callOracliseForMCR();
}
} else {
p1.mcrOracliseFail(newMCRDate, pd.mcrFailTime());
}
}
}
// File: nexusmutual-contracts/contracts/Claims.sol
/* Copyright (C) 2017 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.7;
contract Claims is Iupgradable {
using SafeMath for uint;
TokenFunctions internal tf;
NXMToken internal tk;
TokenController internal tc;
ClaimsReward internal cr;
Pool1 internal p1;
ClaimsData internal cd;
TokenData internal td;
PoolData internal pd;
Pool2 internal p2;
QuotationData internal qd;
MCR internal m1;
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 Gets claim details of claim id = pending claim start + given index
*/
function getClaimFromNewStart(
uint index
)
external
view
returns (
uint coverId,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
(coverId, claimId, voteCA, voteMV, statusnumber) = cd.getClaimFromNewStart(index, msg.sender);
// status = rewardStatus[statusnumber].claimStatusDesc;
}
/**
* @dev Gets details of a claim submitted by the calling user, at a given index
*/
function getUserClaimByIndex(
uint index
)
external
view
returns(
uint status,
uint coverId,
uint claimId
)
{
uint statusno;
(statusno, coverId, claimId) = cd.getUserClaimByIndex(index, msg.sender);
status = statusno;
}
/**
* @dev Gets details of a given claim id.
* @param _claimId Claim Id.
* @return status Current status of claim id
* @return finalVerdict Decision made on the claim, 1 -> acceptance, -1 -> denial
* @return claimOwner Address through which claim is submitted
* @return coverId Coverid associated with the claim id
*/
function getClaimbyIndex(uint _claimId) external view returns (
uint claimId,
uint status,
int8 finalVerdict,
address claimOwner,
uint coverId
)
{
uint stat;
claimId = _claimId;
(, coverId, finalVerdict, stat, , ) = cd.getClaim(_claimId);
claimOwner = qd.getCoverMemberAddress(coverId);
status = 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 curr = qd.getCurrencyOfCover(coverId);
uint tokenx1e18 = m1.calculateTokenPrice(curr);
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 {
tk = NXMToken(ms.tokenAddress());
td = TokenData(ms.getLatestAddress("TD"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tc = TokenController(ms.getLatestAddress("TC"));
p1 = Pool1(ms.getLatestAddress("P1"));
p2 = Pool2(ms.getLatestAddress("P2"));
pd = PoolData(ms.getLatestAddress("PD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
cd = ClaimsData(ms.getLatestAddress("CD"));
qd = QuotationData(ms.getLatestAddress("QD"));
m1 = MCR(ms.getLatestAddress("MC"));
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function changePendingClaimStart() public onlyInternal {
uint origstat;
uint state12Count;
uint pendingClaimStart = cd.pendingClaimStart();
uint actualClaimLength = cd.actualClaimLength();
for (uint i = pendingClaimStart; i < actualClaimLength; i++) {
(, , , origstat, , state12Count) = cd.getClaim(i);
if (origstat > 5 && ((origstat != 12) || (origstat == 12 && state12Count >= 60)))
cd.setpendingClaimStart(i);
else
break;
}
}
/**
* @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) public {
address qadd = qd.getCoverMemberAddress(coverId);
require(qadd == msg.sender);
uint8 cStatus;
(, cStatus, , , ) = qd.getCoverDetailsByCoverID2(coverId);
require(cStatus != uint8(QuotationData.CoverStatus.ClaimSubmitted), "Claim already submitted");
require(cStatus != uint8(QuotationData.CoverStatus.CoverExpired), "Cover already expired");
if (ms.isPause() == false) {
_addClaim(coverId, now, qadd);
} else {
cd.setClaimAtEmergencyPause(coverId, now, false);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.Requested));
}
}
/**
* @dev Submits the Claims queued once the emergency pause is switched off.
*/
function submitClaimAfterEPOff() public onlyInternal {
uint lengthOfClaimSubmittedAtEP = cd.getLengthOfClaimSubmittedAtEP();
uint firstClaimIndexToSubmitAfterEP = cd.getFirstClaimIndexToSubmitAfterEP();
uint coverId;
uint dateUpd;
bool submit;
address qadd;
for (uint i = firstClaimIndexToSubmitAfterEP; i < lengthOfClaimSubmittedAtEP; i++) {
(coverId, dateUpd, submit) = cd.getClaimOfEmergencyPauseByIndex(i);
require(submit == false);
qadd = qd.getCoverMemberAddress(coverId);
_addClaim(coverId, dateUpd, qadd);
cd.setClaimSubmittedAtEPTrue(i, true);
}
cd.setFirstClaimIndexToSubmitAfterEP(lengthOfClaimSubmittedAtEP);
}
/**
* @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);
}
}
/**
* @dev Pause Voting of All Pending Claims when Emergency Pause Start.
*/
function pauseAllPendingClaimsVoting() public onlyInternal {
uint firstIndex = cd.pendingClaimStart();
uint actualClaimLength = cd.actualClaimLength();
for (uint i = firstIndex; i < actualClaimLength; i++) {
if (checkVoteClosing(i) == 0) {
uint dateUpd = cd.getClaimDateUpd(i);
cd.setPendingClaimDetails(i, (dateUpd.add(cd.maxVotingTime())).sub(now), false);
}
}
}
/**
* @dev Resume the voting phase of all Claims paused due to an emergency pause.
*/
function startAllPendingClaimsVoting() public onlyInternal {
uint firstIndx = cd.getFirstClaimIndexToStartVotingAfterEP();
uint i;
uint lengthOfClaimVotingPause = cd.getLengthOfClaimVotingPause();
for (i = firstIndx; i < lengthOfClaimVotingPause; i++) {
uint pendingTime;
uint claimID;
(claimID, pendingTime, ) = cd.getPendingClaimDetailsByIndex(i);
uint pTime = (now.sub(cd.maxVotingTime())).add(pendingTime);
cd.setClaimdateUpd(claimID, pTime);
cd.setPendingClaimVoteStatus(i, true);
uint coverid;
(, coverid) = cd.getClaimCoverId(claimID);
address qadd = qd.getCoverMemberAddress(coverid);
tf.extendCNEPOff(qadd, coverid, pendingTime.add(cd.claimDepositTime()));
p1.closeClaimsOraclise(claimID, uint64(pTime));
}
cd.setFirstClaimIndexToStartVotingAfterEP(i);
}
/**
* @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 curr = qd.getCurrencyOfCover(coverId);
uint tokenx1e18 = m1.calculateTokenPrice(curr);
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));
}
uint time = now;
cd.setClaimdateUpd(claimId, time);
if (stat >= 2 && stat <= 5) {
p1.closeClaimsOraclise(claimId, cd.maxVotingTime());
}
if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) <= now) && (state12Count < 60)) {
p1.closeClaimsOraclise(claimId, cd.payoutRetryTime());
} else if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) > now) && (state12Count < 60)) {
uint64 timeLeft = uint64((dateUpd.add(cd.payoutRetryTime())).sub(now));
p1.closeClaimsOraclise(claimId, timeLeft);
}
}
/**
* @dev Submits a claim for a given cover note.
* Set deposits flag against cover.
*/
function _addClaim(uint coverId, uint time, address add) internal {
tf.depositCN(coverId);
uint len = cd.actualClaimLength();
cd.addClaim(len, coverId, add, now);
cd.callClaimEvent(coverId, add, len, time);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted));
bytes4 curr = qd.getCurrencyOfCover(coverId);
uint sumAssured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).add(sumAssured));
p2.internalLiquiditySwap(curr);
p1.closeClaimsOraclise(len, cd.maxVotingTime());
}
}
// File: nexusmutual-contracts/contracts/ClaimsReward.sol
/* 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.7;
contract ClaimsReward is Iupgradable {
using SafeMath for uint;
NXMToken internal tk;
TokenController internal tc;
TokenFunctions internal tf;
TokenData internal td;
QuotationData internal qd;
Claims internal c1;
ClaimsData internal cd;
Pool1 internal p1;
Pool2 internal p2;
PoolData internal pd;
Governance internal gv;
IPooledStaking internal pooledStaking;
uint private constant DECIMAL1E18 = uint(10) ** 18;
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"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
p1 = Pool1(ms.getLatestAddress("P1"));
p2 = Pool2(ms.getLatestAddress("P2"));
pd = PoolData(ms.getLatestAddress("PD"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
/// @dev Decides the next course of action for a given claim.
function changeClaimStatus(uint claimid) public checkPause onlyInternal {
uint coverid;
(, coverid) = cd.getClaimCoverId(claimid);
uint status;
(, 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"
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
address payable coverHolder = qd.getCoverMemberAddress(coverid);
bytes4 coverCurrency = qd.getCurrencyOfCover(coverid);
bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, coverHolder, coverCurrency);
if (success) {
tf.burnStakedTokens(coverid, coverCurrency, sumAssured);
c1.setClaimStatus(claimid, 14);
}
}
c1.changePendingClaimStart();
}
/// @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 sumAssured, uint status) internal {
uint premiumNXM = qd.getCoverPremiumNXM(coverid);
bytes4 curr = qd.getCurrencyOfCover(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);
}
if (status == 6 || status == 9 || status == 11) {
cd.changeFinalVerdict(claimid, -1);
td.setDepositCN(coverid, false); // Unset flag
tf.burnDepositCN(coverid); // burn Deposited CN
pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).sub(sumAssured));
p2.internalLiquiditySwap(curr);
} else if (status == 7 || status == 8 || status == 10) {
cd.changeFinalVerdict(claimid, 1);
td.setDepositCN(coverid, false); // Unset flag
tf.unlockCN(coverid);
bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, qd.getCoverMemberAddress(coverid), curr);
if (success) {
tf.burnStakedTokens(coverid, curr, sumAssured);
}
}
}
/// @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, sumAssured, 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, sumAssured, 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
}
}
// File: nexusmutual-contracts/contracts/MemberRoles.sol
/* 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.7;
contract MemberRoles is IMemberRoles, Governed, Iupgradable {
TokenController public dAppToken;
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 switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);
MemberRoleDetails[] internal memberRoleData;
bool internal constructorCheck;
uint public maxABCount;
bool public launched;
uint public launchedOn;
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());
dAppToken = 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]));
dAppToken.addToWhitelist(userArray[i]);
_updateRole(userArray[i], uint(Role.Member), true);
dAppToken.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");
dAppToken.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();
dAppToken.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 Called by existed member if wish to Withdraw membership.
*/
function withdrawMembership() public {
require(!ms.isPause() && ms.isMember(msg.sender));
require(dAppToken.totalLockedBalance(msg.sender, now) == 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).
require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens");
gv.removeDelegation(msg.sender);
dAppToken.burnFrom(msg.sender, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
dAppToken.removeFromWhitelist(msg.sender); // need clarification on whitelist
}
/**
* @dev Called by existed member if wish to switch membership to other address.
* @param _add address of user to forward membership.
*/
function switchMembership(address _add) external {
require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add));
require(dAppToken.totalLockedBalance(msg.sender, now) == 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).
require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens");
gv.removeDelegation(msg.sender);
dAppToken.addToWhitelist(_add);
_updateRole(_add, uint(Role.Member), true);
tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
dAppToken.removeFromWhitelist(msg.sender);
emit switchedMembership(msg.sender, _add, now);
}
/// @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;
}
}
// File: nexusmutual-contracts/contracts/ProposalCategory.sol
/* 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.7;
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 Restricts calls to deprecated functions
*/
modifier deprecated() {
revert("Function deprecated");
_;
}
/**
* @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
deprecated
{
}
/**
* @dev Initiates Default settings for Proposal Category contract (Adding default categories)
*/
function proposalCategoryInitiate() external deprecated { //solhint-disable-line
}
/**
* @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("upgradeContract(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
deprecated
{
}
/**
* @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;
}
}
// File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IGovernance.sol
/* 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.7;
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 Initiates add solution
/// @param _solutionHash Solution hash having required data against adding solution
function addSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Opens proposal for voting
function openProposalForVoting(uint _proposalId) 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 pauseProposal(uint _proposalId) public;
function resumeProposal(uint _proposalId) public;
function allowedToCatgorize() public view returns(uint roleId);
}
// File: nexusmutual-contracts/contracts/Governance.sol
// /* 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.7;
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 Initiates add solution
* To implement the governance interface
*/
function addSolution(uint, string calldata, bytes calldata) external {
}
/**
* @dev Opens proposal for voting
* To implement the governance interface
*/
function openProposalForVoting(uint) 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
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 Pauses a proposal
* To implement govblocks interface
*/
function pauseProposal(uint) public {
}
/**
* @dev Resumes a proposal
* To implement govblocks interface
*/
function resumeProposal(uint) public {
}
/**
* @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);
}
(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));
}
}
} | Gets Currency asset token address./ | function changeCurrencyAssetAddress(bytes4 curr, address currAdd) external {
require(ms.checkIsAuthToGoverned(msg.sender));
allCurrencyAssets[curr].currAddress = currAdd;
}
| 7,286,819 |
./full_match/1/0xD0561AEF1D5cd30a1779f01B41B3436027177d9A/sources/src/utils/TransferHelperUtils.sol | Sends ETH to a recipient, making conservative estimates to not run out of gas recipient The address to send ETH to value The amount of ETH to send | function safeSendETHLowLimit(address recipient, uint256 value) internal returns (bool success) {
}
| 3,219,408 |
pragma solidity ^0.4.11;
/**
* Copyright 2017 Veterapreneur
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
*/
/**
* 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;
}
}
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) onlyOwner {
owner = _newOwner;
}
}
contract token {
function balanceOf(address owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function burn(uint256 value) returns(bool success);
}
contract VeteranCoinSale is owned {
using SafeMath for uint256;
uint public tokenSold;
uint public startDate;
uint public deadline;
uint public weekTwo;
uint public weekThree;
uint public weekFour;
// how many token units a buyer gets per wei
uint public rate;
bool crowdSaleOpen;
bool burned;
token tokenReward;
event GoalReached(address _beneficiary);
event CrowdSaleClosed();
event OpenCrowdSale();
event BurnedExcessTokens(address _beneficiary, uint _amountBurned);
event Refunded(address _beneficiary, uint _depositedValue);
event FundTransfer(address _backer, uint _amount, bool _isContribution);
event TokenPurchase(address _backer, uint _amount, uint _tokenAmt);
event TokenClaim(address _backer, uint _tokenAmt);
event BonusRateChange(uint _rate);
/* data structure to hold information about campaign contributors */
// how many token units a buyer gets per wei
mapping(bytes32 => uint) bonusSchedule;
mapping(address => uint256) balances;
mapping(address => uint256) beneficiaryTokens;
/* at initialization, setup the owner */
function VeteranCoinSale(address _fundManager, uint _week1BonusRate, uint _week2BonusRate,
uint _week3BonusRate, uint _week4BonusRate, token addressOfTokenUsedAsReward ) {
if(_fundManager != 0){
owner = _fundManager;
}
require(_week1BonusRate > 0);
require(_week2BonusRate > 0);
require(_week3BonusRate > 0);
require(_week4BonusRate > 0);
bonusSchedule["week1"] = _week1BonusRate;
bonusSchedule["week2"] = _week2BonusRate;
bonusSchedule["week3"] = _week3BonusRate;
bonusSchedule["week4"] = _week4BonusRate;
require( bonusSchedule["week1"] > bonusSchedule["week2"]);
require( bonusSchedule["week2"] > bonusSchedule["week3"]);
require( bonusSchedule["week3"] > bonusSchedule["week4"]);
tokenReward = token(addressOfTokenUsedAsReward);
tokenSold = 0;
startDate = now;
weekTwo = startDate + 1 minutes;
weekThree = startDate + 2 minutes;
weekFour = startDate + 3 minutes;
deadline = startDate + 4 minutes;
//sanity checks
require(startDate < deadline);
require(weekTwo < weekThree);
require(weekThree < weekFour);
crowdSaleOpen = false;
burned = false;
// set rate according to bonus schedule for week 1
rate = bonusSchedule["week1"];
}
modifier afterDeadline() { if (now >= deadline) _; }
modifier releaseTheHounds(){ if (now >= startDate) _;}
modifier saleOpen(){ if (crowdSaleOpen) _;}
modifier allBurned(){if (burned) _;}
modifier notBurned() {if (!burned) _;}
/**
* @dev tokens can be claimed() after the sale and only after the burn
*/
function claimToken() public afterDeadline allBurned {
uint tokens = beneficiaryTokens[msg.sender];
if(tokens > 0){
beneficiaryTokens[msg.sender] = 0;
tokenReward.transfer(msg.sender, tokens);
TokenClaim(msg.sender, tokens);
}
}
//todo looks like modifiers don't work on payable, whoa!!
/**
* @dev buy tokens here, claim tokens after sale ends!
*/
function buyTokens() releaseTheHounds payable saleOpen {
require (msg.sender != 0x0);
uint weiAmount = msg.value;
balances[msg.sender] = balances[msg.sender].add(weiAmount);
uint256 tokens = weiAmount.mul(rate);
FundTransfer(msg.sender, weiAmount, true);
TokenPurchase(msg.sender, weiAmount, tokens);
beneficiaryTokens[msg.sender] = beneficiaryTokens[msg.sender].add(tokens);
tokenSold = tokenSold.add(tokens);
checkFundingGoalReached();
adjustBonusPrice();
}
/**
*
* @dev balances of wei sent to this contract
* @param _beneficiary number of tokens prior to claim
*
*/
function tokenBalanceOf(address _beneficiary) public constant returns (uint256 balance){
return beneficiaryTokens[_beneficiary];
}
/**
*
* @dev balances of wei sent this contract currently holds
* @param _beneficiary how much wei this address sent to contract
*/
function balanceOf(address _beneficiary) public constant returns (uint256 balance){
return balances[_beneficiary];
}
/**
* @dev tokens must be claimed() first, then approved() in coin contract to owner address by "token holder" prior to refund
* @param _beneficiary The investor getting the refund
* @param _tokens number of be transferred.
*/
function refund(address _beneficiary, uint _tokens) public onlyOwner afterDeadline {
require(beneficiaryTokens[_beneficiary] == 0);
require(tokenReward.transferFrom(_beneficiary, owner, _tokens));
uint256 depositedValue = balances[_beneficiary];
balances[_beneficiary] = 0;
tokenSold = tokenSold.sub(_tokens);
_beneficiary.transfer(depositedValue);
Refunded(_beneficiary, depositedValue);
}
/**
* @dev make two checks before writing new rate
*/
function adjustBonusPrice() internal {
if (now >= weekTwo && now < weekThree){
if(rate != bonusSchedule["week2"]){
rate = bonusSchedule["week2"];
BonusRateChange(rate);
}
}
if (now >= weekThree && now < weekFour){
if(rate != bonusSchedule["week3"]){
rate = bonusSchedule["week3"];
BonusRateChange(rate);
}
}
if(now >= weekFour){
if(rate != bonusSchedule["week4"]){
rate = bonusSchedule["week4"];
BonusRateChange(rate);
}
}
}
/**
* @dev when token's sold = token balance, it's over
*
*/
function checkFundingGoalReached() internal {
if(tokenSold == tokenReward.balanceOf(this)){
crowdSaleOpen = false;
GoalReached(owner);
}
}
/**
* @dev auto burn the tokens
*
*/
function autoBurn() public onlyOwner notBurned {
crowdSaleOpen = false;
uint256 burnPile = tokenReward.balanceOf(this).sub(tokenSold);
if(burnPile > 0){
tokenReward.burn(burnPile);
BurnedExcessTokens(owner, burnPile);
}
burned = true;
}
function closeSale() public onlyOwner{
crowdSaleOpen = false;
CrowdSaleClosed();
}
function openSale() public onlyOwner{
crowdSaleOpen = true;
OpenCrowdSale();
}
/**
* @dev owner can safely withdraw contract value
*/
function safeWithdrawal() public onlyOwner{
uint256 balance = this.balance;
if(owner.send(balance)){
FundTransfer(owner,balance,false);
}
}
// @return true if crowdsale is still going on
function saleInProgress() public constant returns (bool) {
return crowdSaleOpen;
}
} | auto burn the tokens/ | function autoBurn() public onlyOwner notBurned {
crowdSaleOpen = false;
uint256 burnPile = tokenReward.balanceOf(this).sub(tokenSold);
if(burnPile > 0){
tokenReward.burn(burnPile);
BurnedExcessTokens(owner, burnPile);
}
burned = true;
}
| 14,073,921 |
pragma solidity ^0.4.24;
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface ERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface ERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string);
}
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
/**
* @dev Implementation of standard for detect smart contract interfaces.
*/
contract SupportsInterface {
/**
* @dev Mapping of supported intefraces.
* @notice You must not set element 0xffffffff to true.
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev Contract constructor.
*/
constructor()
public
{
supportedInterfaces[0x01ffc9a7] = true; // ERC165
}
/**
* @dev Function to check which interfaces are suported by this contract.
* @param _interfaceID Id of the interface.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceID];
}
}
/**
* @dev Utility library of inline functions on addresses.
*/
library AddressUtils {
/**
* @dev Returns whether the target address is a contract.
* @param _addr Address to check.
*/
function isContract(
address _addr
)
internal
view
returns (bool)
{
uint256 size;
/**
* XXX Currently there is no better way to check if there is a contract in an address than to
* check the size of the code at that address.
* See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works.
* TODO: Check this again before the Serenity release, because all addresses will be
* contracts then.
*/
assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
/**
* @dev Implementation of ERC-721 non-fungible token standard specifically for WeTrust Spring.
*/
contract NFToken is ERC721, SupportsInterface, ERC721Metadata, ERC721Enumerable {
using AddressUtils for address;
///////////////////////////
// Constants
//////////////////////////
/**
* @dev Magic value of a smart contract that can recieve NFT.
* Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")).
*/
bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
//////////////////////////
// Events
//////////////////////////
/**
* @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are
* created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any
* number of NFTs may be created and assigned without emitting Transfer. At the time of any
* transfer, the approved address for that NFT (if any) is reset to none.
* @param _from Sender of NFT (if address is zero address it indicates token creation).
* @param _to Receiver of NFT (if address is zero address it indicates token destruction).
* @param _tokenId The NFT that got transfered.
*/
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/**
* @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero
* address indicates there is no approved address. When a Transfer event emits, this also
* indicates that the approved address for that NFT (if any) is reset to none.
* @param _owner Owner of NFT.
* @param _approved Address that we are approving.
* @param _tokenId NFT which we are approving.
*/
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/**
* @dev This emits when an operator is enabled or disabled for an owner. The operator can manage
* all NFTs of the owner.
* @param _owner Owner of NFT.
* @param _operator Address to which we are setting operator rights.
* @param _approved Status of operator rights(true if operator rights are given and false if
* revoked).
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
////////////////////////////////
// Modifiers
///////////////////////////////
/**
* @dev Guarantees that the msg.sender is an owner or operator of the given NFT.
* @param _tokenId ID of the NFT to validate.
*/
modifier canOperate(uint256 _tokenId) {
address tokenOwner = nft[_tokenId].owner;
require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], "Sender is not an authorized operator of this token");
_;
}
/**
* @dev Guarantees that the msg.sender is allowed to transfer NFT.
* @param _tokenId ID of the NFT to transfer.
*/
modifier canTransfer(uint256 _tokenId) {
address tokenOwner = nft[_tokenId].owner;
require(
tokenOwner == msg.sender ||
getApproved(_tokenId) == msg.sender || ownerToOperators[tokenOwner][msg.sender],
"Sender does not have permission to transfer this Token");
_;
}
/**
* @dev Check to make sure the address is not zero address
* @param toTest The Address to make sure it's not zero address
*/
modifier onlyNonZeroAddress(address toTest) {
require(toTest != address(0), "Address must be non zero address");
_;
}
/**
* @dev Guarantees that no owner exists for the nft
* @param nftId NFT to test
*/
modifier noOwnerExists(uint256 nftId) {
require(nft[nftId].owner == address(0), "Owner must not exist for this token");
_;
}
/**
* @dev Guarantees that an owner exists for the nft
* @param nftId NFT to test
*/
modifier ownerExists(uint256 nftId) {
require(nft[nftId].owner != address(0), "Owner must exist for this token");
_;
}
///////////////////////////
// Storage Variable
//////////////////////////
/**
* @dev name of the NFT
*/
string nftName = "WeTrust Nifty";
/**
* @dev NFT symbol
*/
string nftSymbol = "SPRN";
/**
* @dev hostname to be used as base for tokenURI
*/
string public hostname = "https://spring.wetrust.io/shiba/";
/**
* @dev A mapping from NFT ID to the address that owns it.
*/
mapping (uint256 => NFT) public nft;
/**
* @dev List of NFTs
*/
uint256[] nftList;
/**
* @dev Mapping from owner address to count of his tokens.
*/
mapping (address => uint256[]) internal ownerToTokenList;
/**
* @dev Mapping from owner address to mapping of operator addresses.
*/
mapping (address => mapping (address => bool)) internal ownerToOperators;
struct NFT {
address owner;
address approval;
bytes32 traits;
uint16 edition;
bytes4 nftType;
bytes32 recipientId;
uint256 createdAt;
}
////////////////////////////////
// Public Functions
///////////////////////////////
/**
* @dev Contract constructor.
*/
constructor() public {
supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable
supportedInterfaces[0x5b5e139f] = true; // ERC721MetaData
supportedInterfaces[0x80ac58cd] = true; // ERC721
}
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
*/
function balanceOf(address _owner) onlyNonZeroAddress(_owner) public view returns (uint256) {
return ownerToTokenList[_owner].length;
}
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered
* invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
*/
function ownerOf(uint256 _tokenId) ownerExists(_tokenId) external view returns (address _owner) {
return nft[_tokenId].owner;
}
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received`
* on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external {
_safeTransferFrom(_from, _to, _tokenId, _data);
}
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to ""
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external {
_safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT.
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they maybe be permanently lost.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(address _from, address _to, uint256 _tokenId)
onlyNonZeroAddress(_to)
canTransfer(_tokenId)
ownerExists(_tokenId)
external
{
address tokenOwner = nft[_tokenId].owner;
require(tokenOwner == _from, "from address must be owner of tokenId");
_transfer(_to, _tokenId);
}
/**
* @dev Set or reaffirm the approved address for an NFT.
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved Address to be approved for the given NFT ID.
* @param _tokenId ID of the token to be approved.
*/
function approve(address _approved, uint256 _tokenId)
canOperate(_tokenId)
ownerExists(_tokenId)
external
{
address tokenOwner = nft[_tokenId].owner;
require(_approved != tokenOwner, "approved address cannot be owner of the token");
nft[_tokenId].approval = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
/**
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @notice This works even if sender doesn't own any tokens at the time.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(address _operator, bool _approved)
onlyNonZeroAddress(_operator)
external
{
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Get the approved address for a single NFT.
* @notice Throws if `_tokenId` is not a valid NFT.
* @param _tokenId ID of the NFT to query the approval of.
*/
function getApproved(uint256 _tokenId)
ownerExists(_tokenId)
public view returns (address)
{
return nft[_tokenId].approval;
}
/**
* @dev Checks if `_operator` is an approved operator for `_owner`.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
*/
function isApprovedForAll(address _owner, address _operator)
onlyNonZeroAddress(_owner)
onlyNonZeroAddress(_operator)
external view returns (bool)
{
return ownerToOperators[_owner][_operator];
}
/**
* @dev return token list of owned by the owner
* @param owner The address that owns the NFTs.
*/
function getOwnedTokenList(address owner) view public returns(uint256[] tokenList) {
return ownerToTokenList[owner];
}
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name) {
return nftName;
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string _symbol) {
return nftSymbol;
}
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string) {
return appendUintToString(hostname, _tokenId);
}
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256) {
return nftList.length;
}
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256) {
require(_index < nftList.length, "index out of range");
return nftList[_index];
}
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
require(_index < balanceOf(_owner), "index out of range");
return ownerToTokenList[_owner][_index];
}
/////////////////////////////
// Private Functions
////////////////////////////
/**
* @dev append uint to the end of string
* @param inStr input string
* @param v uint value v
* credit goes to : https://ethereum.stackexchange.com/questions/10811/solidity-concatenate-uint-into-a-string
*/
function appendUintToString(string inStr, uint v) pure internal returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
/**
* @dev Actually preforms the transfer.
* @notice Does NO checks.
* @param _to Address of a new owner.
* @param _tokenId The NFT that is being transferred.
*/
function _transfer(address _to, uint256 _tokenId) private {
address from = nft[_tokenId].owner;
clearApproval(_tokenId);
removeNFToken(from, _tokenId);
addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data)
onlyNonZeroAddress(_to)
canTransfer(_tokenId)
ownerExists(_tokenId)
internal
{
address tokenOwner = nft[_tokenId].owner;
require(tokenOwner == _from, "from address must be owner of tokenId");
_transfer(_to, _tokenId);
if (_to.isContract()) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED, "reciever contract did not return the correct return value");
}
}
/**
* @dev Clears the current approval of a given NFT ID.
* @param _tokenId ID of the NFT to be transferred.
*/
function clearApproval(uint256 _tokenId) private {
if(nft[_tokenId].approval != address(0))
{
delete nft[_tokenId].approval;
}
}
/**
* @dev Removes a NFT from owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _from Address from wich we want to remove the NFT.
* @param _tokenId Which NFT we want to remove.
*/
function removeNFToken(address _from, uint256 _tokenId) internal {
require(nft[_tokenId].owner == _from, "from address must be owner of tokenId");
uint256[] storage tokenList = ownerToTokenList[_from];
assert(tokenList.length > 0);
for (uint256 i = 0; i < tokenList.length; i++) {
if (tokenList[i] == _tokenId) {
tokenList[i] = tokenList[tokenList.length - 1];
delete tokenList[tokenList.length - 1];
tokenList.length--;
break;
}
}
delete nft[_tokenId].owner;
}
/**
* @dev Assignes a new NFT to owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _to Address to wich we want to add the NFT.
* @param _tokenId Which NFT we want to add.
*/
function addNFToken(address _to, uint256 _tokenId)
noOwnerExists(_tokenId)
internal
{
nft[_tokenId].owner = _to;
ownerToTokenList[_to].push(_tokenId);
}
}
//@dev Implemention of NFT for WeTrust Spring
contract SpringNFT is NFToken{
//////////////////////////////
// Events
/////////////////////////////
event RecipientUpdate(bytes32 indexed recipientId, bytes32 updateId);
//////////////////////////////
// Modifiers
/////////////////////////////
/**
* @dev Guarrentees that recipient Exists
* @param id receipientId to check
*/
modifier recipientExists(bytes32 id) {
require(recipients[id].exists, "Recipient Must exist");
_;
}
/**
* @dev Guarrentees that recipient does not Exists
* @param id receipientId to check
*/
modifier recipientDoesNotExists(bytes32 id) {
require(!recipients[id].exists, "Recipient Must not exists");
_;
}
/**
* @dev Guarrentees that msg.sender is wetrust owned signer address
*/
modifier onlyByWeTrustSigner() {
require(msg.sender == wetrustSigner, "sender must be from WeTrust Signer Address");
_;
}
/**
* @dev Guarrentees that msg.sender is wetrust owned manager address
*/
modifier onlyByWeTrustManager() {
require(msg.sender == wetrustManager, "sender must be from WeTrust Manager Address");
_;
}
/**
* @dev Guarrentees that msg.sender is either wetrust recipient
* @param id receipientId to check
*/
modifier onlyByWeTrustOrRecipient(bytes32 id) {
require(msg.sender == wetrustSigner || msg.sender == recipients[id].owner, "sender must be from WeTrust or Recipient's owner address");
_;
}
/**
* @dev Guarrentees that contract is not in paused state
*/
modifier onlyWhenNotPaused() {
require(!paused, "contract is currently in paused state");
_;
}
//////////////////////////////
// Storage Variables
/////////////////////////////
/**
* @dev wetrust controlled address that is used to create new NFTs
*/
address public wetrustSigner;
/**
*@dev wetrust controlled address that is used to switch the signer address
*/
address public wetrustManager;
/**
* @dev if paused is true, suspend most of contract's functionality
*/
bool public paused;
/**
* @dev mapping of recipients from WeTrust Spring platform
*/
mapping(bytes32 => Recipient) public recipients;
/**
* @dev mapping to a list of updates made by recipients
*/
mapping(bytes32 => Update[]) public recipientUpdates;
/**
* @dev Stores the Artist signed Message who created the NFT
*/
mapping (uint256 => bytes) public nftArtistSignature;
struct Update {
bytes32 id;
uint256 createdAt;
}
struct Recipient {
string name;
string url;
address owner;
uint256 nftCount;
bool exists;
}
//////////////////////////////
// Public functions
/////////////////////////////
/**
* @dev contract constructor
*/
constructor (address signer, address manager) NFToken() public {
wetrustSigner = signer;
wetrustManager = manager;
}
/**
* @dev Create a new NFT
* @param tokenId create new NFT with this tokenId
* @param receiver the owner of the new NFT
* @param recipientId The issuer of the NFT
* @param traits NFT Traits
* @param nftType Type of the NFT
*/
function createNFT(
uint256 tokenId,
address receiver,
bytes32 recipientId,
bytes32 traits,
bytes4 nftType)
noOwnerExists(tokenId)
onlyByWeTrustSigner
onlyWhenNotPaused public
{
mint(tokenId, receiver, recipientId, traits, nftType);
}
/**
* @dev Allows anyone to redeem a token by providing a signed Message from Spring platform
* @param signedMessage A signed Message containing the NFT parameter from Spring platform
* The Signed Message must be concatenated in the following format
* - address to (the smart contract address)
* - uint256 tokenId
* - bytes4 nftType
* - bytes32 traits
* - bytes32 recipientId
* - bytes32 r of Signature
* - bytes32 s of Signature
* - uint8 v of Signature
*/
function redeemToken(bytes signedMessage) onlyWhenNotPaused public {
address to;
uint256 tokenId;
bytes4 nftType;
bytes32 traits;
bytes32 recipientId;
bytes32 r;
bytes32 s;
byte vInByte;
uint8 v;
string memory prefix = "\x19Ethereum Signed Message:\n32";
assembly {
to := mload(add(signedMessage, 32))
tokenId := mload(add(signedMessage, 64))
nftType := mload(add(signedMessage, 96)) // first 32 bytes are data padding
traits := mload(add(signedMessage, 100))
recipientId := mload(add(signedMessage, 132))
r := mload(add(signedMessage, 164))
s := mload(add(signedMessage, 196))
vInByte := mload(add(signedMessage, 228))
}
require(to == address(this), "This signed Message is not meant for this smart contract");
v = uint8(vInByte);
if (v < 27) {
v += 27;
}
require(nft[tokenId].owner == address(0), "This token has been redeemed already");
bytes32 msgHash = createRedeemMessageHash(tokenId, nftType, traits, recipientId);
bytes32 preFixedMsgHash = keccak256(
abi.encodePacked(
prefix,
msgHash
));
address signer = ecrecover(preFixedMsgHash, v, r, s);
require(signer == wetrustSigner, "WeTrust did not authorized this redeem script");
return mint(tokenId, msg.sender, recipientId, traits, nftType);
}
/**
* @dev Add a new reciepient of WeTrust Spring
* @param recipientId Unique identifier of receipient
* @param name of the Recipient
* @param url link to the recipient's website
* @param owner Address owned by the recipient
*/
function addRecipient(bytes32 recipientId, string name, string url, address owner)
onlyByWeTrustSigner
onlyWhenNotPaused
recipientDoesNotExists(recipientId)
public
{
require(bytes(name).length > 0, "name must not be empty string"); // no empty string
recipients[recipientId].name = name;
recipients[recipientId].url = url;
recipients[recipientId].owner = owner;
recipients[recipientId].exists = true;
}
/**
* @dev Add an link to the update the recipient had made
* @param recipientId The issuer of the update
* @param updateId unique id of the update
*/
function addRecipientUpdate(bytes32 recipientId, bytes32 updateId)
onlyWhenNotPaused
recipientExists(recipientId)
onlyByWeTrustOrRecipient(recipientId)
public
{
recipientUpdates[recipientId].push(Update(updateId, now));
emit RecipientUpdate(recipientId, updateId);
}
/**
* @dev Change recipient information
* @param recipientId to change
* @param name new name of the recipient
* @param url new link of the recipient
* @param owner new address owned by the recipient
*/
function updateRecipientInfo(bytes32 recipientId, string name, string url, address owner)
onlyByWeTrustSigner
onlyWhenNotPaused
recipientExists(recipientId)
public
{
require(bytes(name).length > 0, "name must not be empty string"); // no empty string
recipients[recipientId].name = name;
recipients[recipientId].url = url;
recipients[recipientId].owner = owner;
}
/**
* @dev add a artist signed message for a particular NFT
* @param nftId NFT to add the signature to
* @param artistSignature Artist Signed Message
*/
function addArtistSignature(uint256 nftId, bytes artistSignature) onlyByWeTrustSigner onlyWhenNotPaused public {
require(nftArtistSignature[nftId].length == 0, "Artist Signature already exist for this token"); // make sure no prior signature exists
nftArtistSignature[nftId] = artistSignature;
}
/**
* @dev Set whether or not the contract is paused
* @param _paused status to put the contract in
*/
function setPaused(bool _paused) onlyByWeTrustManager public {
paused = _paused;
}
/**
* @dev Transfer the WeTrust signer of NFT contract to a new address
* @param newAddress new WeTrust owned address
*/
function changeWeTrustSigner(address newAddress) onlyWhenNotPaused onlyByWeTrustManager public {
wetrustSigner = newAddress;
}
/**
* @dev Returns the number of updates recipients had made
* @param recipientId receipientId to check
*/
function getUpdateCount(bytes32 recipientId) view public returns(uint256 count) {
return recipientUpdates[recipientId].length;
}
/**
* @dev returns the message hash to be signed for redeem token
* @param tokenId id of the token to be created
* @param nftType Type of NFT to be created
* @param traits Traits of NFT to be created
* @param recipientId Issuer of the NFT
*/
function createRedeemMessageHash(
uint256 tokenId,
bytes4 nftType,
bytes32 traits,
bytes32 recipientId)
view public returns(bytes32 msgHash)
{
return keccak256(
abi.encodePacked(
address(this),
tokenId,
nftType,
traits,
recipientId
));
}
/**
* @dev Determines the edition of the NFT
* formula used to determine edition Size given the edition Number:
* f(x) = min(300x + 100, 5000)
* using equation: g(x) = 150x^2 - 50x + 1 if x <= 16
* else g(x) = 5000(x-16) - g(16)
* maxEdition = 5000
* @param nextNFTcount to determine edition for
*/
function determineEdition(uint256 nextNFTcount) pure public returns (uint16 edition) {
uint256 output;
uint256 valueWhenXisSixteen = 37601; // g(16)
if (nextNFTcount < valueWhenXisSixteen) {
output = (sqrt(2500 + (600 * (nextNFTcount - 1))) + 50) / 300;
} else {
output = ((nextNFTcount - valueWhenXisSixteen) / 5000) + 16;
}
if (output > 5000) {
output = 5000;
}
edition = uint16(output); // we don't have to worry about casting because output will always be less than or equal to 5000
}
/**
* @dev set new host name for this nft contract
* @param newHostName new host name to use
*/
function setNFTContractInfo(string newHostName, string newName, string newSymbol) onlyByWeTrustManager external {
hostname = newHostName;
nftName = newName;
nftSymbol = newSymbol;
}
//////////////////////////
// Private Functions
/////////////////////////
/**
* @dev Find the Square root of a number
* @param x input
* Credit goes to: https://ethereum.stackexchange.com/questions/2910/can-i-square-root-in-solidity
*/
function sqrt(uint x) pure internal returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
/**
* @dev Add the new NFT to the storage
* @param receiver the owner of the new NFT
* @param recipientId The issuer of the NFT
* @param traits NFT Traits
* @param nftType Type of the NFT
*/
function mint(uint256 tokenId, address receiver, bytes32 recipientId, bytes32 traits, bytes4 nftType)
recipientExists(recipientId)
internal
{
nft[tokenId].owner = receiver;
nft[tokenId].traits = traits;
nft[tokenId].recipientId = recipientId;
nft[tokenId].nftType = nftType;
nft[tokenId].createdAt = now;
nft[tokenId].edition = determineEdition(recipients[recipientId].nftCount + 1);
recipients[recipientId].nftCount++;
ownerToTokenList[receiver].push(tokenId);
nftList.push(tokenId);
emit Transfer(address(0), receiver, tokenId);
}
} | Actually preforms the transfer. Does NO checks. _to Address of a new owner. _tokenId The NFT that is being transferred./ | function _transfer(address _to, uint256 _tokenId) private {
address from = nft[_tokenId].owner;
clearApproval(_tokenId);
removeNFToken(from, _tokenId);
addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
| 2,559,294 |
pragma solidity ^0.5.0;
import "node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "node_modules/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
/**
* @title Nexty sealers management smart contract
*/
contract NextyGovernance {
using SafeMath for uint256;
// zero address
address constant ZERO_ADDRESS = address(0x0);
enum Status {
PENDING_ACTIVE, // Sealer deposited enough NTFs into registration contract successfully.
ACTIVE, // Sealer send request to become a sealer
// and added into activation sealer set successfully
PENDING_WITHDRAW, // Sealer send request to exit from activation sealer set successfully.
// Sealer casted out of activation sealer set
WITHDRAWN, // Sealer already withdrawn their deposit NTFs successfully.
// They can only make withdrawal after withdrawal period.
PENALIZED //Sealer marked as penalized node (update by consensus or voting result via dapp)
//and cannot become active sealer and cannot withdraw balance neither.
}
struct Account {
Status status;
// ntf amount deposited
uint256 balance;
// delegated address to seal blocks
address signer;
// withdrawable block number after leaving
uint256 unlockHeight;
}
// Consensus variables
// index = 0
// signers array
address[] public signers;
// index = 1
// signer => coinbase (beneficiary address) map
mapping(address => address) public signerCoinbase;
// End of consensus variables
// coinbase => NTF Account map
mapping(address => Account) public account;
// minimum of deposited NTF to join
uint256 public stakeRequire;
// minimum number of blocks signer has to wait from leaving block to withdraw the fund
uint256 public stakeLockHeight;
// NTF token contract, unit used to join Nexty sealers
IERC20 public token;
event Deposited(address _sealer, uint _amount);
event Joined(address _sealer, address _signer);
event Left(address _sealer, address _signer);
event Withdrawn(address _sealer, uint256 _amount);
event Banned(address _sealer);
event Unbanned(address _sealer);
/**
* Check if address is a valid destination to transfer tokens to
* - must not be zero address
* - must not be the token address
* - must not be the sender's address
*/
modifier validSigner(address _signer) {
require(signerCoinbase[_signer] == ZERO_ADDRESS, "coinbase already used");
require(_signer != ZERO_ADDRESS, "signer zero");
require(_signer != address(this), "same contract's address");
require(_signer != msg.sender, "same sender's address");
_;
}
modifier notBanned() {
require(account[msg.sender].status != Status.PENALIZED, "banned ");
_;
}
modifier joinable() {
require(account[msg.sender].status != Status.ACTIVE, "already joined ");
require(account[msg.sender].balance >= stakeRequire, "not enough ntf");
_;
}
modifier leaveable() {
require(account[msg.sender].status == Status.ACTIVE, "not joined ");
_;
}
modifier withdrawable() {
require(isWithdrawable(msg.sender), "unable to withdraw at the moment");
_;
}
/**
* contract initialize
*/
constructor(address _token, uint256 _stakeRequire, uint256 _stakeLockHeight, address[] memory _signers) public {
token = IERC20(_token);
stakeRequire = _stakeRequire;
stakeLockHeight = _stakeLockHeight;
for (uint i = 0; i < _signers.length; i++) {
signers.push(_signers[i]);
signerCoinbase[_signers[i]] = _signers[i];
account[_signers[i]].signer = _signers[i];
account[_signers[i]].status = Status.ACTIVE;
}
}
// Get ban status of a sealer's address
function isBanned(address _address) public view returns(bool) {
return (account[_address].status == Status.PENALIZED);
}
////////////////////////////////
function addSigner(address _signer) internal {
signers.push(_signer);
}
function removeSigner(address _signer) internal {
for (uint i = 0; i < signers.length; i++) {
if (_signer == signers[i]) {
signers[i] = signers[signers.length - 1];
signers.length--;
return;
}
}
}
/**
* Transfer the NTF from token holder to registration contract.
* Sealer might have to approve contract to transfer an amount of NTF before calling this function.
* @param _amount NTF Tokens to deposit
*/
function deposit(uint256 _amount) public returns (bool) {
token.transferFrom(msg.sender, address(this), _amount);
account[msg.sender].balance = (account[msg.sender].balance).add(_amount);
emit Deposited(msg.sender, _amount);
return true;
}
/**
* To allow deposited NTF participate joining in as sealer.
* Participate already must deposit enough NTF via Deposit function.
* It takes signer as parameter.
* @param _signer Destination address
*/
function join(address _signer) public notBanned joinable validSigner(_signer) returns (bool) {
account[msg.sender].signer = _signer;
account[msg.sender].status = Status.ACTIVE;
signerCoinbase[_signer] = msg.sender;
addSigner(_signer);
emit Joined(msg.sender, _signer);
return true;
}
/**
* Request to exit out of activation sealer set
*/
function leave() public notBanned leaveable returns (bool) {
address _signer = account[msg.sender].signer;
account[msg.sender].signer = ZERO_ADDRESS;
account[msg.sender].status = Status.PENDING_WITHDRAW;
account[msg.sender].unlockHeight = stakeLockHeight.add(block.number);
delete signerCoinbase[_signer];
removeSigner(_signer);
emit Left(msg.sender, _signer);
return true;
}
/**
* To withdraw sealer’s NTF balance when they already exited and after withdrawal period.
*/
function withdraw() public notBanned withdrawable returns (bool) {
uint256 amount = account[msg.sender].balance;
account[msg.sender].balance = 0;
account[msg.sender].status = Status.WITHDRAWN;
token.transfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
return true;
}
function getStatusCode(Status _status) private pure returns(uint256){
if (_status == Status.PENDING_ACTIVE) return 0;
if (_status == Status.ACTIVE) return 1;
if (_status == Status.PENDING_WITHDRAW) return 2;
if (_status == Status.WITHDRAWN) return 3;
return 127;
}
function getStatus(address _address) public view returns(uint256) {
return getStatusCode(account[_address].status);
}
function getBalance(address _address) public view returns(uint256) {
return account[_address].balance;
}
function getCoinbase(address _address) public view returns(address) {
return account[_address].signer;
}
function getUnlockHeight(address _address) public view returns(uint256) {
return account[_address].unlockHeight;
}
function isWithdrawable(address _address) public view returns(bool) {
return
(account[_address].status != Status.ACTIVE) &&
(account[_address].status != Status.PENALIZED) &&
(account[_address].unlockHeight < block.number);
}
} | To allow deposited NTF participate joining in as sealer. Participate already must deposit enough NTF via Deposit function. It takes signer as parameter. _signer Destination address/ | function join(address _signer) public notBanned joinable validSigner(_signer) returns (bool) {
account[msg.sender].signer = _signer;
account[msg.sender].status = Status.ACTIVE;
signerCoinbase[_signer] = msg.sender;
addSigner(_signer);
emit Joined(msg.sender, _signer);
return true;
}
| 896,367 |
//Address: 0xc99f359f73626e475ee86caab459a4b34ae93fea
//Contract name: DungeonTokenAuction
//Balance: 0 Ether
//Verification Date: 3/10/2018
//Transacion Count: 9
// CODE STARTS HERE
pragma solidity ^0.4.19;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title JointOwnable
* @dev Extension for the Ownable contract, where the owner can assign at most 2 other addresses
* to manage some functions of the contract, using the eitherOwner modifier.
* Note that onlyOwner modifier would still be accessible only for the original owner.
*/
contract JointOwnable is Ownable {
event AnotherOwnerAssigned(address indexed anotherOwner);
address public anotherOwner1;
address public anotherOwner2;
/**
* @dev Throws if called by any account other than the owner or anotherOwner.
*/
modifier eitherOwner() {
require(msg.sender == owner || msg.sender == anotherOwner1 || msg.sender == anotherOwner2);
_;
}
/**
* @dev Allows the current owner to assign another owner.
* @param _anotherOwner The address to another owner.
*/
function assignAnotherOwner1(address _anotherOwner) onlyOwner public {
require(_anotherOwner != 0);
AnotherOwnerAssigned(_anotherOwner);
anotherOwner1 = _anotherOwner;
}
/**
* @dev Allows the current owner to assign another owner.
* @param _anotherOwner The address to another owner.
*/
function assignAnotherOwner2(address _anotherOwner) onlyOwner public {
require(_anotherOwner != 0);
AnotherOwnerAssigned(_anotherOwner);
anotherOwner2 = _anotherOwner;
}
}
/**
* @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 Interface for contracts conforming to ERC-721: Non-Fungible Tokens.
*/
contract ERC721 {
// Events
event Transfer(address indexed from, address indexed to, uint indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint indexed tokenId);
// ERC20 compatible functions.
// function name() public constant returns (string);
// function symbol() public constant returns (string);
function totalSupply() public view returns (uint);
function balanceOf(address _owner) public view returns (uint);
// Functions that define ownership.
function ownerOf(uint _tokenId) external view returns (address);
function transfer(address _to, uint _tokenId) external;
// Approval related functions, mainly used in auction contracts.
function approve(address _to, uint _tokenId) external;
function approvedFor(uint _tokenId) external view returns (address);
function transferFrom(address _from, address _to, uint _tokenId) external;
/**
* @dev Each non-fungible token owner can own more than one token at one time.
* Because each token is referenced by its unique ID, however,
* it can get difficult to keep track of the individual tokens that a user may own.
* To do this, the contract keeps a record of the IDs of each token that each user owns.
*/
mapping(address => uint[]) public ownerTokens;
}
/**
* @title The ERC-721 compliance token contract.
*/
contract ERC721Token is ERC721, Pausable {
/* ======== STATE VARIABLES ======== */
/**
* @dev A mapping from token IDs to the address that owns them.
*/
mapping(uint => address) tokenIdToOwner;
/**
* @dev A mapping from token ids to an address that has been approved to call
* transferFrom(). Each token can only have one approved address for transfer
* at any time. A zero value means no approval is outstanding.
*/
mapping (uint => address) tokenIdToApproved;
/**
* @dev A mapping from token ID to index of the ownerTokens' tokens list.
*/
mapping(uint => uint) tokenIdToOwnerTokensIndex;
/* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */
/**
* @dev Returns the number of tokens owned by a specific address.
* @param _owner The owner address to check.
*/
function balanceOf(address _owner) public view returns (uint) {
return ownerTokens[_owner].length;
}
/**
* @dev Returns the address currently assigned ownership of a given token.
*/
function ownerOf(uint _tokenId) external view returns (address) {
require(tokenIdToOwner[_tokenId] != address(0));
return tokenIdToOwner[_tokenId];
}
/**
* @dev Returns the approved address of a given token.
*/
function approvedFor(uint _tokenId) external view returns (address) {
return tokenIdToApproved[_tokenId];
}
/**
* @dev Get an array of IDs of each token that an user owns.
*/
function getOwnerTokens(address _owner) external view returns(uint[]) {
return ownerTokens[_owner];
}
/**
* @dev External function to transfers a token to another address.
* @param _to The address of the recipient, can be a user or contract.
* @param _tokenId The ID of the token to transfer.
*/
function transfer(address _to, uint _tokenId) whenNotPaused external {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
// You can only send your own token.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/**
* @dev Grant another address the right to transfer a specific Kitty via
* transferFrom(). This is the preferred flow for transfering NFTs to contracts.
* @param _to The address to be granted transfer approval. Pass address(0) to
* clear all approvals.
* @param _tokenId The ID of the Kitty that can be transferred if this call succeeds.
*/
function approve(address _to, uint _tokenId) whenNotPaused external {
// 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);
}
/**
* @dev Transfer a Kitty owned by another address, for which the calling address
* has previously been granted transfer approval by the owner.
* @param _from The address that owns the Kitty to be transfered.
* @param _to The address that should take ownership of the Kitty. Can be any address,
* including the caller.
* @param _tokenId The ID of the Kitty to be transferred.
*/
function transferFrom(address _from, address _to, uint _tokenId) whenNotPaused external {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Check for approval and valid ownership
require(tokenIdToApproved[_tokenId] == msg.sender);
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/* ======== INTERNAL/PRIVATE FUNCTIONS ======== */
/**
* @dev Assigns ownership of a specific token to an address.
*/
function _transfer(address _from, address _to, uint _tokenId) internal {
// Step 1: Remove token from _form address.
// When creating new token, _from is 0x0.
if (_from != address(0)) {
uint[] storage fromTokens = ownerTokens[_from];
uint tokenIndex = tokenIdToOwnerTokensIndex[_tokenId];
// Put the last token to the transferred token index and update its index in ownerTokensIndexes.
uint lastTokenId = fromTokens[fromTokens.length - 1];
// Do nothing if the transferring token is the last item.
if (_tokenId != lastTokenId) {
fromTokens[tokenIndex] = lastTokenId;
tokenIdToOwnerTokensIndex[lastTokenId] = tokenIndex;
}
fromTokens.length--;
}
// Step 2: Add token to _to address.
// Transfer ownership.
tokenIdToOwner[_tokenId] = _to;
// Add the _tokenId to ownerTokens[_to] and remember the index in ownerTokensIndexes.
tokenIdToOwnerTokensIndex[_tokenId] = ownerTokens[_to].length;
ownerTokens[_to].push(_tokenId);
// Emit the Transfer event.
Transfer(_from, _to, _tokenId);
}
/**
* @dev Marks an address as being approved for transferFrom(), overwriting any previous
* approval. Setting _approved to address(0) clears all transfer approval.
*/
function _approve(uint _tokenId, address _approved) internal {
tokenIdToApproved[_tokenId] = _approved;
}
/* ======== MODIFIERS ======== */
/**
* @dev Throws if _dungeonId is not created yet.
*/
modifier tokenExists(uint _tokenId) {
require(_tokenId < totalSupply());
_;
}
/**
* @dev Checks if a given address is the current owner of a particular token.
* @param _claimant The address we are validating against.
* @param _tokenId Token ID
*/
function _owns(address _claimant, uint _tokenId) internal view returns (bool) {
return tokenIdToOwner[_tokenId] == _claimant;
}
}
contract EDStructs {
/**
* @dev The main Dungeon struct. Every dungeon in the game is represented by this structure.
* A dungeon is consists of an unlimited number of floors for your heroes to challenge,
* the power level of a dungeon is encoded in the floorGenes. Some dungeons are in fact more "challenging" than others,
* the secret formula for that is left for user to find out.
*
* Each dungeon also has a "training area", heroes can perform trainings and upgrade their stat,
* and some dungeons are more effective in the training, which is also a secret formula!
*
* When player challenge or do training in a dungeon, the fee will be collected as the dungeon rewards,
* which will be rewarded to the player who successfully challenged the current floor.
*
* Each dungeon fits in fits into three 256-bit words.
*/
struct Dungeon {
// Each dungeon has an ID which is the index in the storage array.
// The timestamp of the block when this dungeon is created.
uint32 creationTime;
// The status of the dungeon, each dungeon can have 5 status, namely:
// 0: Active | 1: Transport Only | 2: Challenge Only | 3: Train Only | 4: InActive
uint8 status;
// The dungeon's difficulty, the higher the difficulty,
// normally, the "rarer" the seedGenes, the higher the diffculty,
// and the higher the contribution fee it is to challenge, train, and transport to the dungeon,
// the formula for the contribution fee is in DungeonChallenge and DungeonTraining contracts.
// A dungeon's difficulty never change.
uint8 difficulty;
// The dungeon's capacity, maximum number of players allowed to stay on this dungeon.
// The capacity of the newbie dungeon (Holyland) is set at 0 (which is infinity).
// Using 16-bit unsigned integers can have a maximum of 65535 in capacity.
// A dungeon's capacity never change.
uint16 capacity;
// The current floor number, a dungeon is consists of an umlimited number of floors,
// when there is heroes successfully challenged a floor, the next floor will be
// automatically generated. Using 32-bit unsigned integer can have a maximum of 4 billion floors.
uint32 floorNumber;
// The timestamp of the block when the current floor is generated.
uint32 floorCreationTime;
// Current accumulated rewards, successful challenger will get a large proportion of it.
uint128 rewards;
// The seed genes of the dungeon, it is used as the base gene for first floor,
// some dungeons are rarer and some are more common, the exact details are,
// of course, top secret of the game!
// A dungeon's seedGenes never change.
uint seedGenes;
// The genes for current floor, it encodes the difficulty level of the current floor.
// We considered whether to store the entire array of genes for all floors, but
// in order to save some precious gas we're willing to sacrifice some functionalities with that.
uint floorGenes;
}
/**
* @dev The main Hero struct. Every hero in the game is represented by this structure.
*/
struct Hero {
// Each hero has an ID which is the index in the storage array.
// The timestamp of the block when this dungeon is created.
uint64 creationTime;
// The timestamp of the block where a challenge is performed, used to calculate when a hero is allowed to engage in another challenge.
uint64 cooldownStartTime;
// Every time a hero challenge a dungeon, its cooldown index will be incremented by one.
uint32 cooldownIndex;
// The seed of the hero, the gene encodes the power level of the hero.
// This is another top secret of the game! Hero's gene can be upgraded via
// training in a dungeon.
uint genes;
}
}
contract DungeonTokenInterface is ERC721, EDStructs {
/**
* @notice Limits the number of dungeons the contract owner can ever create.
*/
uint public constant DUNGEON_CREATION_LIMIT = 1024;
/**
* @dev Name of token.
*/
string public constant name = "Dungeon";
/**
* @dev Symbol of token.
*/
string public constant symbol = "DUNG";
/**
* @dev An array containing the Dungeon struct, which contains all the dungeons in existance.
* The ID for each dungeon is the index of this array.
*/
Dungeon[] public dungeons;
/**
* @dev The external function that creates a new dungeon and stores it, only contract owners
* can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT.
* Will generate a Mint event, a NewDungeonFloor event, and a Transfer event.
*/
function createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _seedGenes, uint _floorGenes, address _owner) external returns (uint);
/**
* @dev The external function to set dungeon status by its ID,
* refer to DungeonStructs for more information about dungeon status.
* Only contract owners can alter dungeon state.
*/
function setDungeonStatus(uint _id, uint _newStatus) external;
/**
* @dev The external function to add additional dungeon rewards by its ID,
* only contract owners can alter dungeon state.
*/
function addDungeonRewards(uint _id, uint _additinalRewards) external;
/**
* @dev The external function to add another dungeon floor by its ID,
* only contract owners can alter dungeon state.
*/
function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) external;
}
/**
* @title The ERC-721 compliance token contract for the Dungeon tokens.
* @dev See the DungeonStructs contract to see the details of the Dungeon token data structure.
*/
contract DungeonToken is DungeonTokenInterface, ERC721Token, JointOwnable {
/* ======== EVENTS ======== */
/**
* @dev The Mint event is fired whenever a new dungeon is created.
*/
event Mint(address indexed owner, uint newTokenId, uint difficulty, uint capacity, uint seedGenes);
/* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */
/**
* @dev Returns the total number of tokens currently in existence.
*/
function totalSupply() public view returns (uint) {
return dungeons.length;
}
/**
* @dev The external function that creates a new dungeon and stores it, only contract owners
* can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT.
* Will generate a Mint event, a NewDungeonFloor event, and a Transfer event.
* @param _difficulty The difficulty of the new dungeon.
* @param _capacity The capacity of the new dungeon.
* @param _floorNumber The initial floor number of the new dungeon.
* @param _seedGenes The seed genes of the new dungeon.
* @param _floorGenes The initial genes of the dungeon floor.
* @return The dungeon ID of the new dungeon.
*/
function createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _seedGenes, uint _floorGenes, address _owner) eitherOwner external returns (uint) {
return _createDungeon(_difficulty, _capacity, _floorNumber, 0, _seedGenes, _floorGenes, _owner);
}
/**
* @dev The external function to set dungeon status by its ID,
* refer to DungeonStructs for more information about dungeon status.
* Only contract owners can alter dungeon state.
*/
function setDungeonStatus(uint _id, uint _newStatus) eitherOwner tokenExists(_id) external {
dungeons[_id].status = uint8(_newStatus);
}
/**
* @dev The external function to add additional dungeon rewards by its ID,
* only contract owners can alter dungeon state.
*/
function addDungeonRewards(uint _id, uint _additinalRewards) eitherOwner tokenExists(_id) external {
dungeons[_id].rewards += uint128(_additinalRewards);
}
/**
* @dev The external function to add another dungeon floor by its ID,
* only contract owners can alter dungeon state.
*/
function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner tokenExists(_id) external {
Dungeon storage dungeon = dungeons[_id];
dungeon.floorNumber++;
dungeon.floorCreationTime = uint32(now);
dungeon.rewards = uint128(_newRewards);
dungeon.floorGenes = _newFloorGenes;
}
/* ======== PRIVATE/INTERNAL FUNCTIONS ======== */
function _createDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _rewards, uint _seedGenes, uint _floorGenes, address _owner) private returns (uint) {
// Ensure the total supply is within the fixed limit.
require(totalSupply() < DUNGEON_CREATION_LIMIT);
// ** STORAGE UPDATE **
// Create a new dungeon.
dungeons.push(Dungeon(uint32(now), 0, uint8(_difficulty), uint16(_capacity), uint32(_floorNumber), uint32(now), uint128(_rewards), _seedGenes, _floorGenes));
// Token id is the index in the storage array.
uint newTokenId = dungeons.length - 1;
// Emit the token mint event.
Mint(_owner, newTokenId, _difficulty, _capacity, _seedGenes);
// This will assign ownership, and also emit the Transfer event.
_transfer(0, _owner, newTokenId);
return newTokenId;
}
/* ======== MIGRATION FUNCTIONS ======== */
/**
* @dev Since the DungeonToken contract is re-deployed due to optimization.
* We need to migrate all dungeons from Beta token contract to Version 1.
*/
function migrateDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _rewards, uint _seedGenes, uint _floorGenes, address _owner) external {
// Migration will be finished before maintenance period ends, tx.origin is used within a short period only.
require(now < 1520694000 && tx.origin == 0x47169f78750Be1e6ec2DEb2974458ac4F8751714);
_createDungeon(_difficulty, _capacity, _floorNumber, _rewards, _seedGenes, _floorGenes, _owner);
}
}
/**
* @title ERC721DutchAuction
* @dev Dutch auction / Decreasing clock auction for ERC721 tokens.
*/
contract ERC721DutchAuction is Ownable, Pausable {
/* ======== STRUCTS/ENUMS ======== */
// Represents an auction of an ERC721 token.
struct Auction {
// Current owner of the ERC721 token.
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;
}
/* ======== CONTRACTS ======== */
// Reference to contract tracking ERC721 token ownership.
ERC721 public nonFungibleContract;
/* ======== STATE VARIABLES ======== */
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint => Auction) tokenIdToAuction;
/* ======== EVENTS ======== */
event AuctionCreated(uint timestamp, address indexed seller, uint indexed tokenId, uint startingPrice, uint endingPrice, uint duration);
event AuctionSuccessful(uint timestamp, address indexed seller, uint indexed tokenId, uint totalPrice, address winner);
event AuctionCancelled(uint timestamp, address indexed seller, uint indexed tokenId);
/**
* @dev Constructor creates a reference to the ERC721 token ownership contract and verifies the owner cut is in the valid range.
* @param _tokenAddress - address of a deployed contract implementing the Nonfungible Interface.
* @param _ownerCut - percent cut the owner takes on each auction, must be between 0-10,000.
*/
function ERC721DutchAuction(address _tokenAddress, uint _ownerCut) public {
require(_ownerCut <= 10000);
nonFungibleContract = ERC721(_tokenAddress);
ownerCut = _ownerCut;
}
/* ======== PUBLIC/EXTERNAL FUNCTIONS ======== */
/**
* @dev Bids on an open auction, completing the auction and transferring
* ownership of the token if enough Ether is supplied.
* @param _tokenId - ID of token to bid on.
*/
function bid(uint _tokenId) whenNotPaused external payable {
// _bid will throw if the bid or funds transfer fails.
_bid(_tokenId, msg.value);
// Transfers the token owned by this contract to another address. It will throw if transfer fails.
nonFungibleContract.transfer(msg.sender, _tokenId);
}
/**
* @dev Cancels an auction that hasn't been won yet. Returns the token 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(uint _tokenId) external {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/**
* @dev Cancels an auction when the contract is paused.
* Only the owner may do this, and tokens are returned to
* the seller. This should only be used in emergencies.
* @param _tokenId - ID of the token on auction to cancel.
*/
function cancelAuctionWhenPaused(uint _tokenId) whenPaused onlyOwner external {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/**
* @dev Remove all Ether from the contract, which is the owner's cuts
* as well as any Ether sent directly to the contract address.
*/
function withdrawBalance() onlyOwner external {
msg.sender.transfer(this.balance);
}
/**
* @dev Returns auction info for an token on auction.
* @param _tokenId - ID of token on auction.
*/
function getAuction(uint _tokenId) external view returns (
address seller,
uint startingPrice,
uint endingPrice,
uint duration,
uint 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(uint _tokenId) external view returns (uint) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _computeCurrentPrice(auction);
}
/* ======== INTERNAL/PRIVATE FUNCTIONS ======== */
/**
* @dev Creates and begins a new auction. Perform all the checkings necessary.
* @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(
uint _tokenId,
uint _startingPrice,
uint _endingPrice,
uint _duration,
address _seller
) internal {
// Sanity check that no inputs overflow how many bits we've allocated to store them in the auction struct.
require(_startingPrice == uint(uint128(_startingPrice)));
require(_endingPrice == uint(uint128(_endingPrice)));
require(_duration == uint(uint64(_duration)));
// If the token is already on any auction, this will throw
// because it will be owned by the auction contract.
require(nonFungibleContract.ownerOf(_tokenId) == msg.sender);
// Throw if the _endingPrice is larger than _startingPrice.
require(_startingPrice >= _endingPrice);
// Require that all auctions have a duration of at least one minute.
require(_duration >= 1 minutes);
// Transfer the token from its owner to this contract. It will throw if transfer fails.
nonFungibleContract.transferFrom(msg.sender, this, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/**
* @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(uint _tokenId, Auction _auction) internal {
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
now,
_auction.seller,
_tokenId,
_auction.startingPrice,
_auction.endingPrice,
_auction.duration
);
}
/**
* @dev Computes the price and transfers winnings.
* Does NOT transfer ownership of token.
*/
function _bid(uint _tokenId, uint _bidAmount) internal returns (uint) {
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint price = _computeCurrentPrice(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.
uint auctioneerCut = price * ownerCut / 10000;
uint sellerProceeds = price - auctioneerCut;
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
AuctionSuccessful(now, seller, _tokenId, price, msg.sender);
return price;
}
/**
* @dev Cancels an auction unconditionally.
*/
function _cancelAuction(uint _tokenId, address _seller) internal {
_removeAuction(_tokenId);
// Transfers the token owned by this contract to its original owner. It will throw if transfer fails.
nonFungibleContract.transfer(_seller, _tokenId);
AuctionCancelled(now, _seller, _tokenId);
}
/**
* @dev Removes an auction from the list of open auctions.
* @param _tokenId - ID of token on auction.
*/
function _removeAuction(uint _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/**
* @dev Returns current price of an token 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 _computeCurrentPrice(Auction storage _auction) internal view returns (uint) {
uint 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;
}
if (secondsPassed >= _auction.duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _auction.endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int totalPriceChange = int(_auction.endingPrice) - int(_auction.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.
int currentPriceChange = totalPriceChange * int(secondsPassed) / int(_auction.duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that startingPrice. Thus, this result will always end up positive.
int currentPrice = int(_auction.startingPrice) + currentPriceChange;
return uint(currentPrice);
}
}
/* ======== MODIFIERS ======== */
/**
* @dev Returns true if the token is on auction.
* @param _auction - Auction to check.
*/
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
}
contract DungeonTokenAuction is DungeonToken, ERC721DutchAuction {
function DungeonTokenAuction(uint _ownerCut) ERC721DutchAuction(this, _ownerCut) public { }
/**
* @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).
*/
function createAuction(
uint _tokenId,
uint _startingPrice,
uint _endingPrice,
uint _duration
) whenNotPaused external {
_approve(_tokenId, this);
// This will perform all the checkings necessary.
_createAuction(_tokenId, _startingPrice, _endingPrice, _duration, msg.sender);
}
}
| Since the DungeonToken contract is re-deployed due to optimization. We need to migrate all dungeons from Beta token contract to Version 1./ Migration will be finished before maintenance period ends, tx.origin is used within a short period only. | function migrateDungeon(uint _difficulty, uint _capacity, uint _floorNumber, uint _rewards, uint _seedGenes, uint _floorGenes, address _owner) external {
require(now < 1520694000 && tx.origin == 0x47169f78750Be1e6ec2DEb2974458ac4F8751714);
_createDungeon(_difficulty, _capacity, _floorNumber, _rewards, _seedGenes, _floorGenes, _owner);
}
| 1,793,800 |
//SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "./SeedPhrasePricing.sol";
import "../interfaces/IN.sol";
import "../interfaces/IRarible.sol";
import "../interfaces/IKarmaScore.sol";
import "../interfaces/INOwnerResolver.sol";
import "../libraries/NilProtocolUtils.sol";
import "../libraries/SeedPhraseUtils.sol";
////////////////////////////////////////////////////////////////////////////////////////
// //
// //
// ░██████╗███████╗███████╗██████╗░ ██████╗░██╗░░██╗██████╗░░█████╗░░██████╗███████╗ //
// ██╔════╝██╔════╝██╔════╝██╔══██╗ ██╔══██╗██║░░██║██╔══██╗██╔══██╗██╔════╝██╔════╝ //
// ╚█████╗░█████╗░░█████╗░░██║░░██║ ██████╔╝███████║██████╔╝███████║╚█████╗░█████╗░░ //
// ░╚═══██╗██╔══╝░░██╔══╝░░██║░░██║ ██╔═══╝░██╔══██║██╔══██╗██╔══██║░╚═══██╗██╔══╝░░ //
// ██████╔╝███████╗███████╗██████╔╝ ██║░░░░░██║░░██║██║░░██║██║░░██║██████╔╝███████╗ //
// ╚═════╝░╚══════╝╚══════╝╚═════╝░ ╚═╝░░░░░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚═╝╚═════╝░╚══════╝ //
// //
// //
// Title: Seed Phrase //
// Devs: Harry Faulkner & maximonee (twitter.com/maximonee_) //
// Description: This contract provides minting for the //
// Seed Phrase NFT by Sean Elliott //
// (twitter.com/seanelliottoc) //
// //
////////////////////////////////////////////////////////////////////////////////////////
contract SeedPhrase is SeedPhrasePricing, VRFConsumerBase {
using Strings for uint256;
using Strings for uint16;
using Strings for uint8;
using Counters for Counters.Counter;
using SeedPhraseUtils for SeedPhraseUtils.Random;
Counters.Counter private _doublePanelTokens;
Counters.Counter private _tokenIds;
address private _owner;
// Tracks whether an n has been used already to mint
mapping(uint256 => bool) public override nUsed;
mapping(PreSaleType => uint16) public presaleLimits;
address[] private genesisSketchAddresses;
uint16[] private bipWordIds = new uint16[](2048);
IRarible public immutable rarible;
INOwnerResolver public immutable nOwnerResolver;
IKarmaScore public immutable karma;
struct Maps {
// Map double panel tokens to burned singles
mapping(uint256 => uint256[2]) burnedTokensPairings;
// Mapping of valid double panel pairings (BIP39 IDs)
mapping(uint16 => uint16) doubleWordPairings;
// Stores the guarenteed token rarity for a double panel
mapping(uint256 => uint8) doubleTokenRarity;
mapping(address => bool) ogAddresses;
// Map token to their unique seed
mapping(uint256 => bytes32) tokenSeed;
}
struct Config {
bool preSaleActive;
bool publicSaleActive;
bool isSaleHalted;
bool bipWordsShuffled;
bool vrfNumberGenerated;
bool isBurnActive;
bool isOwnerSupplyMinted;
bool isGsAirdropComplete;
uint8 ownerSupply;
uint16 maxPublicMint;
uint16 karmaRequirement;
uint32 preSaleLaunchTime;
uint32 publicSaleLaunchTime;
uint256 doubleBurnTokens;
uint256 linkFee;
uint256 raribleTokenId;
uint256 vrfRandomValue;
address vrfCoordinator;
address linkToken;
bytes32 vrfKeyHash;
}
struct ContractAddresses {
address n;
address masterMint;
address dao;
address nOwnersRegistry;
address vrfCoordinator;
address linkToken;
address karmaAddress;
address rarible;
}
Config private config;
Maps private maps;
event Burnt(address to, uint256 firstBurntToken, uint256 secondBurntToken, uint256 doublePaneledToken);
DerivativeParameters params = DerivativeParameters(false, false, 0, 2048, 4);
constructor(
ContractAddresses memory contractAddresses,
bytes32 _vrfKeyHash,
uint256 _linkFee
)
SeedPhrasePricing(
"Seed Phrase",
"SEED",
IN(contractAddresses.n),
params,
30000000000000000,
60000000000000000,
contractAddresses.masterMint,
contractAddresses.dao
)
VRFConsumerBase(contractAddresses.vrfCoordinator, contractAddresses.linkToken)
{
// Start token IDs at 1
_tokenIds.increment();
presaleLimits[PreSaleType.N] = 400;
presaleLimits[PreSaleType.Karma] = 800;
presaleLimits[PreSaleType.GenesisSketch] = 40;
presaleLimits[PreSaleType.OG] = 300;
presaleLimits[PreSaleType.GM] = 300;
nOwnerResolver = INOwnerResolver(contractAddresses.nOwnersRegistry);
rarible = IRarible(contractAddresses.rarible);
karma = IKarmaScore(contractAddresses.karmaAddress);
// Initialize Config struct
config.maxPublicMint = 8;
config.ownerSupply = 20;
config.preSaleLaunchTime = 1639591200;
config.publicSaleLaunchTime = 1639598400;
config.raribleTokenId = 706480;
config.karmaRequirement = 1020;
config.vrfCoordinator = contractAddresses.vrfCoordinator;
config.linkToken = contractAddresses.linkToken;
config.linkFee = _linkFee;
config.vrfKeyHash = _vrfKeyHash;
_owner = 0x7F05F27CC5D83C3e879C53882de13Cc1cbCe8a8c;
}
function owner() external view virtual returns (address) {
return _owner;
}
function setOwner(address owner_) external onlyAdmin {
_owner = owner_;
}
function contractURI() public pure returns (string memory) {
return "https://www.seedphrase.codes/metadata/seedphrase-metadata.json";
}
function getVrfSeed() external onlyAdmin returns (bytes32) {
require(!config.vrfNumberGenerated, "SP:VRF_ALREADY_CALLED");
require(LINK.balanceOf(address(this)) >= config.linkFee, "SP:NOT_ENOUGH_LINK");
return requestRandomness(config.vrfKeyHash, config.linkFee);
}
function fulfillRandomness(bytes32, uint256 randomNumber) internal override {
config.vrfRandomValue = randomNumber;
config.vrfNumberGenerated = true;
}
function _getTokenSeed(uint256 tokenId) internal view returns (bytes32) {
return maps.tokenSeed[tokenId];
}
function _getBipWordIdFromTokenId(uint256 tokenId) internal view returns (uint16) {
return bipWordIds[tokenId - 1];
}
function tokenSVG(uint256 tokenId) public view virtual returns (string memory svg, bytes memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
SeedPhraseUtils.Random memory random = SeedPhraseUtils.Random({
seed: uint256(_getTokenSeed(tokenId)),
offsetBit: 0
});
uint16 bipWordId;
uint16 secondBipWordId = 0;
uint8 rarityValue = 0;
if (tokenId >= 3000) {
uint256[2] memory tokens = maps.burnedTokensPairings[tokenId];
bipWordId = _getBipWordIdFromTokenId(tokens[0]);
secondBipWordId = _getBipWordIdFromTokenId(tokens[1]);
rarityValue = maps.doubleTokenRarity[tokenId];
} else {
bipWordId = _getBipWordIdFromTokenId(tokenId);
}
(bytes memory traits, SeedPhraseUtils.Attrs memory attributes) = SeedPhraseUtils.getTraitsAndAttributes(
bipWordId,
secondBipWordId,
rarityValue,
random
);
return (SeedPhraseUtils.render(random, attributes), traits);
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
(string memory output, bytes memory traits) = tokenSVG(tokenId);
return SeedPhraseUtils.getTokenURI(output, traits, tokenId);
}
/**
Updates the presale state for n holders
*/
function setPreSaleState(bool _preSaleActiveState) external onlyAdmin {
config.preSaleActive = _preSaleActiveState;
}
/**
Updates the public sale state for non-n holders
*/
function setPublicSaleState(bool _publicSaleActiveState) external onlyAdmin {
config.publicSaleActive = _publicSaleActiveState;
}
function setPreSaleTime(uint32 _time) external onlyAdmin {
config.preSaleLaunchTime = _time;
}
function setPublicSaleTime(uint32 _time) external onlyAdmin {
config.publicSaleLaunchTime = _time;
}
/**
Give the ability to halt the sale if necessary due to automatic sale enablement based on time
*/
function setSaleHaltedState(bool _saleHaltedState) external onlyAdmin {
config.isSaleHalted = _saleHaltedState;
}
function setBurnActiveState(bool _burnActiveState) external onlyAdmin {
config.isBurnActive = _burnActiveState;
}
function setGenesisSketchAllowList(address[] calldata addresses) external onlyAdmin {
genesisSketchAddresses = addresses;
}
function setOgAllowList(address[] calldata addresses) external onlyAdmin {
for (uint256 i = 0; i < addresses.length; i++) {
maps.ogAddresses[addresses[i]] = true;
}
}
function _isPreSaleActive() internal view returns (bool) {
return ((block.timestamp >= config.preSaleLaunchTime || config.preSaleActive) && !config.isSaleHalted);
}
function _isPublicSaleActive() internal view override returns (bool) {
return ((block.timestamp >= config.publicSaleLaunchTime || config.publicSaleActive) && !config.isSaleHalted);
}
function _canMintPresale(
address addr,
uint256 amount,
bytes memory data
) internal view override returns (bool, PreSaleType) {
if (maps.ogAddresses[addr] && presaleLimits[PreSaleType.OG] - amount >= 0) {
return (true, PreSaleType.OG);
}
bool isGsHolder;
for (uint256 i = 0; i < genesisSketchAddresses.length; i++) {
if (genesisSketchAddresses[i] == addr) {
isGsHolder = true;
}
}
if (isGsHolder && presaleLimits[PreSaleType.GenesisSketch] - amount >= 0) {
return (true, PreSaleType.GenesisSketch);
}
if (rarible.balanceOf(addr, config.raribleTokenId) > 0 && presaleLimits[PreSaleType.GM] - amount > 0) {
return (true, PreSaleType.GM);
}
uint256 karmaScore = SeedPhraseUtils.getKarma(karma, data, addr);
if (nOwnerResolver.balanceOf(addr) > 0) {
if (karmaScore >= config.karmaRequirement && presaleLimits[PreSaleType.Karma] - amount >= 0) {
return (true, PreSaleType.Karma);
}
if (presaleLimits[PreSaleType.N] - amount >= 0) {
return (true, PreSaleType.N);
}
}
return (false, PreSaleType.None);
}
function canMint(address account, bytes calldata data) public view virtual override returns (bool) {
if (config.isBurnActive) {
return false;
}
uint256 balance = balanceOf(account);
if (_isPublicSaleActive() && (totalMintsAvailable() > 0) && balance < config.maxPublicMint) {
return true;
}
if (_isPreSaleActive()) {
(bool preSaleEligible, ) = _canMintPresale(account, 1, data);
return preSaleEligible;
}
return false;
}
/**
* @notice Allow a n token holder to bulk mint tokens with id of their n tokens' id
* @param recipient Recipient of the mint
* @param tokenIds Ids to be minted
* @param paid Amount paid for the mint
*/
function mintWithN(
address recipient,
uint256[] calldata tokenIds,
uint256 paid,
bytes calldata data
) public virtual override nonReentrant {
uint256 maxTokensToMint = tokenIds.length;
(bool preSaleEligible, PreSaleType presaleType) = _canMintPresale(recipient, maxTokensToMint, data);
require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT");
require(_isPublicSaleActive() || (_isPreSaleActive() && preSaleEligible), "SP:SALE_NOT_ACTIVE");
require(
balanceOf(recipient) + maxTokensToMint <= _getMaxMintPerWallet(),
"NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE"
);
require(!config.isBurnActive, "SP:SALE_OVER");
require(totalSupply() + maxTokensToMint <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED");
uint256 price = getNextPriceForNHoldersInWei(maxTokensToMint, recipient, data);
require(paid == price, "NilPass:INVALID_PRICE");
for (uint256 i = 0; i < maxTokensToMint; i++) {
require(!nUsed[tokenIds[i]], "SP:N_ALREADY_USED");
uint256 tokenId = _tokenIds.current();
require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH");
maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue);
_safeMint(recipient, tokenId);
_tokenIds.increment();
nUsed[tokenIds[i]] = true;
}
if (preSaleEligible) {
presaleLimits[presaleType] -= uint16(maxTokensToMint);
}
}
/**
* @notice Allow anyone to mint a token with the supply id if this pass is unrestricted.
* n token holders can use this function without using the n token holders allowance,
* this is useful when the allowance is fully utilized.
* @param recipient Recipient of the mint
* @param amount Amount of tokens to mint
* @param paid Amount paid for the mint
*/
function mint(
address recipient,
uint8 amount,
uint256 paid,
bytes calldata data
) public virtual override nonReentrant {
(bool preSaleEligible, PreSaleType presaleType) = _canMintPresale(recipient, amount, data);
require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT");
require(
_isPublicSaleActive() ||
(_isPreSaleActive() &&
preSaleEligible &&
(presaleType != PreSaleType.N && presaleType != PreSaleType.Karma)),
"SP:SALE_NOT_ACTIVE"
);
require(!config.isBurnActive, "SP:SALE_OVER");
require(balanceOf(recipient) + amount <= _getMaxMintPerWallet(), "NilPass:MINT_ABOVE_MAX_MINT_ALLOWANCE");
require(totalSupply() + amount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED");
uint256 price = getNextPriceForOpenMintInWei(amount, recipient, data);
require(paid == price, "NilPass:INVALID_PRICE");
for (uint256 i = 0; i < amount; i++) {
uint256 tokenId = _tokenIds.current();
require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH");
maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue);
_safeMint(recipient, tokenId);
_tokenIds.increment();
}
if (preSaleEligible) {
presaleLimits[presaleType] -= amount;
}
}
function mintOwnerSupply(address account) public nonReentrant onlyAdmin {
require(!config.isOwnerSupplyMinted, "SP:ALREADY_MINTED");
require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT");
require(
totalSupply() + config.ownerSupply <= params.maxTotalSupply,
"NilPass:MAX_ALLOCATION_REACHED"
);
for (uint256 i = 0; i < config.ownerSupply; i++) {
uint256 tokenId = _tokenIds.current();
maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue);
_mint(account, tokenId);
_tokenIds.increment();
}
config.isOwnerSupplyMinted = true;
}
/**
* @notice Allow anyone to burn two single panels they own in order to mint
* a double paneled token.
* @param firstTokenId Token ID of the first token
* @param secondTokenId Token ID of the second token
*/
function burnForDoublePanel(uint256 firstTokenId, uint256 secondTokenId) public nonReentrant {
require(config.isBurnActive, "SP:BURN_INACTIVE");
require(ownerOf(firstTokenId) == msg.sender && ownerOf(secondTokenId) == msg.sender, "SP:INCORRECT_OWNER");
require(firstTokenId != secondTokenId, "SP:EQUAL_TOKENS");
// Ensure two owned tokens are in Burnable token pairings
require(
isValidPairing(_getBipWordIdFromTokenId(firstTokenId), _getBipWordIdFromTokenId(secondTokenId)),
"SP:INVALID_TOKEN_PAIRING"
);
_burn(firstTokenId);
_burn(secondTokenId);
// Any Token ID of 3000 or greater indicates it is a double panel e.g. 3000, 3001, 3002...
uint256 doublePanelTokenId = 3000 + _doublePanelTokens.current();
maps.tokenSeed[doublePanelTokenId] = SeedPhraseUtils.generateSeed(doublePanelTokenId, config.vrfRandomValue);
// Get the rarity rating from the burned tokens, store this against the new token
// Burners are guaranteed their previous strongest trait (at least, could be rarer)
uint8 rarity1 = SeedPhraseUtils.getRarityRating(_getTokenSeed(firstTokenId));
uint8 rarity2 = SeedPhraseUtils.getRarityRating(_getTokenSeed(secondTokenId));
maps.doubleTokenRarity[doublePanelTokenId] = (rarity1 > rarity2 ? rarity1 : rarity2);
_mint(msg.sender, doublePanelTokenId);
// Add burned tokens to maps.burnedTokensPairings mapping so we can use them to render the double panels later
maps.burnedTokensPairings[doublePanelTokenId] = [firstTokenId, secondTokenId];
_doublePanelTokens.increment();
emit Burnt(msg.sender, firstTokenId, secondTokenId, doublePanelTokenId);
}
function airdropGenesisSketch() public nonReentrant onlyAdmin {
require(!config.isGsAirdropComplete, "SP:ALREADY_AIRDROPPED");
require(config.bipWordsShuffled && config.vrfNumberGenerated, "SP:ENV_NOT_INIT");
uint256 airdropAmount = genesisSketchAddresses.length;
require(totalSupply() + airdropAmount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED");
for (uint256 i = 0; i < airdropAmount; i++) {
uint256 tokenId = _tokenIds.current();
maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue);
_mint(genesisSketchAddresses[i], tokenId);
_tokenIds.increment();
}
config.isGsAirdropComplete = true;
}
function mintOrphanedPieces(uint256 amount, address addr) public nonReentrant onlyAdmin {
require(totalMintsAvailable() == 0, "SP:MINT_NOT_OVER");
// _tokenIds - 1 to get the current number of minted tokens (token IDs start at 1)
uint256 currentSupply = _tokenIds.current() - 1;
config.doubleBurnTokens = derivativeParams.maxTotalSupply - currentSupply;
require(config.doubleBurnTokens >= amount, "SP:NOT_ENOUGH_ORPHANS");
require(currentSupply + amount <= params.maxTotalSupply, "NilPass:MAX_ALLOCATION_REACHED");
for (uint256 i = 0; i < amount; i++) {
uint256 tokenId = _tokenIds.current();
require(tokenId <= params.maxTotalSupply, "SP:TOKEN_TOO_HIGH");
maps.tokenSeed[tokenId] = SeedPhraseUtils.generateSeed(tokenId, config.vrfRandomValue);
_mint(addr, tokenId);
_tokenIds.increment();
}
config.doubleBurnTokens -= amount;
}
/**
* @notice Calculate the total available number of mints
* @return total mint available
*/
function totalMintsAvailable() public view override returns (uint256) {
uint256 totalAvailable = derivativeParams.maxTotalSupply - totalSupply();
if (block.timestamp > config.publicSaleLaunchTime + 18 hours) {
// Double candle burning starts and decreases max. mintable supply with 1 token per minute.
uint256 doubleBurn = (block.timestamp - (config.publicSaleLaunchTime + 18 hours)) / 1 minutes;
totalAvailable = totalAvailable > doubleBurn ? totalAvailable - doubleBurn : 0;
}
return totalAvailable;
}
function getDoubleBurnedTokens() external view returns (uint256) {
return config.doubleBurnTokens;
}
function _getMaxMintPerWallet() internal view returns (uint128) {
return _isPublicSaleActive() ? config.maxPublicMint : params.maxMintAllowance;
}
function isValidPairing(uint16 first, uint16 second) public view returns (bool) {
return maps.doubleWordPairings[first] == second;
}
function amendPairings(uint16[][] calldata pairings) external onlyAdmin {
for (uint16 i = 0; i < pairings.length; i++) {
if (pairings[i].length != 2) {
continue;
}
maps.doubleWordPairings[pairings[i][0]] = pairings[i][1];
}
}
function shuffleBipWords() external onlyAdmin {
require(config.vrfNumberGenerated, "SP:VRF_NOT_CALLED");
require(!config.bipWordsShuffled, "SP:ALREADY_SHUFFLED");
bipWordIds = SeedPhraseUtils.shuffleBipWords(config.vrfRandomValue);
config.bipWordsShuffled = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(
bytes32 requestId,
uint256 randomness
)
internal
virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 constant private USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee
)
internal
returns (
bytes32 requestId
)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(
address _vrfCoordinator,
address _link
) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(
bytes32 requestId,
uint256 randomness
)
external
{
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;
import "../core/NilPassCore.sol";
abstract contract SeedPhrasePricing is NilPassCore {
uint256 preSalePrice;
uint256 publicSalePrice;
constructor(
string memory name,
string memory symbol,
IN n,
DerivativeParameters memory derivativeParams,
uint256 preSalePrice_,
uint256 publicSalePrice_,
address masterMint,
address dao
) NilPassCore(name, symbol, n, derivativeParams, masterMint, dao) {
preSalePrice = preSalePrice_;
publicSalePrice = publicSalePrice_;
}
enum PreSaleType {
GenesisSketch,
OG,
GM,
Karma,
N,
None
}
function _canMintPresale(
address addr,
uint256 amount,
bytes memory data
) internal view virtual returns (bool, PreSaleType);
function _isPublicSaleActive() internal view virtual returns (bool);
/**
* @notice Returns the next price for an N mint
*/
function getNextPriceForNHoldersInWei(
uint256 numberOfMints,
address account,
bytes memory data
) public view override returns (uint256) {
(bool preSaleEligible, ) = _canMintPresale(account, numberOfMints, data);
uint256 price = preSaleEligible && !_isPublicSaleActive() ? preSalePrice : publicSalePrice;
return numberOfMints * price;
}
/**
* @notice Returns the next price for an open mint
*/
function getNextPriceForOpenMintInWei(
uint256 numberOfMints,
address account,
bytes memory data
) public view override returns (uint256) {
(bool preSaleEligible, ) = _canMintPresale(account, numberOfMints, data);
uint256 price = preSaleEligible && !_isPublicSaleActive() ? preSalePrice : publicSalePrice;
return numberOfMints * price;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
interface IN is IERC721Enumerable, IERC721Metadata {
function getFirst(uint256 tokenId) external view returns (uint256);
function getSecond(uint256 tokenId) external view returns (uint256);
function getThird(uint256 tokenId) external view returns (uint256);
function getFourth(uint256 tokenId) external view returns (uint256);
function getFifth(uint256 tokenId) external view returns (uint256);
function getSixth(uint256 tokenId) external view returns (uint256);
function getSeventh(uint256 tokenId) external view returns (uint256);
function getEight(uint256 tokenId) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
interface IRarible is IERC721Enumerable, IERC721Metadata {
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
}
//SPDX-License-Identifier: MIT
/**
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@( @@( @@( @@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @ @@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@( @@@ @@@ @@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
*/
pragma solidity >=0.8.4;
interface IKarmaScore {
function verify(
address account,
uint256 score,
bytes calldata data
) external view returns (bool);
function merkleRoot() external view returns (bytes32);
function setMerkleRoot(bytes32 _merkleRoot) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
interface INOwnerResolver {
function ownerOf(uint256 nid) external view returns (address);
function balanceOf(address account) external view returns (uint256);
function nOwned(address owner) external view returns (uint256[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
library NilProtocolUtils {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
/// @notice Encodes some bytes to the base64 representation
function base64encode(bytes memory data) external 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);
}
// @notice converts number to string
function stringify(uint256 value) external pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;
import "@openzeppelin/contracts/utils/Strings.sol";
import "../interfaces/IKarmaScore.sol";
import "./NilProtocolUtils.sol";
import "../libraries/NilProtocolUtils.sol";
library SeedPhraseUtils {
using Strings for uint256;
using Strings for uint16;
using Strings for uint8;
struct Random {
uint256 seed;
uint256 offsetBit;
}
struct Colors {
string background;
string panel;
string panel2;
string panelStroke;
string selectedCircleStroke;
string selectedCircleFill;
string selectedCircleFill2;
string negativeCircleStroke;
string negativeCircleFill;
string blackOrWhite;
string dynamicOpacity;
string backgroundCircle;
}
struct Attrs {
bool showStroke;
bool border;
bool showPanel;
bool backgroundSquare;
bool bigBackgroundCircle;
bool showGrid;
bool backgroundCircles;
bool greyscale;
bool doublePanel;
uint16 bipWordId;
uint16 secondBipWordId;
}
uint8 internal constant strokeWeight = 7;
uint16 internal constant segmentSize = 100;
uint16 internal constant radius = 50;
uint16 internal constant padding = 10;
uint16 internal constant viewBox = 1600;
uint16 internal constant panelWidth = segmentSize * 4;
uint16 internal constant panelHeight = segmentSize * 10;
uint16 internal constant singlePanelX = (segmentSize * 6);
uint16 internal constant doublePanel1X = (segmentSize * 3);
uint16 internal constant doublePanel2X = doublePanel1X + (segmentSize * 6);
uint16 internal constant panelY = (segmentSize * 3);
function generateSeed(uint256 tokenId, uint256 vrfRandomValue) external view returns (bytes32) {
return keccak256(abi.encode(tokenId, block.timestamp, block.difficulty, vrfRandomValue));
}
function _shouldAddTrait(
bool isTrue,
bytes memory trueName,
bytes memory falseName,
uint8 prevRank,
uint8 newRank,
bytes memory traits
) internal pure returns (bytes memory, uint8) {
if (isTrue) {
traits = abi.encodePacked(traits, ',{"value": "', trueName, '"}');
}
// Only add the falsy trait if it's named (e.g. there's no negative version of "greyscale")
else if (falseName.length != 0) {
traits = abi.encodePacked(traits, ',{"value": "', falseName, '"}');
}
// Return new (higher rank if trait is true)
return (traits, (isTrue ? newRank : prevRank));
}
function tokenTraits(Attrs memory attributes) internal pure returns (bytes memory traits, uint8 rarityRating) {
rarityRating = 0;
traits = abi.encodePacked("[");
// Add both words to trait if a double panel
if (attributes.doublePanel) {
traits = abi.encodePacked(
traits,
'{"trait_type": "Double Panel BIP39 IDs", "value": "',
attributes.bipWordId.toString(),
" - ",
attributes.secondBipWordId.toString(),
'"},',
'{"value": "Double Panel"}'
);
} else {
traits = abi.encodePacked(
traits,
'{"trait_type": "BIP39 ID", "display_type": "number", "max_value": 2048, "value": ',
attributes.bipWordId.toString(),
"}"
);
}
// Stroke trait - rank 1
(traits, rarityRating) = _shouldAddTrait(
!attributes.showStroke,
"No Stroke",
"OG Stroke",
rarityRating,
1,
traits
);
// Border - rank 2
(traits, rarityRating) = _shouldAddTrait(attributes.border, "Border", "", rarityRating, 2, traits);
// No Panel - rank 3
(traits, rarityRating) = _shouldAddTrait(
!attributes.showPanel,
"No Panel",
"OG Panel",
rarityRating,
3,
traits
);
// Symmetry Group Square - rank 4
(traits, rarityRating) = _shouldAddTrait(
attributes.backgroundSquare,
"Group Square",
"",
rarityRating,
4,
traits
);
// Symmetry Group Circle - rank 5
(traits, rarityRating) = _shouldAddTrait(
attributes.bigBackgroundCircle,
"Group Circle",
"",
rarityRating,
5,
traits
);
// Caged - rank 6
(traits, rarityRating) = _shouldAddTrait(attributes.showGrid, "Caged", "", rarityRating, 6, traits);
// Bubblewrap - rank 7
(traits, rarityRating) = _shouldAddTrait(
attributes.backgroundCircles,
"Bubblewrap",
"",
rarityRating,
7,
traits
);
// Monochrome - rank 8
(traits, rarityRating) = _shouldAddTrait(attributes.greyscale, "Monochrome", "", rarityRating, 8, traits);
traits = abi.encodePacked(traits, "]");
}
/**
* @notice Generates the art defining attributes
* @param bipWordId bip39 word id
* @param secondBipWordId ^ only for a double panel
* @param random RNG
* @param predefinedRarity double panels trait to carry over
* @return attributes struct
*/
function tokenAttributes(
uint16 bipWordId,
uint16 secondBipWordId,
Random memory random,
uint8 predefinedRarity
) internal pure returns (Attrs memory attributes) {
attributes = Attrs({
showStroke: (predefinedRarity == 1) ? false : _boolPercentage(random, 70), // rank 1
border: (predefinedRarity == 2) ? true : _boolPercentage(random, 30), // rank 2
showPanel: (predefinedRarity == 3) ? false : _boolPercentage(random, 80), // rank 3
backgroundSquare: (predefinedRarity == 4) ? true : _boolPercentage(random, 18), // rank 4
bigBackgroundCircle: (predefinedRarity == 5) ? true : _boolPercentage(random, 12), // rank = 5
showGrid: (predefinedRarity == 6) ? true : _boolPercentage(random, 6), // rank 6
backgroundCircles: (predefinedRarity == 7) ? true : _boolPercentage(random, 4), // rank 7
greyscale: (predefinedRarity == 8) ? true : _boolPercentage(random, 2), // rank 8
bipWordId: bipWordId,
doublePanel: (secondBipWordId > 0),
secondBipWordId: secondBipWordId
});
// Rare attributes should always superseed less-rare
// If greyscale OR grid is true then turn on stroke (as it is required)
if (attributes.showGrid || attributes.greyscale) {
attributes.showStroke = true;
}
// backgroundCircles superseeds grid (they cannot co-exist)
if (attributes.backgroundCircles) {
attributes.showGrid = false;
}
// Border cannot be on if background shapes are turned on
if (attributes.bigBackgroundCircle || attributes.backgroundSquare) {
attributes.border = false;
// Big Background Shapes cannot co-exist
if (attributes.bigBackgroundCircle) {
attributes.backgroundSquare = false;
}
}
}
/**
* @notice Converts a tokenId (uint256) into the formats needed to generate the art
* @param tokenId tokenId (also the BIP39 word)
* @return tokenArray with prepended 0's (if tokenId is less that 4 digits) also returns in string format
*/
function _transformTokenId(uint256 tokenId) internal pure returns (uint8[4] memory tokenArray, string memory) {
bytes memory tokenString;
uint8 digit;
for (int8 i = 3; i >= 0; i--) {
digit = uint8(tokenId % 10); // This returns the final digit in the token
if (tokenId > 0) {
tokenId = tokenId / 10; // this removes the last digit from the token as we've grabbed the digit already
tokenArray[uint8(i)] = digit;
}
tokenString = abi.encodePacked(digit.toString(), tokenString);
}
return (tokenArray, string(tokenString));
}
function _renderText(string memory text, string memory color) internal pure returns (bytes memory svg) {
svg = abi.encodePacked(
"<text x='1500' y='1500' text-anchor='end' style='font:700 36px "Courier New";fill:",
color,
";opacity:.4'>#",
text,
"</text>"
);
return svg;
}
function _backgroundShapeSizing(Random memory random, Attrs memory attributes)
internal
pure
returns (uint16, uint16)
{
uint256 idx;
// If we DON'T have a 'doublePanel' or 'no panel' we can return the default sizing
if (!attributes.doublePanel && attributes.showPanel) {
uint16[2][6] memory defaultSizing = [
[1275, 200],
[1150, 375],
[900, 300],
[925, 225],
[850, 150],
[775, 125]
];
idx = SeedPhraseUtils._next(random, 0, defaultSizing.length);
return (defaultSizing[idx][0], defaultSizing[idx][1]);
}
// Otherwise we need to return some slightly different data
if (attributes.bigBackgroundCircle) {
uint16[2][4] memory restrictedCircleDimensions = [[1150, 150], [1275, 200], [1300, 100], [1350, 200]];
idx = SeedPhraseUtils._next(random, 0, restrictedCircleDimensions.length);
return (restrictedCircleDimensions[idx][0], restrictedCircleDimensions[idx][1]);
}
// Else we can assume that it is backgroundSquares
uint16[2][4] memory restrictedSquareDimensions = [[1150, 50], [1100, 125], [1275, 200], [1300, 150]];
idx = SeedPhraseUtils._next(random, 0, restrictedSquareDimensions.length);
return (restrictedSquareDimensions[idx][0], restrictedSquareDimensions[idx][1]);
}
function _getStrokeStyle(
bool showStroke,
string memory color,
string memory opacity,
uint8 customStrokeWeight
) internal pure returns (bytes memory strokeStyle) {
if (showStroke) {
strokeStyle = abi.encodePacked(
" style='stroke-opacity:",
opacity,
";stroke:",
color,
";stroke-width:",
customStrokeWeight.toString(),
"' "
);
return strokeStyle;
}
}
function _getPalette(Random memory random, Attrs memory attributes) internal pure returns (Colors memory) {
string[6] memory selectedPallet;
uint8[6] memory lumosity;
if (attributes.greyscale) {
selectedPallet = ["#f8f9fa", "#c3c4c4", "#909091", "#606061", "#343435", "#0a0a0b"];
lumosity = [249, 196, 144, 96, 52, 10];
} else {
uint256 randPalette = SeedPhraseUtils._next(random, 0, 25);
if (randPalette == 0) {
selectedPallet = ["#ffe74c", "#ff5964", "#ffffff", "#6bf178", "#35a7ff", "#5b3758"];
lumosity = [225, 125, 255, 204, 149, 65];
} else if (randPalette == 1) {
selectedPallet = ["#ff0000", "#ff8700", "#e4ff33", "#a9ff1f", "#0aefff", "#0a33ff"];
lumosity = [54, 151, 235, 221, 191, 57];
} else if (randPalette == 2) {
selectedPallet = ["#f433ab", "#cb04a5", "#934683", "#65334d", "#2d1115", "#e0e2db"];
lumosity = [101, 58, 91, 64, 23, 225];
} else if (randPalette == 3) {
selectedPallet = ["#f08700", "#f6aa28", "#f9d939", "#00a6a6", "#bbdef0", "#23556c"];
lumosity = [148, 177, 212, 131, 216, 76];
} else if (randPalette == 4) {
selectedPallet = ["#f7e6de", "#e5b59e", "#cb7d52", "#bb8f77", "#96624a", "#462b20"];
lumosity = [233, 190, 138, 151, 107, 48];
} else if (randPalette == 5) {
selectedPallet = ["#f61379", "#d91cbc", "#da81ee", "#5011e4", "#4393ef", "#8edef6"];
lumosity = [75, 80, 156, 46, 137, 207];
} else if (randPalette == 6) {
selectedPallet = ["#010228", "#006aa3", "#005566", "#2ac1df", "#82dded", "#dbf5fa"];
lumosity = [5, 88, 68, 163, 203, 240];
} else if (randPalette == 7) {
selectedPallet = ["#f46036", "#5b85aa", "#414770", "#372248", "#171123", "#f7f5fb"];
lumosity = [124, 127, 73, 41, 20, 246];
} else if (randPalette == 8) {
selectedPallet = ["#393d3f", "#fdfdff", "#c6c5b9", "#62929e", "#546a7b", "#c52233"];
lumosity = [60, 253, 196, 137, 103, 70];
} else if (randPalette == 9) {
selectedPallet = ["#002626", "#0e4749", "#95c623", "#e55812", "#efe7da", "#8ddbe0"];
lumosity = [30, 59, 176, 113, 232, 203];
} else if (randPalette == 10) {
selectedPallet = ["#03071e", "#62040d", "#d00000", "#e85d04", "#faa307", "#ffcb47"];
lumosity = [8, 25, 44, 116, 170, 205];
} else if (randPalette == 11) {
selectedPallet = ["#f56a00", "#ff931f", "#ffd085", "#20003d", "#7b2cbf", "#c698eb"];
lumosity = [128, 162, 213, 11, 71, 168];
} else if (randPalette == 12) {
selectedPallet = ["#800016", "#ffffff", "#ff002b", "#407ba7", "#004e89", "#00043a"];
lumosity = [29, 255, 57, 114, 66, 7];
} else if (randPalette == 13) {
selectedPallet = ["#d6d6d6", "#f9f7dc", "#ffee32", "#ffd100", "#202020", "#6c757d"];
lumosity = [214, 245, 228, 204, 32, 116];
} else if (randPalette == 14) {
selectedPallet = ["#fff5d6", "#ccc5b9", "#403d39", "#252422", "#eb5e28", "#bb4111"];
lumosity = [245, 198, 61, 36, 120, 87];
} else if (randPalette == 15) {
selectedPallet = ["#0c0f0a", "#ff206e", "#fbff12", "#41ead4", "#6c20fd", "#ffffff"];
lumosity = [14, 85, 237, 196, 224, 255];
} else if (randPalette == 16) {
selectedPallet = ["#fdd8d8", "#f67979", "#e51010", "#921314", "#531315", "#151315"];
lumosity = [224, 148, 61, 46, 33, 20];
} else if (randPalette == 17) {
selectedPallet = ["#000814", "#002752", "#0066cc", "#f5bc00", "#ffd60a", "#ffee99"];
lumosity = [7, 34, 88, 187, 208, 235];
} else if (randPalette == 18) {
selectedPallet = ["#010b14", "#022d4f", "#fdfffc", "#2ec4b6", "#e71d36", "#ff990a"];
lumosity = [10, 38, 254, 163, 74, 164];
} else if (randPalette == 19) {
selectedPallet = ["#fd650d", "#d90368", "#820263", "#291720", "#06efa9", "#0d5943"];
lumosity = [127, 56, 36, 27, 184, 71];
} else if (randPalette == 20) {
selectedPallet = ["#002914", "#005200", "#34a300", "#70e000", "#aef33f", "#e0ff85"];
lumosity = [31, 59, 128, 184, 215, 240];
} else if (randPalette == 21) {
selectedPallet = ["#001413", "#fafffe", "#6f0301", "#a92d04", "#f6b51d", "#168eb6"];
lumosity = [16, 254, 26, 68, 184, 119];
} else if (randPalette == 22) {
selectedPallet = ["#6a1f10", "#d53e20", "#f7d1ca", "#c4f3fd", "#045362", "#fffbfa"];
lumosity = [46, 92, 217, 234, 67, 252];
} else if (randPalette == 23) {
selectedPallet = ["#6b42ff", "#a270ff", "#dda1f7", "#ffd6eb", "#ff8fb2", "#f56674"];
lumosity = [88, 133, 180, 224, 169, 133];
} else if (randPalette == 24) {
selectedPallet = ["#627132", "#273715", "#99a271", "#fefae1", "#e0a35c", "#bf6b21"];
lumosity = [105, 49, 157, 249, 171, 120];
}
}
// Randomize pallet order here...
return _shufflePallet(random, selectedPallet, lumosity, attributes);
}
function _shufflePallet(
Random memory random,
string[6] memory hexColors,
uint8[6] memory lumaValues,
Attrs memory attributes
) internal pure returns (Colors memory) {
// Shuffle colors and luma values with the same index
for (uint8 i = 0; i < hexColors.length; i++) {
// n = Pick random i > (array length - i)
uint256 n = i + SeedPhraseUtils._next(random, 0, (hexColors.length - i));
// temp = Temporarily store value from array[n]
string memory tempHex = hexColors[n];
uint8 tempLuma = lumaValues[n];
// Swap n value with i value
hexColors[n] = hexColors[i];
hexColors[i] = tempHex;
lumaValues[n] = lumaValues[i];
lumaValues[i] = tempLuma;
}
Colors memory pallet = Colors({
background: hexColors[0],
panel: hexColors[1],
panel2: "", // panel2 should match selected circles
panelStroke: hexColors[2],
selectedCircleStroke: hexColors[2], // Match panel stroke
negativeCircleStroke: hexColors[3],
negativeCircleFill: hexColors[4],
selectedCircleFill: hexColors[5],
selectedCircleFill2: "", // should match panel1
backgroundCircle: "",
blackOrWhite: lumaValues[0] < 150 ? "#fff" : "#000",
dynamicOpacity: lumaValues[0] < 150 ? "0.08" : "0.04"
});
if (attributes.doublePanel) {
pallet.panel2 = pallet.selectedCircleFill;
pallet.selectedCircleFill2 = pallet.panel;
}
if (attributes.bigBackgroundCircle) {
// Set background circle colors here
pallet.backgroundCircle = pallet.background;
pallet.background = pallet.panel;
// Luma based on 'new background', previous background is used for bgCircleColor)
pallet.blackOrWhite = lumaValues[1] < 150 ? "#fff" : "#000";
pallet.dynamicOpacity = lumaValues[1] < 150 ? "0.08" : "0.04";
}
return pallet;
}
/// @notice get an random number between (min and max) using seed and offseting bits
/// this function assumes that max is never bigger than 0xffffff (hex color with opacity included)
/// @dev this function is simply used to get random number using a seed.
/// if does bitshifting operations to try to reuse the same seed as much as possible.
/// should be enough for anyth
/// @param random the randomizer
/// @param min the minimum
/// @param max the maximum
/// @return result the resulting pseudo random number
function _next(
Random memory random,
uint256 min,
uint256 max
) internal pure returns (uint256 result) {
uint256 newSeed = random.seed;
uint256 newOffset = random.offsetBit + 3;
uint256 maxOffset = 4;
uint256 mask = 0xf;
if (max > 0xfffff) {
mask = 0xffffff;
maxOffset = 24;
} else if (max > 0xffff) {
mask = 0xfffff;
maxOffset = 20;
} else if (max > 0xfff) {
mask = 0xffff;
maxOffset = 16;
} else if (max > 0xff) {
mask = 0xfff;
maxOffset = 12;
} else if (max > 0xf) {
mask = 0xff;
maxOffset = 8;
}
// if offsetBit is too high to get the max number
// just get new seed and restart offset to 0
if (newOffset > (256 - maxOffset)) {
newOffset = 0;
newSeed = uint256(keccak256(abi.encode(newSeed)));
}
uint256 offseted = (newSeed >> newOffset);
uint256 part = offseted & mask;
result = min + (part % (max - min));
random.seed = newSeed;
random.offsetBit = newOffset;
}
function _boolPercentage(Random memory random, uint256 percentage) internal pure returns (bool) {
// E.G. If percentage = 30, and random = 0-29 we return true
// Percentage = 1, random = 0 (TRUE)
return (SeedPhraseUtils._next(random, 0, 100) < percentage);
}
/// @param random source of randomness (based on tokenSeed)
/// @param attributes art attributes
/// @return the json
function render(SeedPhraseUtils.Random memory random, SeedPhraseUtils.Attrs memory attributes)
external
pure
returns (string memory)
{
// Get color pallet
SeedPhraseUtils.Colors memory pallet = SeedPhraseUtils._getPalette(random, attributes);
// Start SVG (viewbox & static patterns)
bytes memory svg = abi.encodePacked(
"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1600 1600'><path fill='",
pallet.background,
"' ",
SeedPhraseUtils._getStrokeStyle(attributes.border, pallet.blackOrWhite, "0.3", 50),
" d='M0 0h1600v1600H0z'/>",
" <pattern id='panelCircles' x='0' y='0' width='.25' height='.1' patternUnits='objectBoundingBox'>",
"<circle cx='50' cy='50' r='40' fill='",
pallet.negativeCircleFill,
"' ",
SeedPhraseUtils._getStrokeStyle(attributes.showStroke, pallet.negativeCircleStroke, "1", strokeWeight),
" /></pattern>"
);
// Render optional patterns (grid OR background circles)
if (attributes.backgroundCircles) {
svg = abi.encodePacked(
svg,
"<pattern id='backgroundCircles' x='0' y='0' width='100' height='100'",
" patternUnits='userSpaceOnUse'><circle cx='50' cy='50' r='40' fill='",
pallet.blackOrWhite,
"' style='fill-opacity: ",
pallet.dynamicOpacity,
";'></circle></pattern><path fill='url(#backgroundCircles)' d='M0 0h1600v1600H0z'/>"
);
} else if (attributes.showGrid) {
svg = abi.encodePacked(
svg,
"<pattern id='grid' x='0' y='0' width='100' height='100'",
" patternUnits='userSpaceOnUse'><rect x='0' y='0' width='100' height='100' fill='none' ",
SeedPhraseUtils._getStrokeStyle(true, pallet.blackOrWhite, pallet.dynamicOpacity, strokeWeight),
" /></pattern><path fill='url(#grid)' d='M0 0h1600v1600H0z'/>"
);
}
if (attributes.bigBackgroundCircle) {
(uint16 shapeSize, uint16 stroke) = SeedPhraseUtils._backgroundShapeSizing(random, attributes);
// uint16 centerCircle = (viewBox / 2); // Viewbox = 1600, Center = 800
svg = abi.encodePacked(
svg,
"<circle cx='800' cy='800' r='",
(shapeSize / 2).toString(),
"' fill='",
pallet.backgroundCircle,
"' stroke='",
pallet.negativeCircleStroke,
"' style='stroke-width:",
stroke.toString(),
";stroke-opacity:0.3'/>"
);
} else if (attributes.backgroundSquare) {
(uint16 shapeSize, uint16 stroke) = SeedPhraseUtils._backgroundShapeSizing(random, attributes);
uint16 centerSquare = ((viewBox - shapeSize) / 2);
svg = abi.encodePacked(
svg,
"<rect x='",
centerSquare.toString(),
"' y='",
centerSquare.toString(),
"' width='",
shapeSize.toString(),
"' height='",
shapeSize.toString(),
"' fill='",
pallet.backgroundCircle,
"' stroke='",
pallet.negativeCircleStroke,
"' style='stroke-width:",
stroke.toString(),
";stroke-opacity:0.3'/>"
);
}
// Double panel (only if holder has burned two tokens from the defined pairings)
if (attributes.doublePanel) {
(uint8[4] memory firstBipIndexArray, string memory firstBipIndexStr) = SeedPhraseUtils._transformTokenId(
attributes.bipWordId
);
(uint8[4] memory secondBipIndexArray, string memory secondBipIndexStr) = SeedPhraseUtils._transformTokenId(
attributes.secondBipWordId
);
svg = abi.encodePacked(
svg,
_renderSinglePanel(firstBipIndexArray, attributes, pallet, doublePanel1X, false),
_renderSinglePanel(secondBipIndexArray, attributes, pallet, doublePanel2X, true)
);
// Create text
bytes memory combinedText = abi.encodePacked(firstBipIndexStr, " - #", secondBipIndexStr);
svg = abi.encodePacked(
svg,
SeedPhraseUtils._renderText(string(combinedText), pallet.blackOrWhite),
"</svg>"
);
}
// Single Panel
else {
(uint8[4] memory bipIndexArray, string memory bipIndexStr) = SeedPhraseUtils._transformTokenId(
attributes.bipWordId
);
svg = abi.encodePacked(svg, _renderSinglePanel(bipIndexArray, attributes, pallet, singlePanelX, false));
// Add closing text and svg element
svg = abi.encodePacked(svg, SeedPhraseUtils._renderText(bipIndexStr, pallet.blackOrWhite), "</svg>");
}
return string(svg);
}
function _renderSinglePanel(
uint8[4] memory bipIndexArray,
SeedPhraseUtils.Attrs memory attributes,
SeedPhraseUtils.Colors memory pallet,
uint16 panelX,
bool secondPanel
) internal pure returns (bytes memory panelSvg) {
// Draw panels
bool squareEdges = (attributes.doublePanel && attributes.backgroundSquare);
if (attributes.showPanel) {
panelSvg = abi.encodePacked(
"<rect x='",
(panelX - padding).toString(),
"' y='",
(panelY - padding).toString(),
"' width='",
(panelWidth + (padding * 2)).toString(),
"' height='",
(panelHeight + (padding * 2)).toString(),
"' rx='",
(squareEdges ? 0 : radius).toString(),
"' fill='",
(secondPanel ? pallet.panel2 : pallet.panel),
"' ",
SeedPhraseUtils._getStrokeStyle(attributes.showStroke, pallet.panelStroke, "1", strokeWeight),
"/>"
);
}
// Fill panel with negative circles, should resemble M600 300h400v1000H600z
panelSvg = abi.encodePacked(
panelSvg,
"<path fill='url(#panelCircles)' d='M",
panelX.toString(),
" ",
panelY.toString(),
"h",
panelWidth.toString(),
"v",
panelHeight.toString(),
"H",
panelX.toString(),
"z'/>"
);
// Draw selected circles
panelSvg = abi.encodePacked(
panelSvg,
_renderSelectedCircles(bipIndexArray, pallet, attributes.showStroke, panelX, secondPanel)
);
}
function _renderSelectedCircles(
uint8[4] memory bipIndexArray,
SeedPhraseUtils.Colors memory pallet,
bool showStroke,
uint16 panelX,
bool secondPanel
) internal pure returns (bytes memory svg) {
for (uint8 i = 0; i < bipIndexArray.length; i++) {
svg = abi.encodePacked(
svg,
"<circle cx='",
(panelX + (segmentSize * i) + radius).toString(),
"' cy='",
(panelY + (segmentSize * bipIndexArray[i]) + radius).toString(),
"' r='41' fill='", // Increase the size a tiny bit here (+1) to hide negative circle outline
(secondPanel ? pallet.selectedCircleFill2 : pallet.selectedCircleFill),
"' ",
SeedPhraseUtils._getStrokeStyle(showStroke, pallet.selectedCircleStroke, "1", strokeWeight),
" />"
);
}
}
function getRarityRating(bytes32 tokenSeed) external pure returns (uint8) {
SeedPhraseUtils.Random memory random = SeedPhraseUtils.Random({ seed: uint256(tokenSeed), offsetBit: 0 });
(, uint8 rarityRating) = SeedPhraseUtils.tokenTraits(SeedPhraseUtils.tokenAttributes(0, 0, random, 0));
return rarityRating;
}
function getTraitsAndAttributes(
uint16 bipWordId,
uint16 secondBipWordId,
uint8 rarityValue,
SeedPhraseUtils.Random memory random
) external pure returns (bytes memory, SeedPhraseUtils.Attrs memory) {
SeedPhraseUtils.Attrs memory attributes = SeedPhraseUtils.tokenAttributes(
bipWordId,
secondBipWordId,
random,
rarityValue
);
(bytes memory traits, ) = SeedPhraseUtils.tokenTraits(attributes);
return (traits, attributes);
}
function getKarma(IKarmaScore karma, bytes memory data, address account) external view returns (uint256) {
if (data.length > 0) {
(, uint256 karmaScore, ) = abi.decode(data, (address, uint256, bytes32[]));
if (karma.verify(account, karmaScore, data)) {
return account == address(0) ? 1000 : karmaScore;
}
}
return 1000;
}
function shuffleBipWords(uint256 randomValue) external pure returns (uint16[] memory) {
uint16 size = 2048;
uint16[] memory result = new uint16[](size);
// Initialize array.
for (uint16 i = 0; i < size; i++) {
result[i] = i + 1;
}
// Set the initial randomness based on the provided entropy from VRF.
bytes32 random = keccak256(abi.encodePacked(randomValue));
// Set the last item of the array which will be swapped.
uint16 lastItem = size - 1;
// We need to do `size - 1` iterations to completely shuffle the array.
for (uint16 i = 1; i < size - 1; i++) {
// Select a number based on the randomness.
uint16 selectedItem = uint16(uint256(random) % lastItem);
// Swap items `selected_item <> last_item`.
(result[lastItem], result[selectedItem]) = (result[selectedItem], result[lastItem]);
// Decrease the size of the possible shuffle
// to preserve the already shuffled items.
// The already shuffled items are at the end of the array.
lastItem--;
// Generate new randomness.
random = keccak256(abi.encodePacked(random));
}
return result;
}
function getDescriptionPt1() internal pure returns (string memory) {
return "\"Seed Phrase is a 'Crypto Native' *fully* on-chain collection.\\n\\nA '*SEED*' is unique, it represents a single word from the BIP-0039 word list (the most commonly used word list to generate a seed/recovery phrase, think of it as a dictionary that only holds 2048 words).\\n\\n***Your 'SEED*' = *Your 'WORD*' in the list.** \\nClick [here](https://www.seedphrase.codes/token?id=";
}
function getDescriptionPt2() internal pure returns (string memory) {
return ") to decipher *your 'SEED*' and find out which word it translates to!\\n\\nFor Licensing, T&Cs or any other info, please visit: [www.seedphrase.codes](https://www.seedphrase.codes/).\"";
}
function getTokenURI(string memory output, bytes memory traits, uint256 tokenId) external pure returns (string memory) {
return string(
abi.encodePacked(
"data:application/json;base64,",
NilProtocolUtils.base64encode(
bytes(
string(
abi.encodePacked(
'{"name": "Seed Phrase #',
NilProtocolUtils.stringify(tokenId),
'", "image": "data:image/svg+xml;base64,',
NilProtocolUtils.base64encode(bytes(output)),
'", "attributes": ',
traits,
', "description": ',
getDescriptionPt1(),
tokenId.toString(),
getDescriptionPt2(),
"}"
)
)
)
)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(
address owner,
address spender
)
external
view
returns (
uint256 remaining
);
function approve(
address spender,
uint256 value
)
external
returns (
bool success
);
function balanceOf(
address owner
)
external
view
returns (
uint256 balance
);
function decimals()
external
view
returns (
uint8 decimalPlaces
);
function decreaseApproval(
address spender,
uint256 addedValue
)
external
returns (
bool success
);
function increaseApproval(
address spender,
uint256 subtractedValue
) external;
function name()
external
view
returns (
string memory tokenName
);
function symbol()
external
view
returns (
string memory tokenSymbol
);
function totalSupply()
external
view
returns (
uint256 totalTokensIssued
);
function transfer(
address to,
uint256 value
)
external
returns (
bool success
);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
)
external
returns (
bool success
);
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (
bool success
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
)
internal
pure
returns (
uint256
)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash,
uint256 _vRFInputSeed
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "../interfaces/IN.sol";
import "../interfaces/INilPass.sol";
import "../interfaces/IPricingStrategy.sol";
/**
* @title NilPassCore contract
* @author Tony Snark
* @notice This contract provides basic functionalities to allow minting using the NilPass
* @dev This contract should be used only for testing or testnet deployments
*/
abstract contract NilPassCore is ERC721Enumerable, ReentrancyGuard, AccessControl, INilPass, IPricingStrategy {
uint128 public constant MAX_MULTI_MINT_AMOUNT = 32;
uint128 public constant MAX_N_TOKEN_ID = 8888;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN");
bytes32 public constant DAO_ROLE = keccak256("DAO");
IN public immutable n;
uint16 public reserveMinted;
uint256 public mintedOutsideNRange;
address public masterMint;
DerivativeParameters public derivativeParams;
uint128 maxTokenId;
struct DerivativeParameters {
bool onlyNHolders;
bool supportsTokenId;
uint16 reservedAllowance;
uint128 maxTotalSupply;
uint128 maxMintAllowance;
}
event Minted(address to, uint256 tokenId);
/**
* @notice Construct an NilPassCore instance
* @param name Name of the token
* @param symbol Symbol of the token
* @param n_ Address of your n instance (only for testing)
* @param derivativeParams_ Parameters describing the derivative settings
* @param masterMint_ Address of the master mint contract
* @param dao_ Address of the NIL DAO
*/
constructor(
string memory name,
string memory symbol,
IN n_,
DerivativeParameters memory derivativeParams_,
address masterMint_,
address dao_
) ERC721(name, symbol) {
derivativeParams = derivativeParams_;
require(derivativeParams.maxTotalSupply > 0, "NilPass:INVALID_SUPPLY");
require(
!derivativeParams.onlyNHolders ||
(derivativeParams.onlyNHolders && derivativeParams.maxTotalSupply <= MAX_N_TOKEN_ID),
"NilPass:INVALID_SUPPLY"
);
require(derivativeParams.maxTotalSupply >= derivativeParams.reservedAllowance, "NilPass:INVALID_ALLOWANCE");
require(masterMint_ != address(0), "NilPass:INVALID_MASTERMINT");
require(dao_ != address(0), "NilPass:INVALID_DAO");
n = n_;
masterMint = masterMint_;
derivativeParams.maxMintAllowance = derivativeParams.maxMintAllowance < MAX_MULTI_MINT_AMOUNT
? derivativeParams.maxMintAllowance
: MAX_MULTI_MINT_AMOUNT;
maxTokenId = derivativeParams.maxTotalSupply > MAX_N_TOKEN_ID
? derivativeParams.maxTotalSupply
: MAX_N_TOKEN_ID;
_setupRole(ADMIN_ROLE, msg.sender);
_setupRole(DAO_ROLE, dao_);
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
_setRoleAdmin(DAO_ROLE, DAO_ROLE);
}
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, msg.sender), "Nil:ACCESS_DENIED");
_;
}
modifier onlyDAO() {
require(hasRole(DAO_ROLE, msg.sender), "Nil:ACCESS_DENIED");
_;
}
/**
* @notice Allow anyone to mint a token with the supply id if this pass is unrestricted.
* n token holders can use this function without using the n token holders allowance,
* this is useful when the allowance is fully utilized.
*/
function mint(
address,
uint8,
uint256,
bytes calldata
) public virtual override nonReentrant {
require(false, "MINTING DISABLED");
}
/**
* @notice Allow anyone to mint multiple tokens with the provided IDs if this pass is unrestricted.
* n token holders can use this function without using the n token holders allowance,
* this is useful when the allowance is fully utilized.
*/
function mintTokenId(
address,
uint256[] calldata,
uint256,
bytes calldata
) public virtual override nonReentrant {
require(false, "MINTING DISABLED");
}
/**
* @notice Allow a n token holder to bulk mint tokens with id of their n tokens' id
*/
function mintWithN(
address,
uint256[] calldata,
uint256,
bytes calldata
) public virtual override nonReentrant {
require(false, "MINTING DISABLED");
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`
*/
function _safeMint(address to, uint256 tokenId) internal virtual override {
require(msg.sender == masterMint, "NilPass:INVALID_MINTER");
super._safeMint(to, tokenId);
emit Minted(to, tokenId);
}
/**
* @notice Set the exclusivity flag to only allow N holders to mint
* @param status Boolean to enable or disable N holder exclusivity
*/
function setOnlyNHolders(bool status) public onlyAdmin {
derivativeParams.onlyNHolders = status;
}
/**
* @notice Calculate the currently available number of reserved tokens for n token holders
* @return Reserved mint available
*/
function nHoldersMintsAvailable() public view returns (uint256) {
return derivativeParams.reservedAllowance - reserveMinted;
}
/**
* @notice Calculate the currently available number of open mints
* @return Open mint available
*/
function openMintsAvailable() public view returns (uint256) {
uint256 maxOpenMints = derivativeParams.maxTotalSupply - derivativeParams.reservedAllowance;
uint256 currentOpenMints = totalSupply() - reserveMinted;
return maxOpenMints - currentOpenMints;
}
/**
* @notice Calculate the total available number of mints
* @return total mint available
*/
function totalMintsAvailable() public view virtual override returns (uint256) {
return nHoldersMintsAvailable() + openMintsAvailable();
}
function mintParameters() external view override returns (INilPass.MintParams memory) {
return
INilPass.MintParams({
reservedAllowance: derivativeParams.reservedAllowance,
maxTotalSupply: derivativeParams.maxTotalSupply,
openMintsAvailable: openMintsAvailable(),
totalMintsAvailable: totalMintsAvailable(),
nHoldersMintsAvailable: nHoldersMintsAvailable(),
nHolderPriceInWei: getNextPriceForNHoldersInWei(1, address(0x1), ""),
openPriceInWei: getNextPriceForOpenMintInWei(1, address(0x1), ""),
totalSupply: totalSupply(),
onlyNHolders: derivativeParams.onlyNHolders,
maxMintAllowance: derivativeParams.maxMintAllowance,
supportsTokenId: derivativeParams.supportsTokenId
});
}
/**
* @notice Check if a token with an Id exists
* @param tokenId The token Id to check for
*/
function tokenExists(uint256 tokenId) external view override returns (bool) {
return _exists(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Enumerable, IERC165, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function maxTotalSupply() external view override returns (uint256) {
return derivativeParams.maxTotalSupply;
}
function reservedAllowance() public view returns (uint16) {
return derivativeParams.reservedAllowance;
}
function getNextPriceForNHoldersInWei(
uint256 numberOfMints,
address account,
bytes memory data
) public view virtual override returns (uint256);
function getNextPriceForOpenMintInWei(
uint256 numberOfMints,
address account,
bytes memory data
) public view virtual override returns (uint256);
function canMint(address account, bytes calldata data) external view virtual override returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface INilPass is IERC721Enumerable {
struct MintParams {
uint256 reservedAllowance;
uint256 maxTotalSupply;
uint256 nHoldersMintsAvailable;
uint256 openMintsAvailable;
uint256 totalMintsAvailable;
uint256 nHolderPriceInWei;
uint256 openPriceInWei;
uint256 totalSupply;
uint256 maxMintAllowance;
bool onlyNHolders;
bool supportsTokenId;
}
function mint(
address recipient,
uint8 amount,
uint256 paid,
bytes calldata data
) external;
function mintTokenId(
address recipient,
uint256[] calldata tokenIds,
uint256 paid,
bytes calldata data
) external;
function mintWithN(
address recipient,
uint256[] calldata tokenIds,
uint256 paid,
bytes calldata data
) external;
function totalMintsAvailable() external view returns (uint256);
function maxTotalSupply() external view returns (uint256);
function mintParameters() external view returns (MintParams memory);
function tokenExists(uint256 tokenId) external view returns (bool);
function canMint(address account, bytes calldata data) external view returns (bool);
function nUsed(uint256 nid) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
interface IPricingStrategy {
/**
* @notice Returns the next price for an N mint
*/
function getNextPriceForNHoldersInWei(
uint256 numberOfMints,
address account,
bytes memory data
) external view returns (uint256);
/**
* @notice Returns the next price for an open mint
*/
function getNextPriceForOpenMintInWei(
uint256 numberOfMints,
address account,
bytes memory data
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
| get an random number between (min and max) using seed and offseting bits this function assumes that max is never bigger than 0xffffff (hex color with opacity included) this function is simply used to get random number using a seed. if does bitshifting operations to try to reuse the same seed as much as possible. should be enough for anyth random the randomizer min the minimum max the maximum return result the resulting pseudo random number if offsetBit is too high to get the max number just get new seed and restart offset to 0 | function _next(
Random memory random,
uint256 min,
uint256 max
) internal pure returns (uint256 result) {
uint256 newSeed = random.seed;
uint256 newOffset = random.offsetBit + 3;
uint256 maxOffset = 4;
uint256 mask = 0xf;
if (max > 0xfffff) {
mask = 0xffffff;
maxOffset = 24;
mask = 0xfffff;
maxOffset = 20;
mask = 0xffff;
maxOffset = 16;
mask = 0xfff;
maxOffset = 12;
mask = 0xff;
maxOffset = 8;
}
if (newOffset > (256 - maxOffset)) {
newOffset = 0;
newSeed = uint256(keccak256(abi.encode(newSeed)));
}
uint256 offseted = (newSeed >> newOffset);
uint256 part = offseted & mask;
result = min + (part % (max - min));
random.seed = newSeed;
random.offsetBit = newOffset;
}
| 6,394,629 |
./full_match/1/0xF895B67031670F4b2D00a08a67a7A5c80F8E829f/sources/contracts/protocols/base/FeesV1.sol | Gives MAX allowance to token spender token address to apporve spender address | function _approveToken(address token, address spender) internal {
IERC20 _token = IERC20(token);
if (shouldResetAllowance[token]) {
_token.safeApprove(spender, 0);
_token.safeApprove(spender, type(uint256).max);
} else if (_token.allowance(address(this), spender) > 0) return;
else {
_token.safeApprove(spender, type(uint256).max);
}
}
| 8,417,204 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
contract EtherWallet {
// variable feeds
address payable public owner;
mapping(address => uint) private userBalances;
bool internal locked;
// constructor
constructor(address payable _owner) {
owner = _owner;
}
// modifiers
modifier noReentrant() {
require(!locked, "no re entrancy");
locked = true;
_;
locked = false;
}
modifier onlyOwner() {
require(owner == msg.sender, "need to be owner");
_;
}
// events
event Deposit(address indexed Depositor, uint amount);
event Sent(uint amount);
event Receive(address indexed Depositor, uint amount);
event Fallback(address indexed Depositor, uint amount);
// ---------- start app ---------- \\
// deposit fund
function deposit() payable public {
emit Deposit(msg.sender, msg.value);
}
// symbolic old fund transfering
function send(address payable to, uint amount) public {
if(msg.sender == owner) {
to.transfer(amount);
emit Sent(amount);
return;
}
revert("sender is not allowed");
}
// safe & secure transfer method
function withdraw() public noReentrant onlyOwner {
uint amountToWithdraw = userBalances[msg.sender];
userBalances[msg.sender] = 0;
(bool success, ) = msg.sender.call{value: amountToWithdraw}("");
require(success);
}
// watch how many fund deposited
function balanceOf() view public returns(uint) {
return address(this).balance;
}
// deposit OPCODE methods
receive() external payable {
emit Receive(msg.sender, msg.value);
}
fallback() external payable {
emit Fallback(msg.sender, msg.value);
}
}
| watch how many fund deposited | function balanceOf() view public returns(uint) {
return address(this).balance;
}
| 6,378,520 |
./partial_match/1/0xCd73e4322Ee1D0a7d01D2A471eBB464dA90454cc/sources/ERC721Psi.sol | Mapping from token ID to owner address | {
using Address for address;
using Strings for uint256;
using BitMaps for BitMaps.BitMap;
BitMaps.BitMap private _batchHead;
string private _name;
string private _symbol;
mapping(uint256 => address) internal _owners;
uint256 internal _minted;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
______ _____ _____ ______ ___ __ _ _ _
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721Psi: balance query for the zero address"
);
uint256 count;
for (uint256 i; i < _minted; ++i) {
if (_exists(i)) {
if (owner == ownerOf(i)) {
++count;
}
}
}
return count;
}
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721Psi: balance query for the zero address"
);
uint256 count;
for (uint256 i; i < _minted; ++i) {
if (_exists(i)) {
if (owner == ownerOf(i)) {
++count;
}
}
}
return count;
}
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721Psi: balance query for the zero address"
);
uint256 count;
for (uint256 i; i < _minted; ++i) {
if (_exists(i)) {
if (owner == ownerOf(i)) {
++count;
}
}
}
return count;
}
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721Psi: balance query for the zero address"
);
uint256 count;
for (uint256 i; i < _minted; ++i) {
if (_exists(i)) {
if (owner == ownerOf(i)) {
++count;
}
}
}
return count;
}
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
(address owner, uint256 tokenIdBatchHead) = _ownerAndBatchHeadOf(
tokenId
);
return owner;
}
function _ownerAndBatchHeadOf(uint256 tokenId)
internal
view
returns (address owner, uint256 tokenIdBatchHead)
{
require(
_exists(tokenId),
"ERC721Psi: owner query for nonexistent token"
);
tokenIdBatchHead = _getBatchHead(tokenId);
owner = _owners[tokenIdBatchHead];
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "ERC721Psi: URI query for nonexistent token");
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
function _baseURI() internal view virtual returns (string memory) {
return "";
}
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721Psi: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721Psi: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721Psi: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721Psi: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Psi: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Psi: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, 1, _data),
"ERC721Psi: transfer to non ERC721Receiver implementer"
);
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId < _minted;
}
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721Psi: operator query for nonexistent token"
);
address owner = ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 quantity) internal virtual {
_safeMint(to, quantity, "");
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
uint256 startTokenId = _minted;
_mint(to, quantity);
require(
_checkOnERC721Received(
address(0),
to,
startTokenId,
quantity,
_data
),
"ERC721Psi: transfer to non ERC721Receiver implementer"
);
}
function _mint(address to, uint256 quantity) internal virtual {
uint256 tokenIdBatchHead = _minted;
require(quantity > 0, "ERC721Psi: quantity must be greater 0");
require(to != address(0), "ERC721Psi: mint to the zero address");
_beforeTokenTransfers(address(0), to, tokenIdBatchHead, quantity);
_minted += quantity;
_owners[tokenIdBatchHead] = to;
_batchHead.set(tokenIdBatchHead);
_afterTokenTransfers(address(0), to, tokenIdBatchHead, quantity);
for (
uint256 tokenId = tokenIdBatchHead;
tokenId < tokenIdBatchHead + quantity;
tokenId++
) {
emit Transfer(address(0), to, tokenId);
}
}
function _mint(address to, uint256 quantity) internal virtual {
uint256 tokenIdBatchHead = _minted;
require(quantity > 0, "ERC721Psi: quantity must be greater 0");
require(to != address(0), "ERC721Psi: mint to the zero address");
_beforeTokenTransfers(address(0), to, tokenIdBatchHead, quantity);
_minted += quantity;
_owners[tokenIdBatchHead] = to;
_batchHead.set(tokenIdBatchHead);
_afterTokenTransfers(address(0), to, tokenIdBatchHead, quantity);
for (
uint256 tokenId = tokenIdBatchHead;
tokenId < tokenIdBatchHead + quantity;
tokenId++
) {
emit Transfer(address(0), to, tokenId);
}
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
(address owner, uint256 tokenIdBatchHead) = _ownerAndBatchHeadOf(
tokenId
);
require(owner == from, "ERC721Psi: transfer of token that is not own");
require(to != address(0), "ERC721Psi: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId);
uint256 nextTokenId = tokenId + 1;
if (!_batchHead.get(nextTokenId) && nextTokenId < _minted) {
_owners[nextTokenId] = from;
_batchHead.set(nextTokenId);
}
_owners[tokenId] = to;
if (tokenId != tokenIdBatchHead) {
_batchHead.set(tokenId);
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
(address owner, uint256 tokenIdBatchHead) = _ownerAndBatchHeadOf(
tokenId
);
require(owner == from, "ERC721Psi: transfer of token that is not own");
require(to != address(0), "ERC721Psi: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId);
uint256 nextTokenId = tokenId + 1;
if (!_batchHead.get(nextTokenId) && nextTokenId < _minted) {
_owners[nextTokenId] = from;
_batchHead.set(nextTokenId);
}
_owners[tokenId] = to;
if (tokenId != tokenIdBatchHead) {
_batchHead.set(tokenId);
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
(address owner, uint256 tokenIdBatchHead) = _ownerAndBatchHeadOf(
tokenId
);
require(owner == from, "ERC721Psi: transfer of token that is not own");
require(to != address(0), "ERC721Psi: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId);
uint256 nextTokenId = tokenId + 1;
if (!_batchHead.get(nextTokenId) && nextTokenId < _minted) {
_owners[nextTokenId] = from;
_batchHead.set(nextTokenId);
}
_owners[tokenId] = to;
if (tokenId != tokenIdBatchHead) {
_batchHead.set(tokenId);
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint256 startTokenId,
uint256 quantity,
bytes memory _data
) private returns (bool r) {
if (to.isContract()) {
r = true;
for (
uint256 tokenId = startTokenId;
tokenId < startTokenId + quantity;
tokenId++
) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
r =
r &&
retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert(
"ERC721Psi: transfer to non ERC721Receiver implementer"
);
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
return r;
return true;
}
}
function _checkOnERC721Received(
address from,
address to,
uint256 startTokenId,
uint256 quantity,
bytes memory _data
) private returns (bool r) {
if (to.isContract()) {
r = true;
for (
uint256 tokenId = startTokenId;
tokenId < startTokenId + quantity;
tokenId++
) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
r =
r &&
retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert(
"ERC721Psi: transfer to non ERC721Receiver implementer"
);
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
return r;
return true;
}
}
function _checkOnERC721Received(
address from,
address to,
uint256 startTokenId,
uint256 quantity,
bytes memory _data
) private returns (bool r) {
if (to.isContract()) {
r = true;
for (
uint256 tokenId = startTokenId;
tokenId < startTokenId + quantity;
tokenId++
) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
r =
r &&
retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert(
"ERC721Psi: transfer to non ERC721Receiver implementer"
);
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
return r;
return true;
}
}
function _checkOnERC721Received(
address from,
address to,
uint256 startTokenId,
uint256 quantity,
bytes memory _data
) private returns (bool r) {
if (to.isContract()) {
r = true;
for (
uint256 tokenId = startTokenId;
tokenId < startTokenId + quantity;
tokenId++
) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
r =
r &&
retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert(
"ERC721Psi: transfer to non ERC721Receiver implementer"
);
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
return r;
return true;
}
}
} catch (bytes memory reason) {
function _checkOnERC721Received(
address from,
address to,
uint256 startTokenId,
uint256 quantity,
bytes memory _data
) private returns (bool r) {
if (to.isContract()) {
r = true;
for (
uint256 tokenId = startTokenId;
tokenId < startTokenId + quantity;
tokenId++
) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
r =
r &&
retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert(
"ERC721Psi: transfer to non ERC721Receiver implementer"
);
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
return r;
return true;
}
}
} else {
function _checkOnERC721Received(
address from,
address to,
uint256 startTokenId,
uint256 quantity,
bytes memory _data
) private returns (bool r) {
if (to.isContract()) {
r = true;
for (
uint256 tokenId = startTokenId;
tokenId < startTokenId + quantity;
tokenId++
) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
r =
r &&
retval == IERC721Receiver.onERC721Received.selector;
if (reason.length == 0) {
revert(
"ERC721Psi: transfer to non ERC721Receiver implementer"
);
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
return r;
return true;
}
}
} else {
function _getBatchHead(uint256 tokenId)
internal
view
returns (uint256 tokenIdBatchHead)
{
tokenIdBatchHead = _batchHead.scanForward(tokenId);
}
function totalSupply() public view virtual override returns (uint256) {
return _minted;
}
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(index < totalSupply(), "ERC721Psi: global index out of bounds");
uint256 count;
for (uint256 i; i < _minted; i++) {
if (_exists(i)) {
if (count == index) return i;
else count++;
}
}
}
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(index < totalSupply(), "ERC721Psi: global index out of bounds");
uint256 count;
for (uint256 i; i < _minted; i++) {
if (_exists(i)) {
if (count == index) return i;
else count++;
}
}
}
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(index < totalSupply(), "ERC721Psi: global index out of bounds");
uint256 count;
for (uint256 i; i < _minted; i++) {
if (_exists(i)) {
if (count == index) return i;
else count++;
}
}
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256 tokenId)
{
uint256 count;
for (uint256 i; i < _minted; i++) {
if (_exists(i) && owner == ownerOf(i)) {
if (count == index) return i;
else count++;
}
}
revert("ERC721Psi: owner index out of bounds");
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256 tokenId)
{
uint256 count;
for (uint256 i; i < _minted; i++) {
if (_exists(i) && owner == ownerOf(i)) {
if (count == index) return i;
else count++;
}
}
revert("ERC721Psi: owner index out of bounds");
}
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256 tokenId)
{
uint256 count;
for (uint256 i; i < _minted; i++) {
if (_exists(i) && owner == ownerOf(i)) {
if (count == index) return i;
else count++;
}
}
revert("ERC721Psi: owner index out of bounds");
}
) internal virtual {}
) internal virtual {}
}
| 4,434,848 |
// SPDX-License-Identifier: BSD-2-Clause
// SwingingMarketMaker.sol
// Copyright (c) 2021 Giry SAS. All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
pragma solidity ^0.8.10;
pragma abicoder v2;
import "../../Persistent.sol";
contract Mango is Persistent {
using P.Offer for P.Offer.t;
using P.OfferDetail for P.OfferDetail.t;
event BidAtMaxPosition(address quote, address base, uint offerId);
event AskAtMinPosition(address quote, address base, uint offerId);
event Initialized(uint from, uint to);
/** Immutables */
// total number of Asks (resp. Bids)
uint16 public immutable NSLOTS;
// initial min price given by `QUOTE_0/BASE_0`
uint96 immutable BASE_0;
uint96 immutable QUOTE_0;
address public immutable BASE;
address public immutable QUOTE;
/** Mutables */
//NB if one wants to allow this contract to be multi-makers one should use uint[][] ASKS/BIDS and allocate a new array for each maker.
uint[] ASKS;
uint[] BIDS;
mapping(uint => uint) index_of_bid; // bidId -> index
mapping(uint => uint) index_of_ask; // askId -> index
//NB if one wants to allow this contract to be multi-makers one should use uint[] for each mutable fields to allow user specific parameters.
int current_shift;
// price increment is current_delta / BASE_0
uint current_delta; // quote increment
// triggers `__boundariesReached__` whenever amounts of bids/asks is below `current_min_offer_type`
uint current_min_offer_type;
// whether the strat reneges on offers
bool paused = false;
// Base and quote token treasuries
address current_base_treasury;
address current_quote_treasury;
constructor(
address payable mgv,
address base,
address quote,
uint base_0,
uint quote_0,
uint nslots,
uint delta
) MangroveOffer(mgv) {
// sanity check
require(
nslots > 0 &&
mgv != address(0) &&
uint16(nslots) == nslots &&
uint96(base_0) == base_0 &&
uint96(quote_0) == quote_0,
"Mango/constructor/invalidArguments"
);
BASE = base;
QUOTE = quote;
NSLOTS = uint16(nslots);
ASKS = new uint[](nslots);
BIDS = new uint[](nslots);
BASE_0 = uint96(base_0);
QUOTE_0 = uint96(quote_0);
current_delta = delta;
current_min_offer_type = 1;
current_quote_treasury = msg.sender;
current_base_treasury = msg.sender;
OFR_GASREQ = 400_000; // dry run OK with 200_000
}
function initialize(
uint lastBidPosition, // [0,..,lastBidPosition] are bids
bool withBase,
uint from, // slice (from included)
uint to, // to index excluded
uint[][2] calldata pivotIds, // `pivotIds[0][i]` ith pivots for bids, `pivotIds[1][i]` ith pivot for asks
uint[] calldata tokenAmounts
) public mgvOrAdmin {
/** Initializing Asks and Bids */
/** NB we assume Mangrove is already provisioned for posting NSLOTS asks and NSLOTS bids*/
/** NB cannot post newOffer with infinite gasreq since fallback OFR_GASREQ is not defined yet (and default is likely wrong) */
require(
to > from && pivotIds[0].length == to - from,
"Mango/initialize/invalidSlice"
);
require(
tokenAmounts.length == to - from,
"Mango/initialize/invalidBaseAmounts"
);
require(lastBidPosition < NSLOTS - 1, "Mango/initialize/NoSlotForAsks"); // bidding => slice doesn't fill the book
uint i;
for (i = from; i < to; i++) {
if (i <= lastBidPosition) {
uint bidPivot = pivotIds[0][i - from];
bidPivot = bidPivot > 0
? bidPivot // taking pivot from the user
: i > 0
? BIDS[i - 1]
: 0; // otherwise getting last inserted offer as pivot
updateBid({
index: i,
withBase: withBase,
reset: true, // overwrites old value
amount: tokenAmounts[i - from],
pivotId: bidPivot
});
} else {
uint askPivot = pivotIds[1][i - from];
askPivot = askPivot > 0
? askPivot // taking pivot from the user
: i > 0
? ASKS[i - 1]
: 0; // otherwise getting last inserted offer as pivot
updateAsk({
index: i,
withBase: withBase,
reset: true,
amount: tokenAmounts[i - from],
pivotId: askPivot
});
}
}
emit Initialized({from: from, to: to});
}
/** Sets the account from which base (resp. quote) tokens need to be fetched or put during trade execution*/
function set_treasury(bool base, address treasury) external onlyAdmin {
require(treasury != address(0), "Mango/set_treasury/zeroAddress");
if (base) {
current_base_treasury = treasury;
} else {
current_quote_treasury = treasury;
}
}
function get_treasury(bool base) external view onlyAdmin returns (address) {
return base ? current_base_treasury : current_quote_treasury;
}
/** Deposits received tokens into the corresponding treasury*/
function __put__(uint amount, MgvLib.SingleOrder calldata order)
internal
virtual
override
returns (uint)
{
if (order.inbound_tkn == BASE && current_base_treasury != address(this)) {
return IERC20(BASE).transfer(current_base_treasury, amount) ? 0 : amount;
}
if (current_quote_treasury != address(this)) {
return
IERC20(QUOTE).transfer(current_quote_treasury, amount) ? 0 : amount;
}
// order.inbound_tkn has to be either BASE or QUOTE so only possibility is `this` is treasury
return 0;
}
/** Fetches required tokens from the corresponding treasury*/
function __get__(uint amount, MgvLib.SingleOrder calldata order)
internal
virtual
override
returns (uint)
{
if (order.outbound_tkn == BASE && current_base_treasury != address(this)) {
return
IERC20(BASE).transferFrom(current_base_treasury, address(this), amount)
? 0
: amount;
}
if (current_quote_treasury != address(this)) {
return
IERC20(QUOTE).transferFrom(
current_quote_treasury,
address(this),
amount
)
? 0
: amount;
}
// order.outbound_tkn has to be either BASE or QUOTE so only possibility is `this` is treasury
return 0;
}
// with ba=0:bids only, ba=1: asks only ba>1 all
function retractOffers(
uint ba,
uint from,
uint to
) external onlyAdmin returns (uint collected) {
for (uint i = from; i < to; i++) {
if (ba > 0) {
collected += ASKS[i] > 0
? retractOfferInternal(BASE, QUOTE, ASKS[i], true)
: 0;
}
if (ba == 0 || ba > 1) {
collected += BIDS[i] > 0
? retractOfferInternal(QUOTE, BASE, BIDS[i], true)
: 0;
}
}
}
/** Setters and getters */
function get_delta() external view onlyAdmin returns (uint) {
return current_delta;
}
function set_delta(uint delta) public mgvOrAdmin {
current_delta = delta;
}
function get_shift() external view onlyAdmin returns (int) {
return current_shift;
}
/** Shift the price (induced by quote amount) of n slots down or up */
/** price at position i will be shifted (up or down depending on the sign of `shift`) */
/** New positions 0<= i < s are initialized with amount[i] in base tokens if `withBase`. In quote tokens otherwise*/
function set_shift(
int s,
bool withBase,
uint[] calldata amounts
) public mgvOrAdmin {
require(
amounts.length == (s < 0 ? uint(-s) : uint(s)),
"Mango/set_shift/notEnoughAmounts"
);
if (s < 0) {
negative_shift(uint(-s), withBase, amounts);
} else {
positive_shift(uint(s), withBase, amounts);
}
}
function set_min_offer_type(uint m) public mgvOrAdmin {
current_min_offer_type = m;
}
// return Mango offer Ids on Mangrove. If `liveOnly` will only return offer Ids that are live (0 otherwise).
function get_offers(bool liveOnly)
external
view
returns (uint[][2] memory offers)
{
offers[0] = new uint[](NSLOTS);
offers[1] = new uint[](NSLOTS);
for (uint i = 0; i < NSLOTS; i++) {
uint askId = ASKS[index_of_position(i)];
uint bidId = BIDS[index_of_position(i)];
offers[0][i] = (MGV.offers(QUOTE, BASE, bidId).gives() > 0 || !liveOnly)
? BIDS[index_of_position(i)]
: 0;
offers[1][i] = (MGV.offers(BASE, QUOTE, askId).gives() > 0 || !liveOnly)
? ASKS[index_of_position(i)]
: 0;
}
}
// starts reneging all offers
// NB reneged offers will not be reposted
function pause() public mgvOrAdmin {
paused = true;
}
function restart() external onlyAdmin {
paused = false;
}
function __lastLook__(MgvLib.SingleOrder calldata order)
internal
virtual
override
returns (bool proceed)
{
order; //shh
proceed = !paused;
}
function writeOffer(
uint index,
address outbound_tkn,
address inbound_tkn,
uint wants,
uint gives,
uint pivotId
) internal {
inbound_tkn; // shh
if (outbound_tkn == BASE) {
// Asks
if (ASKS[index] == 0) {
// offer slot not initialized yet
ASKS[index] = newOfferInternal({
outbound_tkn: BASE,
inbound_tkn: QUOTE,
wants: wants,
gives: gives,
gasreq: OFR_GASREQ,
gasprice: 0,
pivotId: pivotId,
provision: 0
});
index_of_ask[ASKS[index]] = index;
} else {
updateOfferInternal({
outbound_tkn: BASE,
inbound_tkn: QUOTE,
wants: wants,
gives: gives,
gasreq: OFR_GASREQ,
gasprice: 0,
pivotId: pivotId,
provision: 0,
offerId: ASKS[index]
});
}
if (position_of_index(index) <= current_min_offer_type) {
__boundariesReached__(false, ASKS[index]);
}
} else {
// Bids
if (BIDS[index] == 0) {
BIDS[index] = newOfferInternal({
outbound_tkn: QUOTE,
inbound_tkn: BASE,
wants: wants,
gives: gives,
gasreq: OFR_GASREQ,
gasprice: 0,
pivotId: pivotId,
provision: 0
});
index_of_bid[BIDS[index]] = index;
} else {
updateOfferInternal({
outbound_tkn: QUOTE,
inbound_tkn: BASE,
wants: wants,
gives: gives,
gasreq: OFR_GASREQ,
gasprice: 0,
pivotId: pivotId,
provision: 0,
offerId: BIDS[index]
});
}
if (position_of_index(index) >= NSLOTS - 1 - current_min_offer_type) {
__boundariesReached__(true, BIDS[index]);
}
}
}
// returns the value of x in the ring [0,m]
// i.e if x>=0 this is just x % m
// if x<0 this is m + (x % m)
function modulo(int x, uint m) internal pure returns (uint) {
if (x >= 0) {
return uint(x) % m;
} else {
return uint(int(m) + (x % int(m)));
}
}
/** Minimal amount of quotes for the general term of the `__quote_progression__` */
/** If min price was not shifted this is just `QUOTE_0` */
/** In general this is QUOTE_0 + shift*delta */
function quote_min() internal view returns (uint) {
int qm = int(uint(QUOTE_0)) + current_shift * int(current_delta);
require(qm > 0, "Mango/quote_min/ShiftUnderflow");
return (uint(qm));
}
/** Returns the position in the order book of the offer associated to this index `i` */
function position_of_index(uint i) internal view returns (uint) {
// position(i) = (i+shift) % N
return modulo(int(i) - current_shift, NSLOTS);
}
/** Returns the index in the ring of offers at which the offer Id at position `p` in the book is stored */
function index_of_position(uint p) internal view returns (uint) {
return modulo(int(p) + current_shift, NSLOTS);
}
/**Next index in the ring of offers */
function next_index(uint i) internal view returns (uint) {
return (i + 1) % NSLOTS;
}
/**Previous index in the ring of offers */
function prev_index(uint i) internal view returns (uint) {
return i > 0 ? i - 1 : NSLOTS - 1;
}
/** Function that determines the amount of quotes that are offered at position i of the OB depending on initial_price and paramater delta*/
/** Here the default is an arithmetic progression */
function __quote_progression__(uint position)
internal
view
virtual
returns (uint)
{
return current_delta * position + quote_min();
}
/** Returns the quantity of quote tokens for an offer at position `p` given an amount of Base tokens (eq. 2)*/
function quotes_of_position(uint p, uint base_amount)
internal
view
returns (uint)
{
return (__quote_progression__(p) * base_amount) / BASE_0;
}
/** Returns the quantity of base tokens for an offer at position `p` given an amount of quote tokens (eq. 3)*/
function bases_of_position(uint p, uint quote_amount)
internal
view
returns (uint)
{
return (quote_amount * BASE_0) / __quote_progression__(p);
}
/** Recenter the order book by shifting min price up `s` positions in the book */
/** As a consequence `s` Bids will be cancelled and `s` new asks will be posted */
function positive_shift(
uint s,
bool withBase,
uint[] calldata amounts
) internal {
require(s < NSLOTS, "Mango/shift/positiveShiftTooLarge");
uint index = index_of_position(0);
current_shift += int(s); // updating new shift
// Warning: from now on position_of_index reflects the new shift
// One must progress relative to index when retracting offers
uint cpt = 0;
while (cpt < s) {
// slots occupied by [Bids[index],..,Bids[index+`s` % N]] are retracted
if (BIDS[index] != 0) {
retractOfferInternal({
outbound_tkn: QUOTE,
inbound_tkn: BASE,
offerId: BIDS[index],
deprovision: false
});
}
// slots are replaced by `s` Asks.
// NB the price of Ask[index] is computed given the new position associated to `index`
// because the shift has been updated above
// `pos` is the offer position in the OB (not the array)
uint pos = position_of_index(index);
uint new_gives;
uint new_wants;
if (withBase) {
new_gives = quotes_of_position(pos, amounts[cpt]);
new_wants = amounts[cpt];
} else {
new_wants = bases_of_position(pos, amounts[cpt]);
new_gives = amounts[cpt];
}
writeOffer({
index: index,
outbound_tkn: BASE,
inbound_tkn: QUOTE,
wants: new_wants,
gives: new_gives,
pivotId: pos > 0 ? ASKS[index_of_position(pos - 1)] : 0
});
cpt++;
index = next_index(index);
}
}
/** Recenter the order book by shifting max price down `s` positions in the book */
/** As a consequence `s` Asks will be cancelled and `s` new Bids will be posted */
function negative_shift(
uint s,
bool withBase,
uint[] calldata amounts
) internal {
require(s < NSLOTS, "Mango/shift/NegativeShiftTooLarge");
uint index = index_of_position(NSLOTS - 1);
current_shift -= int(s); // updating new shift
// Warning: from now on position_of_index reflects the new shift
// One must progress relative to index when retracting offers
uint cpt;
while (cpt < s) {
// slots occupied by [Asks[index-`s` % N],..,Asks[index]] are retracted
if (ASKS[index] != 0) {
retractOfferInternal({
outbound_tkn: BASE,
inbound_tkn: QUOTE,
offerId: ASKS[index],
deprovision: false
});
}
// slots are replaced by `s` Bids.
// NB the price of Bids[index] is computed given the new position associated to `index`
// because the shift has been updated above
// `pos` is the offer position in the OB (not the array)
uint pos = position_of_index(index);
uint new_gives;
uint new_wants;
if (withBase) {
new_wants = amounts[cpt];
new_gives = quotes_of_position(pos, amounts[cpt]);
} else {
new_wants = bases_of_position(pos, amounts[cpt]);
new_gives = amounts[cpt];
}
writeOffer({
index: index,
outbound_tkn: QUOTE,
inbound_tkn: BASE,
wants: new_wants,
gives: new_gives,
pivotId: pos < NSLOTS - 1 ? BIDS[index_of_position(pos + 1)] : 0
});
cpt++;
index = prev_index(index);
}
}
// for reposting partial filled offers one always gives the residual (default behavior)
// and adapts wants to the new price (if different).
function __residualWants__(MgvLib.SingleOrder calldata order)
internal
virtual
override
returns (uint)
{
if (order.outbound_tkn == BASE) {
// Ask offer (wants QUOTE)
uint index = index_of_ask[order.offerId];
uint residual_base = __residualGives__(order); // default
if (residual_base == 0) {
return 0;
}
return quotes_of_position(position_of_index(index), residual_base);
} else {
// Bid order (wants BASE)
uint index = index_of_bid[order.offerId];
uint residual_quote = __residualGives__(order); // default
if (residual_quote == 0) {
return 0;
}
return bases_of_position(position_of_index(index), residual_quote);
}
}
/** Define what to do when the AMM boundaries are reached (either when reposting a bid or a ask) */
function __boundariesReached__(bool bid, uint offerId) internal virtual {
if (bid) {
emit BidAtMaxPosition(QUOTE, BASE, offerId);
} else {
emit AskAtMinPosition(BASE, QUOTE, offerId);
}
}
function __posthookSuccess__(MgvLib.SingleOrder calldata order)
internal
virtual
override
{
// reposting residual of offer using override `__newWants__` and default `__newGives` for new price
super.__posthookSuccess__(order);
if (order.outbound_tkn == BASE) {
// Ask Offer (`this` contract just sold some BASE @ pos)
uint index = index_of_ask[order.offerId];
if (index == 0) {
// offer was posted using newOffer, not during initialization
return;
}
uint pos = position_of_index(index);
// bid for some BASE token with the received QUOTE tokens @ pos-1
if (pos > 0) {
updateBid({
index: index_of_position(pos - 1),
withBase: false,
reset: false, // top up old value with received amount
amount: order.gives,
pivotId: 0
});
} else {
// Ask cannot be at Pmin unless a shift has eliminated all bids
emit PosthookFail(
order.outbound_tkn,
order.inbound_tkn,
order.offerId,
"Mango/posthook/BuyingOutOfPriceRange"
);
return;
}
} else {
// Bid offer (`this` contract just bought some BASE)
uint index = index_of_bid[order.offerId];
if (index == 0) {
// offer was posted using newOffer, not during initialization
return;
}
uint pos = position_of_index(index);
// ask for some QUOTE tokens in exchange of the received BASE tokens @ pos+1
if (pos < NSLOTS - 1) {
updateAsk({
index: index_of_position(pos + 1),
withBase: true,
reset: false, // top up old value with received amount
amount: order.gives,
pivotId: 0
});
} else {
// Take profit
emit PosthookFail(
order.outbound_tkn,
order.inbound_tkn,
order.offerId,
"Mango/posthook/SellingOutOfPriceRange"
);
return;
}
}
}
function updateBid(
uint index,
bool withBase,
bool reset,
uint amount,
uint pivotId
) internal {
// outbound : QUOTE, inbound: BASE
P.Offer.t offer = MGV.offers(QUOTE, BASE, BIDS[index]);
uint position = position_of_index(index);
uint new_wants;
uint new_gives;
if (withBase) {
// amount: BASE
new_wants = reset ? amount : amount + offer.wants();
new_gives = quotes_of_position(position, new_wants);
} else {
new_gives = reset ? amount : amount + offer.gives();
new_wants = bases_of_position(position, new_gives);
}
uint pivot;
if (offer.gives() == 0) {
// offer was not live
if (pivotId != 0) {
pivot = pivotId;
} else {
if (position > 0) {
pivot = BIDS[index_of_position(position - 1)]; // if this offer is no longer in the book will start form best
} else {
pivot = offer.prev(); // trying previous offer on Mangrove as a pivot
}
}
} else {
// offer is live, so reusing its id for pivot
pivot = BIDS[index];
}
writeOffer({
index: index,
outbound_tkn: QUOTE,
inbound_tkn: BASE,
wants: new_wants,
gives: new_gives,
pivotId: pivot
});
}
function updateAsk(
uint index,
bool withBase,
bool reset,
uint amount,
uint pivotId
) internal {
// outbound : BASE, inbound: QUOTE
P.Offer.t offer = MGV.offers(BASE, QUOTE, ASKS[index]);
uint position = position_of_index(index);
uint new_gives;
uint new_wants;
if (withBase) {
// amount: BASE
new_gives = reset ? amount : amount + offer.gives(); // in BASE
new_wants = quotes_of_position(position, new_gives);
} else {
new_wants = reset ? amount : amount + offer.wants(); // in QUOTES
new_gives = bases_of_position(position, new_wants);
}
uint pivot;
if (offer.gives() == 0) {
// offer was not live
if (pivotId != 0) {
pivot = pivotId;
} else {
if (position > 0) {
pivot = ASKS[index_of_position(position - 1)]; // if this offer is no longer in the book will start form best
} else {
pivot = offer.prev(); // trying previous offer on Mangrove as a pivot
}
}
} else {
// offer is live, so reusing its id for pivot
pivot = ASKS[index];
}
writeOffer({
index: index,
outbound_tkn: BASE,
inbound_tkn: QUOTE,
wants: new_wants,
gives: new_gives,
pivotId: pivot
});
}
}
| Asks offer slot not initialized yet Bids | function writeOffer(
uint index,
address outbound_tkn,
address inbound_tkn,
uint wants,
uint gives,
uint pivotId
) internal {
if (outbound_tkn == BASE) {
if (ASKS[index] == 0) {
ASKS[index] = newOfferInternal({
outbound_tkn: BASE,
inbound_tkn: QUOTE,
wants: wants,
gives: gives,
gasreq: OFR_GASREQ,
gasprice: 0,
pivotId: pivotId,
provision: 0
});
index_of_ask[ASKS[index]] = index;
updateOfferInternal({
outbound_tkn: BASE,
inbound_tkn: QUOTE,
wants: wants,
gives: gives,
gasreq: OFR_GASREQ,
gasprice: 0,
pivotId: pivotId,
provision: 0,
offerId: ASKS[index]
});
}
if (position_of_index(index) <= current_min_offer_type) {
__boundariesReached__(false, ASKS[index]);
}
if (BIDS[index] == 0) {
BIDS[index] = newOfferInternal({
outbound_tkn: QUOTE,
inbound_tkn: BASE,
wants: wants,
gives: gives,
gasreq: OFR_GASREQ,
gasprice: 0,
pivotId: pivotId,
provision: 0
});
index_of_bid[BIDS[index]] = index;
updateOfferInternal({
outbound_tkn: QUOTE,
inbound_tkn: BASE,
wants: wants,
gives: gives,
gasreq: OFR_GASREQ,
gasprice: 0,
pivotId: pivotId,
provision: 0,
offerId: BIDS[index]
});
}
if (position_of_index(index) >= NSLOTS - 1 - current_min_offer_type) {
__boundariesReached__(true, BIDS[index]);
}
}
}
| 12,701,460 |
./full_match/1/0xa1C7345503A008a9FdF660393A3a8F9448c61f2A/sources/contracts/Vault.sol | /// Initiates a deposit of want tokens to the vault. amountIn The amount of want tokens to deposit. receiver The address to receive vault tokens. calculate the shares based on the amount. | function deposit(uint256 amountIn, address receiver)
public
override
nonReentrant
ensureFeesAreCollected
returns (uint256 shares)
{
onlyBatcher();
isValidAddress(receiver);
require(amountIn > 0, "ZERO_AMOUNT");
shares = totalSupply() > 0
? (totalSupply() * amountIn) / totalVaultFunds()
: amountIn;
require(shares != 0, "ZERO_SHARES");
IERC20(wantToken).safeTransferFrom(msg.sender, address(this), amountIn);
_mint(receiver, shares);
}
| 3,153,945 |
./partial_match/1/0x9caBE9340644168Ede11AA65013DDF0D4bccF39B/sources/Roof.sol | Initializes the contract setting the deployer as the initial owner./ | function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function _afterTokenTransfer(
address from,
address to,
uint256 amount
}
constructor() {
_transferOwnership(_msgSender());
}
| 3,920,679 |
./partial_match/3/0xc4Db62b30448448c5C1F0c5B99570eD75AcaaBE9/sources/Distribute.sol | uint256 total = 77; for (uint256 i = 0; i < recipients.length; i++) { total += values[i%77]%(10(i+1))/(10i); } | function distributeToken(IERC20 token, address[] recipients, uint256[] values, uint256 total) external discountFUT {
require(token.transferFrom(msg.sender, address(this), total));
for (uint i = 1; i <= values.length; i++) {
uint256 value = values[i-1];
for (uint j = 0; j < 77; j++) {
require(token.transfer(recipients[i*j],value%10));
value /=10;
}
}
}
| 5,336,123 |